CheckIosAppStore.php 16 KB

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