CheckGooglePlayStore.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. * 定时检测 Google Play 上架包是否仍可访问(大致对应「未下架」)。
  9. *
  10. * 规则与 iOS 侧类似:
  11. * - online : HTTP 200 且页面含正常 Play 详情特征
  12. * - delisted : HTTP 404,或 200 但为 Play「Not Found」错误页
  13. * - unknown : 超时、429、5xx、页面过短无法判断等
  14. *
  15. * 连续 delisted / unknown 达阈值才告警;恢复 online 会清计数与已通知标记。
  16. */
  17. class CheckGooglePlayStore extends Command
  18. {
  19. protected $signature = 'google:check-play-store';
  20. protected $description = '检测 Google Play 包是否疑似下架,告警时 Telegram sendMsgAndImportant';
  21. /** 展示名 => Play 详情页完整 URL(须含 id= 包名) */
  22. protected array $apps = [
  23. 'google-AFVegas-Nights-228' => 'https://play.google.com/store/apps/details?id=com.oipjuwenkjhde.kjhbnmuiejnd',
  24. 'google-PrimeAF-Gaming-229' => 'https://play.google.com/store/apps/details?id=com.rewubsbdqkk.koeesowemli',
  25. 'google-test111' => 'https://play.google.com/store/apps/details?id=com.rewubsbdqkk.123',
  26. ];
  27. protected int $delistedConfirmTimes = 3;
  28. protected int $unknownConfirmTimes = 3;
  29. protected int $counterExpireSeconds = 3600;
  30. protected int $httpMaxAttempts = 3;
  31. protected int $sleepMinMicroseconds = 200000;
  32. protected int $sleepMaxMicroseconds = 500000;
  33. public function handle()
  34. {
  35. if ($this->apps === []) {
  36. $this->warn('未配置 Google Play 检测列表(CheckGooglePlayStore::$apps),跳过。');
  37. return 0;
  38. }
  39. $env = env('APP_ENV', 'local');
  40. $results = [];
  41. $delistedNotified = [];
  42. $unknownNotified = [];
  43. foreach ($this->apps as $name => $url) {
  44. $result = $this->checkSingleApp($name, $url);
  45. $results[] = $result;
  46. Util::WriteLog(
  47. 'google_play_check',
  48. sprintf(
  49. '[%s] %s | %s | %s',
  50. strtoupper($result['status']),
  51. $name,
  52. $url,
  53. $result['reason']
  54. )
  55. );
  56. $pkg = $result['package'];
  57. if ($result['status'] === 'online') {
  58. $this->clearCounters($pkg);
  59. } elseif ($result['status'] === 'delisted') {
  60. $count = $this->increaseCounter($this->getDelistedCounterKey($pkg));
  61. $this->clearCounter($this->getUnknownCounterKey($pkg));
  62. if ($count >= $this->delistedConfirmTimes) {
  63. if (!$this->hasAlreadyNotified('delisted', $pkg)) {
  64. $delistedNotified[] = [
  65. 'name' => $name,
  66. 'url' => $url,
  67. 'reason' => $result['reason'],
  68. 'count' => $count,
  69. ];
  70. $this->markNotified('delisted', $pkg);
  71. }
  72. }
  73. } elseif ($result['status'] === 'unknown') {
  74. $count = $this->increaseCounter($this->getUnknownCounterKey($pkg));
  75. $this->clearCounter($this->getDelistedCounterKey($pkg));
  76. if ($count >= $this->unknownConfirmTimes) {
  77. if (!$this->hasAlreadyNotified('unknown', $pkg)) {
  78. $unknownNotified[] = [
  79. 'name' => $name,
  80. 'url' => $url,
  81. 'reason' => $result['reason'],
  82. 'count' => $count,
  83. ];
  84. $this->markNotified('unknown', $pkg);
  85. }
  86. }
  87. }
  88. usleep(random_int($this->sleepMinMicroseconds, $this->sleepMaxMicroseconds));
  89. }
  90. if (!empty($delistedNotified)) {
  91. $this->notifyDelisted($env, $delistedNotified);
  92. $this->warn('已发送下架告警: ' . count($delistedNotified) . ' 个');
  93. }
  94. if (!empty($unknownNotified)) {
  95. $this->notifyUnknown($env, $unknownNotified);
  96. $this->warn('已发送检测异常告警: ' . count($unknownNotified) . ' 个');
  97. }
  98. foreach ($results as $item) {
  99. $this->line(sprintf(
  100. '[%s] %s - %s',
  101. strtoupper($item['status']),
  102. $item['name'],
  103. $item['reason']
  104. ));
  105. }
  106. if (empty($delistedNotified) && empty($unknownNotified)) {
  107. $this->info('本次检测完成,无需告警。');
  108. }
  109. return empty($delistedNotified) ? 0 : 1;
  110. }
  111. /**
  112. * @return array{name:string,url:string,package:string,status:string,reason:string}
  113. */
  114. protected function checkSingleApp(string $name, string $playUrl): array
  115. {
  116. $parsed = $this->parsePlayStoreUrl($playUrl);
  117. if ($parsed === null) {
  118. return [
  119. 'name' => $name,
  120. 'url' => $playUrl,
  121. 'package' => '_badurl_' . md5($playUrl),
  122. 'status' => 'unknown',
  123. 'reason' => '无法从 URL 解析包名 id=',
  124. ];
  125. }
  126. $package = $parsed['package'];
  127. $requestUrl = $this->buildDetailsUrl($package);
  128. $resp = $this->httpGetWithRetry($requestUrl, $this->httpMaxAttempts);
  129. if (!empty($resp['error'])) {
  130. return [
  131. 'name' => $name,
  132. 'url' => $playUrl,
  133. 'package' => $package,
  134. 'status' => 'unknown',
  135. 'reason' => '请求失败: ' . $resp['error'],
  136. ];
  137. }
  138. $code = (int) ($resp['code'] ?? 0);
  139. $body = (string) ($resp['body'] ?? '');
  140. if (in_array($code, [403, 429, 500, 502, 503, 504], true)) {
  141. return [
  142. 'name' => $name,
  143. 'url' => $playUrl,
  144. 'package' => $package,
  145. 'status' => 'unknown',
  146. 'reason' => "HTTP {$code}",
  147. ];
  148. }
  149. if ($code === 404) {
  150. return [
  151. 'name' => $name,
  152. 'url' => $playUrl,
  153. 'package' => $package,
  154. 'status' => 'delisted',
  155. 'reason' => 'Play 返回 HTTP 404(包不存在或已下架)',
  156. ];
  157. }
  158. if ($code !== 200) {
  159. return [
  160. 'name' => $name,
  161. 'url' => $playUrl,
  162. 'package' => $package,
  163. 'status' => 'unknown',
  164. 'reason' => "HTTP {$code}",
  165. ];
  166. }
  167. if ($this->isPlayNotFoundPage($body)) {
  168. return [
  169. 'name' => $name,
  170. 'url' => $playUrl,
  171. 'package' => $package,
  172. 'status' => 'delisted',
  173. 'reason' => 'Play 错误页(Not Found 等)',
  174. ];
  175. }
  176. if ($this->isLikelyNormalDetailPage($body)) {
  177. $this->clearNotifiedFlags($package);
  178. return [
  179. 'name' => $name,
  180. 'url' => $playUrl,
  181. 'package' => $package,
  182. 'status' => 'online',
  183. 'reason' => '详情页正常(含 Play 前端特征)',
  184. ];
  185. }
  186. $len = strlen($body);
  187. if ($len < 15000) {
  188. return [
  189. 'name' => $name,
  190. 'url' => $playUrl,
  191. 'package' => $package,
  192. 'status' => 'unknown',
  193. 'reason' => "HTTP 200 但正文过短({$len} bytes),无法判断",
  194. ];
  195. }
  196. return [
  197. 'name' => $name,
  198. 'url' => $playUrl,
  199. 'package' => $package,
  200. 'status' => 'unknown',
  201. 'reason' => 'HTTP 200 但未识别为正常详情页(页面结构可能变更)',
  202. ];
  203. }
  204. protected function isPlayNotFoundPage(string $body): bool
  205. {
  206. if (stripos($body, '<title>Not Found</title>') !== false) {
  207. return true;
  208. }
  209. if (preg_match('/requested\s+URL\s+was\s+not\s+found/i', $body)) {
  210. return true;
  211. }
  212. return false;
  213. }
  214. protected function isLikelyNormalDetailPage(string $body): bool
  215. {
  216. if ($this->isPlayNotFoundPage($body)) {
  217. return false;
  218. }
  219. if (strlen($body) < 30000) {
  220. return false;
  221. }
  222. // 当前 Play Web 详情页常见内嵌数据;404 短页不含
  223. if (strpos($body, 'WIZ_global_data') === false) {
  224. return false;
  225. }
  226. return true;
  227. }
  228. /**
  229. * 从详情链接解析包名。
  230. */
  231. protected function parsePlayStoreUrl(string $url): ?array
  232. {
  233. $parts = parse_url($url);
  234. if (empty($parts['host']) || stripos($parts['host'], 'play.google.com') === false) {
  235. return null;
  236. }
  237. $query = $parts['query'] ?? '';
  238. if ($query === '') {
  239. return null;
  240. }
  241. parse_str($query, $q);
  242. if (empty($q['id']) || !is_string($q['id'])) {
  243. return null;
  244. }
  245. $id = $q['id'];
  246. if (!preg_match('/^[a-zA-Z][a-zA-Z0-9._]*$/', $id)) {
  247. return null;
  248. }
  249. return ['package' => $id];
  250. }
  251. protected function buildDetailsUrl(string $package): string
  252. {
  253. return 'https://play.google.com/store/apps/details?id=' . rawurlencode($package) . '&hl=en&gl=US';
  254. }
  255. /**
  256. * @return array{code:int,body:string,error:string}
  257. */
  258. protected function httpGetWithRetry(string $url, int $maxAttempts = 3): array
  259. {
  260. $attempt = 0;
  261. $last = [
  262. 'code' => 0,
  263. 'body' => '',
  264. 'error' => '',
  265. ];
  266. while ($attempt < $maxAttempts) {
  267. $attempt++;
  268. $ch = curl_init($url);
  269. curl_setopt_array($ch, [
  270. CURLOPT_RETURNTRANSFER => true,
  271. CURLOPT_FOLLOWLOCATION => true,
  272. CURLOPT_TIMEOUT => 45,
  273. CURLOPT_CONNECTTIMEOUT => 15,
  274. CURLOPT_SSL_VERIFYPEER => true,
  275. CURLOPT_HTTPHEADER => [
  276. 'Accept: text/html,application/xhtml+xml;q=0.9,*/*;q=0.8',
  277. 'Accept-Language: en-US,en;q=0.9',
  278. 'Cache-Control: no-cache',
  279. ],
  280. CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
  281. ]);
  282. $body = curl_exec($ch);
  283. $code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
  284. $error = curl_error($ch);
  285. curl_close($ch);
  286. $last = [
  287. 'code' => $code,
  288. 'body' => is_string($body) ? $body : '',
  289. 'error' => $error ?: '',
  290. ];
  291. if ($last['error'] === '' && ($code === 200 || $code === 404)) {
  292. return $last;
  293. }
  294. $shouldRetry = $last['error'] !== '' || in_array($code, [429, 500, 502, 503, 504], true);
  295. if (!$shouldRetry || $attempt >= $maxAttempts) {
  296. return $last;
  297. }
  298. $sleepSeconds = $attempt === 1 ? 2 : ($attempt === 2 ? 5 : 8);
  299. sleep($sleepSeconds);
  300. }
  301. return $last;
  302. }
  303. protected function getDelistedCounterKey(string $package): string
  304. {
  305. return 'google:play:delisted:' . $package;
  306. }
  307. protected function getUnknownCounterKey(string $package): string
  308. {
  309. return 'google:play:unknown:' . $package;
  310. }
  311. protected function getDelistedNotifiedKey(string $package): string
  312. {
  313. return 'google:play:notified:delisted:' . $package;
  314. }
  315. protected function getUnknownNotifiedKey(string $package): string
  316. {
  317. return 'google:play:notified:unknown:' . $package;
  318. }
  319. protected function increaseCounter(string $key): int
  320. {
  321. $count = (int) Redis::incr($key);
  322. Redis::expire($key, $this->counterExpireSeconds);
  323. return $count;
  324. }
  325. protected function clearCounters(string $package): void
  326. {
  327. $this->clearCounter($this->getDelistedCounterKey($package));
  328. $this->clearCounter($this->getUnknownCounterKey($package));
  329. }
  330. protected function clearCounter(string $key): void
  331. {
  332. try {
  333. Redis::del($key);
  334. } catch (\Throwable $e) {
  335. Util::WriteLog('google_play_check', 'Redis del error: ' . $e->getMessage());
  336. }
  337. }
  338. protected function hasAlreadyNotified(string $type, string $package): bool
  339. {
  340. try {
  341. $key = $type === 'delisted'
  342. ? $this->getDelistedNotifiedKey($package)
  343. : $this->getUnknownNotifiedKey($package);
  344. return (bool) Redis::exists($key);
  345. } catch (\Throwable $e) {
  346. Util::WriteLog('google_play_check', 'Redis exists error: ' . $e->getMessage());
  347. return false;
  348. }
  349. }
  350. protected function markNotified(string $type, string $package): void
  351. {
  352. try {
  353. $key = $type === 'delisted'
  354. ? $this->getDelistedNotifiedKey($package)
  355. : $this->getUnknownNotifiedKey($package);
  356. Redis::setex($key, $this->counterExpireSeconds, 1);
  357. } catch (\Throwable $e) {
  358. Util::WriteLog('google_play_check', 'Redis setex error: ' . $e->getMessage());
  359. }
  360. }
  361. protected function clearNotifiedFlags(string $package): void
  362. {
  363. try {
  364. Redis::del(
  365. $this->getDelistedNotifiedKey($package),
  366. $this->getUnknownNotifiedKey($package)
  367. );
  368. } catch (\Throwable $e) {
  369. Util::WriteLog('google_play_check', 'Redis clear notified flags error: ' . $e->getMessage());
  370. }
  371. }
  372. protected function notifyDelisted(string $env, array $items): void
  373. {
  374. $lines = ["[{$env}] Google Play 下架/不可访问检测告警"];
  375. foreach ($items as $item) {
  376. $lines[] = '• ' . $item['name'];
  377. $lines[] = ' 原因: ' . $item['reason'];
  378. $lines[] = ' 连续次数: ' . $item['count'];
  379. $lines[] = ' 链接: ' . $item['url'];
  380. }
  381. $this->sendTelegramMessage(implode("\n", $lines));
  382. }
  383. protected function notifyUnknown(string $env, array $items): void
  384. {
  385. $lines = ["[{$env}] Google Play 检测异常告警"];
  386. foreach ($items as $item) {
  387. $lines[] = '• ' . $item['name'];
  388. $lines[] = ' 原因: ' . $item['reason'];
  389. $lines[] = ' 连续次数: ' . $item['count'];
  390. $lines[] = ' 链接: ' . $item['url'];
  391. }
  392. $this->sendTelegramMessage(implode("\n", $lines));
  393. }
  394. protected function sendTelegramMessage(string $message): void
  395. {
  396. try {
  397. TelegramBot::getDefault()->sendMsgAndImportant($message);
  398. } catch (\Throwable $e) {
  399. Util::WriteLog('google_play_check', 'Telegram send error: ' . $e->getMessage());
  400. $this->error('Telegram 发送失败: ' . $e->getMessage());
  401. }
  402. }
  403. }