CheckIosAppStore.php 16 KB

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