ImportService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. <?php
  2. namespace App\Services;
  3. use App\Models\ImportPost;
  4. use Cache;
  5. use DB;
  6. use Illuminate\Database\QueryException;
  7. class ImportService
  8. {
  9. const CACHE_KEY = 'pf:import-service:';
  10. public static function getId($userId, $year, $month, $day)
  11. {
  12. if ($userId > 999999) {
  13. return null;
  14. }
  15. if ($year < 9 || $year > (int) now()->addYear()->format('y')) {
  16. return null;
  17. }
  18. if ($month < 1 || $month > 12) {
  19. return null;
  20. }
  21. if ($day < 1 || $day > 31) {
  22. return null;
  23. }
  24. $start = 1;
  25. $maxAttempts = 10;
  26. for ($attempt = 0; $attempt < $maxAttempts; $attempt++) {
  27. try {
  28. return DB::transaction(function () use ($userId, $year, $month, $day, $start) {
  29. $maxExistingIncr = ImportPost::where('user_id', $userId)
  30. ->where('creation_year', $year)
  31. ->where('creation_month', $month)
  32. ->where('creation_day', $day)
  33. ->lockForUpdate()
  34. ->max('creation_id') ?? 0;
  35. $incr = $maxExistingIncr + 1;
  36. if ($incr > 999) {
  37. [$newYear, $newMonth, $newDay] = self::getNextValidDate($year, $month, $day);
  38. if (! $newYear) {
  39. throw new \Exception('Could not find valid next date');
  40. }
  41. return self::getId($userId, $newYear, $newMonth, $newDay);
  42. }
  43. $uid = str_pad($userId, 6, 0, STR_PAD_LEFT);
  44. $yearStr = str_pad($year, 2, 0, STR_PAD_LEFT);
  45. $monthStr = str_pad($month, 2, 0, STR_PAD_LEFT);
  46. $dayStr = str_pad($day, 2, 0, STR_PAD_LEFT);
  47. $zone = $yearStr.$monthStr.$dayStr.str_pad($incr, 3, 0, STR_PAD_LEFT);
  48. return [
  49. 'id' => $start.$uid.$zone,
  50. 'year' => $year,
  51. 'month' => $month,
  52. 'day' => $day,
  53. 'incr' => $incr,
  54. 'user_id' => $userId,
  55. ];
  56. }, 3);
  57. } catch (QueryException $e) {
  58. if ($e->getCode() === '40001') {
  59. usleep(random_int(1000, 10000));
  60. continue;
  61. }
  62. throw $e;
  63. } catch (\Exception $e) {
  64. if (strpos($e->getMessage(), 'Could not find valid next date') !== false) {
  65. return null;
  66. }
  67. throw $e;
  68. }
  69. }
  70. return null;
  71. }
  72. public static function getAndReserveId($userId, $year, $month, $day, $importPostData = [])
  73. {
  74. if ($userId > 999999) {
  75. return null;
  76. }
  77. if ($year < 9 || $year > (int) now()->addYear()->format('y')) {
  78. return null;
  79. }
  80. if ($month < 1 || $month > 12) {
  81. return null;
  82. }
  83. if ($day < 1 || $day > 31) {
  84. return null;
  85. }
  86. $start = 1;
  87. $maxAttempts = 10;
  88. for ($attempt = 0; $attempt < $maxAttempts; $attempt++) {
  89. try {
  90. return DB::transaction(function () use ($userId, $year, $month, $day, $start, $importPostData) {
  91. $maxExistingIncr = ImportPost::where('user_id', $userId)
  92. ->where('creation_year', $year)
  93. ->where('creation_month', $month)
  94. ->where('creation_day', $day)
  95. ->lockForUpdate()
  96. ->max('creation_id') ?? 0;
  97. $incr = $maxExistingIncr + 1;
  98. if ($incr > 999) {
  99. [$newYear, $newMonth, $newDay] = self::getNextValidDate($year, $month, $day);
  100. if (! $newYear) {
  101. throw new \Exception('Could not find valid next date');
  102. }
  103. return self::getAndReserveId($userId, $newYear, $newMonth, $newDay, $importPostData);
  104. }
  105. $uid = str_pad($userId, 6, 0, STR_PAD_LEFT);
  106. $yearStr = str_pad($year, 2, 0, STR_PAD_LEFT);
  107. $monthStr = str_pad($month, 2, 0, STR_PAD_LEFT);
  108. $dayStr = str_pad($day, 2, 0, STR_PAD_LEFT);
  109. $zone = $yearStr.$monthStr.$dayStr.str_pad($incr, 3, 0, STR_PAD_LEFT);
  110. $idData = [
  111. 'id' => $start.$uid.$zone,
  112. 'year' => $year,
  113. 'month' => $month,
  114. 'day' => $day,
  115. 'incr' => $incr,
  116. 'user_id' => $userId,
  117. ];
  118. $placeholder = new ImportPost(array_merge([
  119. 'user_id' => $userId,
  120. 'creation_year' => $year,
  121. 'creation_month' => $month,
  122. 'creation_day' => $day,
  123. 'creation_id' => $incr,
  124. 'reserved_at' => now(),
  125. ], $importPostData));
  126. $placeholder->save();
  127. return [
  128. 'id_data' => $idData,
  129. 'import_post' => $placeholder,
  130. ];
  131. }, 3);
  132. } catch (QueryException $e) {
  133. if ($e->getCode() === '40001') {
  134. usleep(random_int(1000, 10000));
  135. continue;
  136. }
  137. if ($e->getCode() === '23000') {
  138. usleep(random_int(100, 1000));
  139. continue;
  140. }
  141. throw $e;
  142. } catch (\Exception $e) {
  143. if (strpos($e->getMessage(), 'Could not find valid next date') !== false) {
  144. return null;
  145. }
  146. throw $e;
  147. }
  148. }
  149. return null;
  150. }
  151. public static function getUniqueCreationId($userId, $year, $month, $day, $excludeImportPostId = null)
  152. {
  153. return DB::transaction(function () use ($userId, $year, $month, $day, $excludeImportPostId) {
  154. $query = ImportPost::where('user_id', $userId)
  155. ->where('creation_year', $year)
  156. ->where('creation_month', $month)
  157. ->where('creation_day', $day)
  158. ->lockForUpdate();
  159. if ($excludeImportPostId) {
  160. $query->where('id', '!=', $excludeImportPostId);
  161. }
  162. $maxExistingIncr = $query->max('creation_id') ?? 0;
  163. $incr = $maxExistingIncr + 1;
  164. while ($incr <= 999) {
  165. $uid = str_pad($userId, 6, 0, STR_PAD_LEFT);
  166. $yearStr = str_pad($year, 2, 0, STR_PAD_LEFT);
  167. $monthStr = str_pad($month, 2, 0, STR_PAD_LEFT);
  168. $dayStr = str_pad($day, 2, 0, STR_PAD_LEFT);
  169. $zone = $yearStr.$monthStr.$dayStr.str_pad($incr, 3, 0, STR_PAD_LEFT);
  170. $statusId = '1'.$uid.$zone;
  171. $statusExists = DB::table('statuses')->where('id', $statusId)->exists();
  172. $importExists = ImportPost::where('user_id', $userId)
  173. ->where('creation_year', $year)
  174. ->where('creation_month', $month)
  175. ->where('creation_day', $day)
  176. ->where('creation_id', $incr)
  177. ->when($excludeImportPostId, function ($q) use ($excludeImportPostId) {
  178. return $q->where('id', '!=', $excludeImportPostId);
  179. })
  180. ->exists();
  181. if (! $statusExists && ! $importExists) {
  182. return [
  183. 'incr' => $incr,
  184. 'year' => $year,
  185. 'month' => $month,
  186. 'day' => $day,
  187. 'status_id' => $statusId,
  188. ];
  189. }
  190. $incr++;
  191. }
  192. [$newYear, $newMonth, $newDay] = self::getNextValidDate($year, $month, $day);
  193. if (! $newYear) {
  194. return null;
  195. }
  196. return self::getUniqueCreationId($userId, $newYear, $newMonth, $newDay, $excludeImportPostId);
  197. }, 3);
  198. }
  199. public static function getPostCount($profileId, $refresh = false)
  200. {
  201. $key = self::CACHE_KEY.'totalPostCountByProfileId:'.$profileId;
  202. if ($refresh) {
  203. Cache::forget($key);
  204. }
  205. return intval(Cache::remember($key, 21600, function () use ($profileId) {
  206. return ImportPost::whereProfileId($profileId)->whereSkipMissingMedia(false)->count();
  207. }));
  208. }
  209. public static function getAttempts($profileId)
  210. {
  211. $key = self::CACHE_KEY.'attemptsByProfileId:'.$profileId;
  212. return intval(Cache::remember($key, 21600, function () use ($profileId) {
  213. return ImportPost::whereProfileId($profileId)
  214. ->whereSkipMissingMedia(false)
  215. ->get()
  216. ->groupBy(function ($item) {
  217. return $item->created_at->format('Y-m-d');
  218. })
  219. ->count();
  220. }));
  221. }
  222. public static function clearAttempts($profileId)
  223. {
  224. $key = self::CACHE_KEY.'attemptsByProfileId:'.$profileId;
  225. return Cache::forget($key);
  226. }
  227. public static function getImportedFiles($profileId, $refresh = false)
  228. {
  229. $key = self::CACHE_KEY.'importedPostsByProfileId:'.$profileId;
  230. if ($refresh) {
  231. Cache::forget($key);
  232. }
  233. return Cache::remember($key, 21600, function () use ($profileId) {
  234. return ImportPost::whereProfileId($profileId)
  235. ->get()
  236. ->filter(function ($ip) {
  237. return StatusService::get($ip->status_id) == null;
  238. })
  239. ->map(function ($ip) {
  240. return collect($ip->media)->map(function ($m) {
  241. return $m['uri'];
  242. });
  243. })->values()->flatten();
  244. });
  245. }
  246. public static function clearImportedFiles($profileId)
  247. {
  248. $key = self::CACHE_KEY.'importedPostsByProfileId:'.$profileId;
  249. return Cache::forget($key);
  250. }
  251. private static function getNextValidDate($year, $month, $day)
  252. {
  253. try {
  254. $fullYear = $year < 50 ? 2000 + $year : 1900 + $year;
  255. $date = \Carbon\Carbon::createFromDate($fullYear, $month, $day);
  256. $nextDay = $date->addDay();
  257. $nextYear2Digit = (int) $nextDay->format('y');
  258. return [
  259. $nextYear2Digit,
  260. $nextDay->month,
  261. $nextDay->day,
  262. ];
  263. } catch (\Exception $e) {
  264. return [null, null, null];
  265. }
  266. }
  267. }