script_task.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. # This Python file uses the following encoding: utf-8
  2. import subprocess
  3. import tempfile
  4. import lzma
  5. import os
  6. import time
  7. import json
  8. import random
  9. import requests
  10. import urllib3
  11. from tasks.base_task import BaseTask
  12. from module.logger import logger
  13. from module.exception import TaskEnd
  14. urllib3.disable_warnings()
  15. os.environ['MSYS_NO_PATHCONV'] = '1'
  16. WELFARE_BASE = "https://god-welfare.gameyw.netease.com"
  17. GL_PACKAGE = "com.netease.gl"
  18. SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
  19. FRIDA_SERVER_LOCAL = os.path.join(SCRIPT_DIR, "frida-server-17.6.2-android-x86_64")
  20. FRIDA_SERVER_XZ = FRIDA_SERVER_LOCAL + ".xz"
  21. FRIDA_SERVER_REMOTE = "/data/local/tmp/frida-server"
  22. ADB_PATH = os.path.join(SCRIPT_DIR, "platform-tools", "adb.exe")
  23. APP_KEY = "g37"
  24. GL_VERSION = "4.11.0"
  25. GL_CLIENTTYPE = "50"
  26. class ScriptTask(BaseTask):
  27. def run(self):
  28. self.gl_uid = ""
  29. self.gl_token = ""
  30. self.gl_deviceid = ""
  31. self.gl_source = "URS"
  32. self.role_id = ""
  33. self.server = ""
  34. self.app_key = APP_KEY
  35. self.frida_pid = None
  36. self.session = requests.Session()
  37. self.session.verify = False
  38. logger.hr('AutoCheckinBigGod', level=1)
  39. # [1/5] 检查运行环境
  40. logger.info('[1/5] 检查运行环境...')
  41. if not self._check_adb_connection():
  42. logger.error('未检测到ADB设备,请确保模拟器已启动并已连接ADB')
  43. self.set_next_run('AutoCheckinBigGod', success=False, finish=True)
  44. raise TaskEnd('AutoCheckinBigGod')
  45. logger.info('ADB已连接')
  46. if not self._ensure_frida_server_running():
  47. logger.error('Frida Server启动失败,请检查模拟器环境')
  48. self.set_next_run('AutoCheckinBigGod', success=False, finish=True)
  49. raise TaskEnd('AutoCheckinBigGod')
  50. logger.info('Frida Server运行中')
  51. # [2/5] 启动大神APP
  52. logger.info('[2/5] 启动大神APP...')
  53. pid = self._launch_app()
  54. if not pid:
  55. logger.error('无法启动大神APP,请确保模拟器中已安装大神APP')
  56. self.set_next_run('AutoCheckinBigGod', success=False, finish=True)
  57. raise TaskEnd('AutoCheckinBigGod')
  58. self.frida_pid = pid
  59. logger.info(f'大神APP已运行 (PID: {pid})')
  60. # [3/5] 获取Token
  61. logger.info('[3/5] 获取Token...')
  62. token_data = None
  63. for attempt in range(1, 4):
  64. token_data = self._extract_token(pid)
  65. if token_data:
  66. break
  67. if attempt < 3:
  68. logger.warning(f'第{attempt}次获取Token失败,等待{10 * attempt}秒后重试...')
  69. time.sleep(10 * attempt)
  70. new_pid = self._get_app_pid()
  71. if new_pid:
  72. pid = new_pid
  73. self.frida_pid = pid
  74. if not token_data:
  75. logger.error('无法获取Token,请确保已登录大神APP')
  76. self.set_next_run('AutoCheckinBigGod', success=False, finish=True)
  77. raise TaskEnd('AutoCheckinBigGod')
  78. self.gl_uid = token_data.get('GL_UID', '')
  79. self.gl_token = token_data.get('GL_TOKEN', '')
  80. self.gl_deviceid = token_data.get('GL_DEVICEID', '')
  81. self.gl_source = token_data.get('GL_SOURCE', 'URS')
  82. self.role_id = token_data.get('ROLE_ID', '')
  83. self.server = token_data.get('SERVER', '')
  84. if token_data.get('APP_KEY'):
  85. self.app_key = token_data.get('APP_KEY')
  86. logger.info(f'Token获取成功! 用户ID: {self.gl_uid[:16]}...')
  87. # Token已获取,将大神APP切到后台,减少对用户的干扰
  88. try:
  89. self._adb_shell(['input', 'keyevent', 'KEYCODE_HOME'])
  90. except Exception:
  91. pass
  92. if self.role_id and self.server:
  93. logger.info(f'角色信息: {self.role_id} @ {self.server}')
  94. else:
  95. logger.warning('未能获取角色信息,请确保已在大神APP中绑定阴阳师角色')
  96. # [4/5] 获取礼包列表
  97. logger.info('[4/5] 获取礼包列表...')
  98. rewards = self._get_rewards()
  99. if not rewards:
  100. logger.info('没有可领取的礼包')
  101. self._cleanup()
  102. self.set_next_run('AutoCheckinBigGod', success=True, finish=True)
  103. raise TaskEnd('AutoCheckinBigGod')
  104. # [5/5] 领取礼包
  105. logger.info(f'[5/5] 领取 {len(rewards)} 个礼包...')
  106. success_count = 0
  107. for r in rewards:
  108. if self._claim_reward(r['id'], r['title']):
  109. success_count += 1
  110. time.sleep(1)
  111. logger.info(f'完成! 成功领取 {success_count}/{len(rewards)} 个礼包')
  112. self._cleanup()
  113. self.set_next_run('AutoCheckinBigGod', success=True, finish=True)
  114. raise TaskEnd('AutoCheckinBigGod')
  115. # ======================== 清理 ========================
  116. def _cleanup(self):
  117. logger.info('清理:关闭大神APP和Frida Server...')
  118. try:
  119. self._adb_shell(['am', 'force-stop', GL_PACKAGE])
  120. except Exception:
  121. pass
  122. try:
  123. self._adb_shell(['killall', 'frida-server'])
  124. except Exception:
  125. pass
  126. # ======================== ADB 操作 ========================
  127. def _adb_cmd(self, args, timeout=10):
  128. cmd = [ADB_PATH] + args
  129. result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
  130. return result.stdout.strip()
  131. def _adb_shell(self, cmd, timeout=15):
  132. return self._adb_cmd(['shell'] + cmd, timeout=timeout)
  133. def _get_app_pid(self):
  134. try:
  135. output = self._adb_shell(['pidof', GL_PACKAGE])
  136. if output:
  137. return int(output.split()[0])
  138. except Exception as e:
  139. logger.warning(f'获取PID失败: {e}')
  140. return None
  141. def _launch_app(self):
  142. try:
  143. self._adb_shell(['am', 'force-stop', GL_PACKAGE])
  144. time.sleep(2)
  145. self._adb_shell([
  146. 'monkey', '-p', GL_PACKAGE,
  147. '-c', 'android.intent.category.LAUNCHER', '1'
  148. ])
  149. logger.info('等待大神APP启动...')
  150. time.sleep(15)
  151. return self._get_app_pid()
  152. except Exception as e:
  153. logger.warning(f'启动APP失败: {e}')
  154. return None
  155. # ======================== Frida Server 管理 ========================
  156. def _check_adb_connection(self):
  157. try:
  158. output = self._adb_cmd(['devices'])
  159. lines = [l for l in output.strip().split('\n')[1:] if l.strip() and 'device' in l]
  160. return len(lines) > 0
  161. except Exception:
  162. return False
  163. def _is_frida_server_running(self):
  164. try:
  165. output = self._adb_shell(['ps | grep frida-server'])
  166. return 'frida-server' in output
  167. except Exception:
  168. return False
  169. def _is_frida_server_installed(self):
  170. try:
  171. output = self._adb_shell(['ls', '-l', FRIDA_SERVER_REMOTE])
  172. return 'No such file' not in output and FRIDA_SERVER_REMOTE in output
  173. except Exception:
  174. return False
  175. def _ensure_frida_local(self):
  176. if os.path.exists(FRIDA_SERVER_LOCAL):
  177. return True
  178. if not os.path.exists(FRIDA_SERVER_XZ):
  179. logger.error(f'找不到Frida Server压缩文件: {FRIDA_SERVER_XZ}')
  180. return False
  181. logger.info('解压Frida Server...')
  182. try:
  183. with lzma.open(FRIDA_SERVER_XZ, 'rb') as f_in:
  184. with open(FRIDA_SERVER_LOCAL, 'wb') as f_out:
  185. f_out.write(f_in.read())
  186. logger.info('Frida Server解压完成')
  187. return True
  188. except Exception as e:
  189. logger.error(f'解压失败: {e}')
  190. return False
  191. def _push_frida_server(self):
  192. if not self._ensure_frida_local():
  193. return False
  194. logger.info('推送Frida Server到模拟器...')
  195. try:
  196. self._adb_cmd(['push', FRIDA_SERVER_LOCAL, FRIDA_SERVER_REMOTE], timeout=30)
  197. self._adb_shell(['chmod', '755', FRIDA_SERVER_REMOTE])
  198. logger.info('Frida Server推送完成')
  199. return True
  200. except Exception as e:
  201. logger.error(f'推送失败: {e}')
  202. return False
  203. def _start_frida_server(self):
  204. logger.info('启动Frida Server...')
  205. subprocess.Popen(
  206. [ADB_PATH, 'shell', f'{FRIDA_SERVER_REMOTE} &'],
  207. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
  208. )
  209. time.sleep(3)
  210. if self._is_frida_server_running():
  211. logger.info('Frida Server已启动')
  212. return True
  213. logger.error('Frida Server启动失败,请确保模拟器已开启Root模式')
  214. return False
  215. def _ensure_frida_server_running(self):
  216. if self._is_frida_server_running():
  217. return True
  218. if not self._is_frida_server_installed():
  219. if not self._push_frida_server():
  220. return False
  221. return self._start_frida_server()
  222. # ======================== Frida 脚本执行 ========================
  223. def _run_frida_script(self, pid, script_content, wait_time=3, timeout=10):
  224. with tempfile.NamedTemporaryFile(mode='w', suffix='.js', delete=False, encoding='utf-8') as f:
  225. f.write(script_content)
  226. script_path = f.name
  227. try:
  228. process = subprocess.Popen(
  229. ['frida', '-U', '-p', str(pid), '-l', script_path],
  230. stdin=subprocess.PIPE,
  231. stdout=subprocess.PIPE,
  232. stderr=subprocess.PIPE,
  233. text=True
  234. )
  235. time.sleep(wait_time)
  236. stdout, stderr = process.communicate(input='exit\n', timeout=timeout)
  237. return stdout + stderr
  238. except subprocess.TimeoutExpired:
  239. process.kill()
  240. logger.warning('Frida脚本执行超时')
  241. return None
  242. except Exception as e:
  243. logger.warning(f'Frida脚本执行失败: {e}')
  244. return None
  245. finally:
  246. try:
  247. os.unlink(script_path)
  248. except:
  249. pass
  250. def _extract_token(self, pid):
  251. script = f"""
  252. Java.perform(function() {{
  253. Java.choose('com.netease.gl.serviceaccount.proto.auth.GLAuth$Authed', {{
  254. onMatch: function(instance) {{
  255. var uid = instance.getUid();
  256. var token = instance.getToken();
  257. var source = instance.getSource();
  258. if (uid && token) {{
  259. console.log('GL_UID:' + uid);
  260. console.log('GL_TOKEN:' + token);
  261. console.log('GL_SOURCE:' + source);
  262. }}
  263. }},
  264. onComplete: function() {{}}
  265. }});
  266. try {{
  267. var YXFDeviceInfo = Java.use('com.netease.gl.glbase.build.YXFDeviceInfo');
  268. console.log('GL_DEVICEID:' + YXFDeviceInfo.getDeviceId());
  269. }} catch(e) {{}}
  270. Java.choose('com.netease.gl.serviceim.entity.chatroom.GameRoleCardEntity', {{
  271. onMatch: function(instance) {{
  272. var appKey = instance.getAppKey ? instance.getAppKey() : null;
  273. if (appKey === '{self.app_key}') {{
  274. var displayInfos = instance.getRoleCardDisplayInfos();
  275. if (displayInfos && displayInfos.size() > 0) {{
  276. var info = displayInfos.get(0);
  277. var fields = info.getClass().getDeclaredFields();
  278. for (var i = 0; i < fields.length; i++) {{
  279. fields[i].setAccessible(true);
  280. var name = fields[i].getName();
  281. try {{
  282. var value = fields[i].get(info);
  283. if (name === 'roleId' && value) {{
  284. console.log('ROLE_ID:' + value);
  285. }} else if (name === 'server' && value) {{
  286. console.log('SERVER:' + value);
  287. }}
  288. }} catch(e) {{}}
  289. }}
  290. console.log('APP_KEY:' + appKey);
  291. }}
  292. }}
  293. }},
  294. onComplete: function() {{}}
  295. }});
  296. }});
  297. """
  298. output = self._run_frida_script(pid, script, wait_time=3, timeout=10)
  299. if not output:
  300. return None
  301. data = {}
  302. for line in output.split('\n'):
  303. if 'GL_UID:' in line:
  304. data['GL_UID'] = line.split('GL_UID:')[1].strip()
  305. elif 'GL_TOKEN:' in line and 'GL_TOKEN' not in data:
  306. data['GL_TOKEN'] = line.split('GL_TOKEN:')[1].strip()
  307. elif 'GL_DEVICEID:' in line:
  308. data['GL_DEVICEID'] = line.split('GL_DEVICEID:')[1].strip()
  309. elif 'GL_SOURCE:' in line:
  310. data['GL_SOURCE'] = line.split('GL_SOURCE:')[1].strip()
  311. elif 'ROLE_ID:' in line:
  312. data['ROLE_ID'] = line.split('ROLE_ID:')[1].strip()
  313. elif 'SERVER:' in line:
  314. data['SERVER'] = line.split('SERVER:')[1].strip()
  315. elif 'APP_KEY:' in line:
  316. data['APP_KEY'] = line.split('APP_KEY:')[1].strip()
  317. if data.get('GL_UID') and data.get('GL_TOKEN'):
  318. return data
  319. return None
  320. def _frida_sign(self, url, body, headers=None):
  321. if not self.frida_pid:
  322. self.frida_pid = self._get_app_pid()
  323. if not self.frida_pid:
  324. logger.error('无法获取APP PID,请确保大神APP已打开')
  325. return None
  326. headers_code = ""
  327. if headers:
  328. for k, v in headers.items():
  329. v = v.replace("'", "\\'")
  330. headers_code += f"map.put('{k}', '{v}');\n"
  331. body_escaped = body.replace("\\", "\\\\").replace("'", "\\'")
  332. script = f"""
  333. Java.perform(function() {{
  334. var Tools = Java.use('com.netease.nep.Tools');
  335. var HashMap = Java.use('java.util.HashMap');
  336. var map = HashMap.$new();
  337. {headers_code}
  338. var result = Tools.getPostMethodSignatures('{url}', '{body_escaped}', map);
  339. console.log('SIGNED_URL:' + result);
  340. }});
  341. """
  342. output = self._run_frida_script(self.frida_pid, script, wait_time=2, timeout=15)
  343. if not output:
  344. return None
  345. for line in output.split('\n'):
  346. if 'SIGNED_URL:' in line:
  347. return line.split('SIGNED_URL:')[1].strip()
  348. return None
  349. # ======================== HTTP API ========================
  350. def _generate_nonce(self):
  351. return str(random.randint(-9000000000000000000, 9000000000000000000))
  352. def _build_headers(self, nonce=None):
  353. if not nonce:
  354. nonce = self._generate_nonce()
  355. return {
  356. "Content-Type": "application/json",
  357. "Accept": "application/json",
  358. "User-Agent": f"Mozilla/5.0 (Linux; Android 12) Godlike/{GL_VERSION}",
  359. "gl-version": GL_VERSION,
  360. "gl-source": self.gl_source,
  361. "gl-deviceid": self.gl_deviceid,
  362. "gl-token": self.gl_token,
  363. "gl-clienttype": GL_CLIENTTYPE,
  364. "gl-uid": self.gl_uid,
  365. "gl-nonce": nonce,
  366. "Origin": "https://act.ds.163.com",
  367. "Referer": "https://act.ds.163.com/",
  368. }
  369. def _get_rewards(self):
  370. url = f"{WELFARE_BASE}/v1/welfare/getAppInfos"
  371. payload = {
  372. "appKey": self.app_key,
  373. "roleId": self.role_id,
  374. "server": self.server,
  375. }
  376. try:
  377. resp = self.session.post(url, json=payload, headers=self._build_headers(), timeout=15)
  378. data = resp.json()
  379. if data.get('code') != 200:
  380. logger.warning(f'获取礼包失败: {data.get("errmsg")}')
  381. return []
  382. rewards = []
  383. for app_info in data.get('result', []):
  384. for bag in app_info.get('rewardBags', []):
  385. bag_id = bag.get('id')
  386. title = bag.get('title', '')
  387. completed = bag.get('completed', False)
  388. has_apply = bag.get('hasApplay', False)
  389. desc = bag.get('fixedRewardDesc', '')
  390. if has_apply:
  391. logger.info(f' [已领取] {title}')
  392. elif completed:
  393. logger.info(f' [可领取] {title} - {desc}')
  394. rewards.append({'id': bag_id, 'title': title})
  395. else:
  396. logger.info(f' [未完成] {title}')
  397. return rewards
  398. except Exception as e:
  399. logger.error(f'获取礼包请求异常: {e}')
  400. return []
  401. def _claim_reward(self, bag_id, title):
  402. base_url = f"{WELFARE_BASE}/v1/welfare/applyRewardV2"
  403. payload = {
  404. "appKey": self.app_key,
  405. "rewardBagId": bag_id,
  406. "roleId": self.role_id,
  407. "server": self.server,
  408. }
  409. nonce = self._generate_nonce()
  410. sign_headers = {
  411. "GL-ClientType": GL_CLIENTTYPE,
  412. "GL-DeviceId": self.gl_deviceid,
  413. "GL-Nonce": nonce,
  414. "GL-Token": self.gl_token,
  415. "GL-Uid": self.gl_uid,
  416. }
  417. logger.info(f' 正在领取: {title}...')
  418. signed_url = self._frida_sign(base_url, json.dumps(payload), sign_headers)
  419. if not signed_url:
  420. logger.warning(f' 签名失败: {title}')
  421. return False
  422. try:
  423. headers = self._build_headers(nonce)
  424. resp = self.session.post(signed_url, json=payload, headers=headers, timeout=15)
  425. data = resp.json()
  426. code = data.get('code')
  427. msg = data.get('errmsg', '')
  428. if code == 200:
  429. logger.info(f' 领取成功: {title}')
  430. return True
  431. elif code == 801 or '已领取' in msg:
  432. logger.info(f' 已领取过: {title}')
  433. else:
  434. logger.warning(f' 领取失败: {title} - {msg}')
  435. except Exception as e:
  436. logger.error(f' 领取异常: {title} - {e}')
  437. return False