CheckIosAppStore.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Notification\TelegramBot;
  4. use App\Util;
  5. use Illuminate\Console\Command;
  6. use Illuminate\Support\Facades\Redis;
  7. /**
  8. * 检测配置的 iOS App Store 包是否被下架,若下架则通过 Telegram 通知。
  9. *
  10. * 规则:
  11. * 1. 优先使用 Apple lookup 接口检测:
  12. * https://itunes.apple.com/lookup?id={appId}&country={country}&entity=software
  13. *
  14. * 2. 状态分三类:
  15. * - online : 明确在线
  16. * - delisted : 明确下架/该区不可用
  17. * - unknown : 暂时无法判断(429、403、5xx、超时、网络错误等)
  18. *
  19. * 3. 连续确认:
  20. * - delisted 连续 N 次才发下架告警
  21. * - unknown 连续 N 次才发异常告警
  22. *
  23. * 4. online 会清除之前的连续计数
  24. */
  25. class CheckIosAppStore extends Command
  26. {
  27. protected $signature = 'ios:check-app-store';
  28. protected $description = '检测 iOS App Store 包是否被下架,下架时 Telegram 通知';
  29. /** 要检测的 iOS 包列表:name => url */
  30. protected array $apps = [
  31. 'Slots Magnet Revolution 206' => 'https://apps.apple.com/us/app/slots-magnet-revolution/id6759797102',
  32. 'Viking Mysteric Slots 207' => 'https://apps.apple.com/us/app/viking-mysteric-slots/id6759851510',
  33. 'Slots Chemistry Pirate 208' => 'https://apps.apple.com/us/app/slots-chemistry-pirate/id6759852588',
  34. // 'Mini Plinko Slot 227' => 'https://apps.apple.com/us/app/mini-plinko-slot/id6769709635',
  35. // 'ios test' => 'https://apps.apple.com/us/app/slots-chemistry-pirate/id67598525',
  36. // 'ceshi' => 'https://apps.apple.com/us/app/pixiepineslotsgrid/id6758513278',
  37. ];
  38. /**
  39. * 连续多少次确认“下架”才发告警
  40. */
  41. protected int $delistedConfirmTimes = 3;
  42. /**
  43. * 连续多少次确认“异常”才发告警
  44. */
  45. protected int $unknownConfirmTimes = 3;
  46. /**
  47. * Redis 计数过期时间(秒)
  48. * 比如每 10 分钟跑一次,3600 表示 1 小时窗口内累计
  49. */
  50. protected int $counterExpireSeconds = 3600;
  51. /**
  52. * 每次请求最大重试次数
  53. */
  54. protected int $httpMaxAttempts = 3;
  55. /**
  56. * 请求间随机抖动范围(微秒)
  57. */
  58. protected int $sleepMinMicroseconds = 200000; // 0.2 秒
  59. protected int $sleepMaxMicroseconds = 500000; // 0.5 秒
  60. public function handle()
  61. {
  62. $env = env('APP_ENV', 'local');
  63. $results = [];
  64. $delistedNotified = [];
  65. $unknownNotified = [];
  66. foreach ($this->apps as $name => $url) {
  67. $result = $this->checkSingleApp($name, $url);
  68. $results[] = $result;
  69. Util::WriteLog(
  70. 'ios_app_store_check',
  71. sprintf(
  72. '[%s] %s | %s | %s',
  73. strtoupper($result['status']),
  74. $name,
  75. $url,
  76. $result['reason']
  77. )
  78. );
  79. if ($result['status'] === 'online') {
  80. $this->clearCounters($result['app_id']);
  81. } elseif ($result['status'] === 'delisted') {
  82. $count = $this->increaseCounter($this->getDelistedCounterKey($result['app_id']));
  83. $this->clearCounter($this->getUnknownCounterKey($result['app_id']));
  84. if ($count >= $this->delistedConfirmTimes) {
  85. if (!$this->hasAlreadyNotified('delisted', $result['app_id'])) {
  86. $delistedNotified[] = [
  87. 'name' => $name,
  88. 'url' => $url,
  89. 'reason' => $result['reason'],
  90. 'count' => $count,
  91. ];
  92. $this->markNotified('delisted', $result['app_id']);
  93. }
  94. }
  95. } elseif ($result['status'] === 'unknown') {
  96. $count = $this->increaseCounter($this->getUnknownCounterKey($result['app_id']));
  97. $this->clearCounter($this->getDelistedCounterKey($result['app_id']));
  98. if ($count >= $this->unknownConfirmTimes) {
  99. if (!$this->hasAlreadyNotified('unknown', $result['app_id'])) {
  100. $unknownNotified[] = [
  101. 'name' => $name,
  102. 'url' => $url,
  103. 'reason' => $result['reason'],
  104. 'count' => $count,
  105. ];
  106. $this->markNotified('unknown', $result['app_id']);
  107. }
  108. }
  109. }
  110. // 请求间抖动,降低被 Apple 限流概率
  111. usleep(random_int($this->sleepMinMicroseconds, $this->sleepMaxMicroseconds));
  112. }
  113. if (!empty($delistedNotified)) {
  114. $this->notifyDelisted($env, $delistedNotified);
  115. $this->warn('已发送下架告警: ' . count($delistedNotified) . ' 个');
  116. }
  117. if (!empty($unknownNotified)) {
  118. $this->notifyUnknown($env, $unknownNotified);
  119. $this->warn('已发送检测异常告警: ' . count($unknownNotified) . ' 个');
  120. }
  121. foreach ($results as $item) {
  122. $this->line(sprintf(
  123. '[%s] %s - %s',
  124. strtoupper($item['status']),
  125. $item['name'],
  126. $item['reason']
  127. ));
  128. }
  129. if (empty($delistedNotified) && empty($unknownNotified)) {
  130. $this->info('本次检测完成,无需告警。');
  131. }
  132. return empty($delistedNotified) ? 0 : 1;
  133. }
  134. /**
  135. * 检测单个 App 状态
  136. *
  137. * 返回:
  138. * [
  139. * 'name' => string,
  140. * 'url' => string,
  141. * 'app_id' => string,
  142. * 'status' => 'online'|'delisted'|'unknown',
  143. * 'reason' => string,
  144. * ]
  145. */
  146. protected function checkSingleApp(string $name, string $appStoreUrl): array
  147. {
  148. $parsed = $this->parseAppStoreUrl($appStoreUrl);
  149. if (!$parsed) {
  150. return [
  151. 'name' => $name,
  152. 'url' => $appStoreUrl,
  153. 'app_id' => 'unknown',
  154. 'status' => 'unknown',
  155. 'reason' => '无法解析 App Store URL 中的国家或 App ID',
  156. ];
  157. }
  158. $country = $parsed['country'];
  159. $appId = $parsed['app_id'];
  160. $lookupUrl = sprintf(
  161. 'https://itunes.apple.com/lookup?id=%s&country=%s&entity=software',
  162. $appId,
  163. $country
  164. );
  165. $resp = $this->httpGetWithRetry($lookupUrl, $this->httpMaxAttempts);
  166. if (!empty($resp['error'])) {
  167. return [
  168. 'name' => $name,
  169. 'url' => $appStoreUrl,
  170. 'app_id' => $appId,
  171. 'status' => 'unknown',
  172. 'reason' => 'Lookup 请求失败: ' . $resp['error'],
  173. ];
  174. }
  175. $code = (int)($resp['code'] ?? 0);
  176. $body = (string)($resp['body'] ?? '');
  177. if ($code === 200) {
  178. $json = json_decode($body, true);
  179. if (!is_array($json)) {
  180. return [
  181. 'name' => $name,
  182. 'url' => $appStoreUrl,
  183. 'app_id' => $appId,
  184. 'status' => 'unknown',
  185. 'reason' => 'Lookup 返回非有效 JSON',
  186. ];
  187. }
  188. $resultCount = (int)($json['resultCount'] ?? 0);
  189. $results = $json['results'] ?? [];
  190. if ($resultCount <= 0 || empty($results)) {
  191. return [
  192. 'name' => $name,
  193. 'url' => $appStoreUrl,
  194. 'app_id' => $appId,
  195. 'status' => 'delisted',
  196. 'reason' => "Lookup 无结果(resultCount=0, country={$country}, appId={$appId})",
  197. ];
  198. }
  199. $app = $results[0];
  200. $trackId = (string)($app['trackId'] ?? '');
  201. $trackViewUrl = (string)($app['trackViewUrl'] ?? '');
  202. if ($trackId !== (string)$appId) {
  203. return [
  204. 'name' => $name,
  205. 'url' => $appStoreUrl,
  206. 'app_id' => $appId,
  207. 'status' => 'unknown',
  208. 'reason' => 'Lookup 返回结果异常:trackId 不匹配',
  209. ];
  210. }
  211. if ($trackViewUrl !== '' && stripos($trackViewUrl, "/{$country}/") === false) {
  212. return [
  213. 'name' => $name,
  214. 'url' => $appStoreUrl,
  215. 'app_id' => $appId,
  216. 'status' => 'online',
  217. 'reason' => 'Lookup 返回应用信息(国家链接与配置不一致,但应用存在)',
  218. ];
  219. }
  220. // 成功在线时,清掉已通知标记,这样未来再次异常还能重新通知
  221. $this->clearNotifiedFlags($appId);
  222. return [
  223. 'name' => $name,
  224. 'url' => $appStoreUrl,
  225. 'app_id' => $appId,
  226. 'status' => 'online',
  227. 'reason' => 'Lookup 正常返回应用信息',
  228. ];
  229. }
  230. // 这些不能直接判定为下架
  231. if (in_array($code, [403, 404, 429, 500, 502, 503, 504], true)) {
  232. return [
  233. 'name' => $name,
  234. 'url' => $appStoreUrl,
  235. 'app_id' => $appId,
  236. 'status' => 'unknown',
  237. 'reason' => "Lookup HTTP {$code}",
  238. ];
  239. }
  240. return [
  241. 'name' => $name,
  242. 'url' => $appStoreUrl,
  243. 'app_id' => $appId,
  244. 'status' => 'unknown',
  245. 'reason' => "Lookup HTTP {$code}",
  246. ];
  247. }
  248. /**
  249. * 从 App Store 链接中提取国家和 app id
  250. *
  251. * 示例:
  252. * https://apps.apple.com/us/app/slots-magnet-revolution/id6759797102
  253. */
  254. protected function parseAppStoreUrl(string $url): ?array
  255. {
  256. $pattern = '#https?://apps\.apple\.com/([a-z]{2})/app/.*/id(\d+)#i';
  257. if (!preg_match($pattern, $url, $matches)) {
  258. return null;
  259. }
  260. return [
  261. 'country' => strtolower($matches[1]),
  262. 'app_id' => $matches[2],
  263. ];
  264. }
  265. /**
  266. * GET 请求,带简单重试和退避
  267. *
  268. * 返回:
  269. * [
  270. * 'code' => int,
  271. * 'body' => string,
  272. * 'error' => string,
  273. * ]
  274. */
  275. protected function httpGetWithRetry(string $url, int $maxAttempts = 3): array
  276. {
  277. $attempt = 0;
  278. $last = [
  279. 'code' => 0,
  280. 'body' => '',
  281. 'error' => '',
  282. ];
  283. while ($attempt < $maxAttempts) {
  284. $attempt++;
  285. $ch = curl_init($url);
  286. curl_setopt_array($ch, [
  287. CURLOPT_RETURNTRANSFER => true,
  288. CURLOPT_FOLLOWLOCATION => true,
  289. CURLOPT_TIMEOUT => 20,
  290. CURLOPT_CONNECTTIMEOUT => 10,
  291. CURLOPT_SSL_VERIFYPEER => true,
  292. CURLOPT_HTTPHEADER => [
  293. 'Accept: application/json',
  294. 'Accept-Language: en-US,en;q=0.9',
  295. 'Cache-Control: no-cache',
  296. ],
  297. CURLOPT_USERAGENT => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
  298. ]);
  299. $body = curl_exec($ch);
  300. $code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
  301. $error = curl_error($ch);
  302. curl_close($ch);
  303. $last = [
  304. 'code' => $code,
  305. 'body' => is_string($body) ? $body : '',
  306. 'error' => $error ?: '',
  307. ];
  308. if ($last['error'] === '' && $code === 200) {
  309. return $last;
  310. }
  311. $shouldRetry = $last['error'] !== '' || in_array($code, [429, 500, 502, 503, 504], true);
  312. if (!$shouldRetry || $attempt >= $maxAttempts) {
  313. return $last;
  314. }
  315. if ($attempt == 1) {
  316. $sleepSeconds = 2;
  317. } elseif ($attempt == 2) {
  318. $sleepSeconds = 5;
  319. } else {
  320. $sleepSeconds = 8;
  321. }
  322. sleep($sleepSeconds);
  323. }
  324. return $last;
  325. }
  326. protected function getDelistedCounterKey(string $appId): string
  327. {
  328. return "ios:appstore:delisted:{$appId}";
  329. }
  330. protected function getUnknownCounterKey(string $appId): string
  331. {
  332. return "ios:appstore:unknown:{$appId}";
  333. }
  334. protected function getDelistedNotifiedKey(string $appId): string
  335. {
  336. return "ios:appstore:notified:delisted:{$appId}";
  337. }
  338. protected function getUnknownNotifiedKey(string $appId): string
  339. {
  340. return "ios:appstore:notified:unknown:{$appId}";
  341. }
  342. protected function increaseCounter(string $key): int
  343. {
  344. $count = (int) Redis::incr($key);
  345. Redis::expire($key, $this->counterExpireSeconds);
  346. return $count;
  347. }
  348. protected function clearCounters(string $appId): void
  349. {
  350. $this->clearCounter($this->getDelistedCounterKey($appId));
  351. $this->clearCounter($this->getUnknownCounterKey($appId));
  352. }
  353. protected function clearCounter(string $key): void
  354. {
  355. try {
  356. Redis::del($key);
  357. } catch (\Throwable $e) {
  358. Util::WriteLog('ios_app_store_check', 'Redis del error: ' . $e->getMessage());
  359. }
  360. }
  361. /**
  362. * 防止达到阈值后每次 cron 都重复发同类告警
  363. */
  364. protected function hasAlreadyNotified(string $type, string $appId): bool
  365. {
  366. try {
  367. $key = $type === 'delisted'
  368. ? $this->getDelistedNotifiedKey($appId)
  369. : $this->getUnknownNotifiedKey($appId);
  370. return (bool) Redis::exists($key);
  371. } catch (\Throwable $e) {
  372. Util::WriteLog('ios_app_store_check', 'Redis exists error: ' . $e->getMessage());
  373. return false;
  374. }
  375. }
  376. protected function markNotified(string $type, string $appId): void
  377. {
  378. try {
  379. $key = $type === 'delisted'
  380. ? $this->getDelistedNotifiedKey($appId)
  381. : $this->getUnknownNotifiedKey($appId);
  382. // 通知标记也设置一个过期,防止永远不恢复
  383. Redis::setex($key, $this->counterExpireSeconds, 1);
  384. } catch (\Throwable $e) {
  385. Util::WriteLog('ios_app_store_check', 'Redis setex error: ' . $e->getMessage());
  386. }
  387. }
  388. protected function clearNotifiedFlags(string $appId): void
  389. {
  390. try {
  391. Redis::del(
  392. $this->getDelistedNotifiedKey($appId),
  393. $this->getUnknownNotifiedKey($appId)
  394. );
  395. } catch (\Throwable $e) {
  396. Util::WriteLog('ios_app_store_check', 'Redis clear notified flags error: ' . $e->getMessage());
  397. }
  398. }
  399. protected function notifyDelisted(string $env, array $items): void
  400. {
  401. $lines = ["[{$env}] iOS App Store 下架检测告警"];
  402. foreach ($items as $item) {
  403. $lines[] = "• {$item['name']}";
  404. $lines[] = " 原因: {$item['reason']}";
  405. $lines[] = " 连续次数: {$item['count']}";
  406. $lines[] = " 链接: {$item['url']}";
  407. }
  408. $this->sendTelegramMessage(implode("\n", $lines));
  409. }
  410. protected function notifyUnknown(string $env, array $items): void
  411. {
  412. $lines = ["[{$env}] iOS App Store 检测异常告警"];
  413. foreach ($items as $item) {
  414. $lines[] = "• {$item['name']}";
  415. $lines[] = " 原因: {$item['reason']}";
  416. $lines[] = " 连续次数: {$item['count']}";
  417. $lines[] = " 链接: {$item['url']}";
  418. }
  419. $this->sendTelegramMessage(implode("\n", $lines));
  420. }
  421. protected function sendTelegramMessage(string $message): void
  422. {
  423. try {
  424. // TelegramBot::getDefault()->sendMsg($message);
  425. TelegramBot::getDefault()->sendMsgAndImportant($message);
  426. } catch (\Throwable $e) {
  427. Util::WriteLog('ios_app_store_check', 'Telegram send error: ' . $e->getMessage());
  428. $this->error('Telegram 发送失败: ' . $e->getMessage());
  429. }
  430. }
  431. }