script_task.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. serial = str(self.config.script.device.serial)
  159. if serial and serial != 'auto':
  160. logger.info(f'专用ADB连接到 {serial}...')
  161. self._adb_cmd(['connect', serial], timeout=10)
  162. output = self._adb_cmd(['devices'])
  163. lines = [l for l in output.strip().split('\n')[1:] if l.strip() and '\tdevice' in l]
  164. return len(lines) > 0
  165. except Exception:
  166. return False
  167. def _is_frida_server_running(self):
  168. try:
  169. output = self._adb_shell(['ps | grep frida-server'])
  170. return 'frida-server' in output
  171. except Exception:
  172. return False
  173. def _is_frida_server_installed(self):
  174. try:
  175. output = self._adb_shell(['ls', '-l', FRIDA_SERVER_REMOTE])
  176. return 'No such file' not in output and FRIDA_SERVER_REMOTE in output
  177. except Exception:
  178. return False
  179. def _ensure_frida_local(self):
  180. if os.path.exists(FRIDA_SERVER_LOCAL):
  181. return True
  182. if not os.path.exists(FRIDA_SERVER_XZ):
  183. logger.error(f'找不到Frida Server压缩文件: {FRIDA_SERVER_XZ}')
  184. return False
  185. logger.info('解压Frida Server...')
  186. try:
  187. with lzma.open(FRIDA_SERVER_XZ, 'rb') as f_in:
  188. with open(FRIDA_SERVER_LOCAL, 'wb') as f_out:
  189. f_out.write(f_in.read())
  190. logger.info('Frida Server解压完成')
  191. return True
  192. except Exception as e:
  193. logger.error(f'解压失败: {e}')
  194. return False
  195. def _push_frida_server(self):
  196. if not self._ensure_frida_local():
  197. return False
  198. logger.info('推送Frida Server到模拟器...')
  199. try:
  200. self._adb_cmd(['push', FRIDA_SERVER_LOCAL, FRIDA_SERVER_REMOTE], timeout=30)
  201. self._adb_shell(['chmod', '755', FRIDA_SERVER_REMOTE])
  202. logger.info('Frida Server推送完成')
  203. return True
  204. except Exception as e:
  205. logger.error(f'推送失败: {e}')
  206. return False
  207. def _start_frida_server(self):
  208. logger.info('启动Frida Server...')
  209. subprocess.Popen(
  210. [ADB_PATH, 'shell', f'{FRIDA_SERVER_REMOTE} &'],
  211. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
  212. )
  213. time.sleep(3)
  214. if self._is_frida_server_running():
  215. logger.info('Frida Server已启动')
  216. return True
  217. logger.error('Frida Server启动失败,请确保模拟器已开启Root模式')
  218. return False
  219. def _ensure_frida_server_running(self):
  220. if self._is_frida_server_running():
  221. return True
  222. if not self._is_frida_server_installed():
  223. if not self._push_frida_server():
  224. return False
  225. return self._start_frida_server()
  226. # ======================== Frida 脚本执行 ========================
  227. def _run_frida_script(self, pid, script_content, wait_time=3, timeout=10):
  228. with tempfile.NamedTemporaryFile(mode='w', suffix='.js', delete=False, encoding='utf-8') as f:
  229. f.write(script_content)
  230. script_path = f.name
  231. try:
  232. process = subprocess.Popen(
  233. ['frida', '-U', '-p', str(pid), '-l', script_path],
  234. stdin=subprocess.PIPE,
  235. stdout=subprocess.PIPE,
  236. stderr=subprocess.PIPE,
  237. text=True
  238. )
  239. time.sleep(wait_time)
  240. stdout, stderr = process.communicate(input='exit\n', timeout=timeout)
  241. return stdout + stderr
  242. except subprocess.TimeoutExpired:
  243. process.kill()
  244. logger.warning('Frida脚本执行超时')
  245. return None
  246. except Exception as e:
  247. logger.warning(f'Frida脚本执行失败: {e}')
  248. return None
  249. finally:
  250. try:
  251. os.unlink(script_path)
  252. except:
  253. pass
  254. def _extract_token(self, pid):
  255. script = f"""
  256. Java.perform(function() {{
  257. Java.choose('com.netease.gl.serviceaccount.proto.auth.GLAuth$Authed', {{
  258. onMatch: function(instance) {{
  259. var uid = instance.getUid();
  260. var token = instance.getToken();
  261. var source = instance.getSource();
  262. if (uid && token) {{
  263. console.log('GL_UID:' + uid);
  264. console.log('GL_TOKEN:' + token);
  265. console.log('GL_SOURCE:' + source);
  266. }}
  267. }},
  268. onComplete: function() {{}}
  269. }});
  270. try {{
  271. var YXFDeviceInfo = Java.use('com.netease.gl.glbase.build.YXFDeviceInfo');
  272. console.log('GL_DEVICEID:' + YXFDeviceInfo.getDeviceId());
  273. }} catch(e) {{}}
  274. Java.choose('com.netease.gl.serviceim.entity.chatroom.GameRoleCardEntity', {{
  275. onMatch: function(instance) {{
  276. var appKey = instance.getAppKey ? instance.getAppKey() : null;
  277. if (appKey === '{self.app_key}') {{
  278. var displayInfos = instance.getRoleCardDisplayInfos();
  279. if (displayInfos && displayInfos.size() > 0) {{
  280. var info = displayInfos.get(0);
  281. var fields = info.getClass().getDeclaredFields();
  282. for (var i = 0; i < fields.length; i++) {{
  283. fields[i].setAccessible(true);
  284. var name = fields[i].getName();
  285. try {{
  286. var value = fields[i].get(info);
  287. if (name === 'roleId' && value) {{
  288. console.log('ROLE_ID:' + value);
  289. }} else if (name === 'server' && value) {{
  290. console.log('SERVER:' + value);
  291. }}
  292. }} catch(e) {{}}
  293. }}
  294. console.log('APP_KEY:' + appKey);
  295. }}
  296. }}
  297. }},
  298. onComplete: function() {{}}
  299. }});
  300. }});
  301. """
  302. output = self._run_frida_script(pid, script, wait_time=3, timeout=10)
  303. if not output:
  304. return None
  305. data = {}
  306. for line in output.split('\n'):
  307. if 'GL_UID:' in line:
  308. data['GL_UID'] = line.split('GL_UID:')[1].strip()
  309. elif 'GL_TOKEN:' in line and 'GL_TOKEN' not in data:
  310. data['GL_TOKEN'] = line.split('GL_TOKEN:')[1].strip()
  311. elif 'GL_DEVICEID:' in line:
  312. data['GL_DEVICEID'] = line.split('GL_DEVICEID:')[1].strip()
  313. elif 'GL_SOURCE:' in line:
  314. data['GL_SOURCE'] = line.split('GL_SOURCE:')[1].strip()
  315. elif 'ROLE_ID:' in line:
  316. data['ROLE_ID'] = line.split('ROLE_ID:')[1].strip()
  317. elif 'SERVER:' in line:
  318. data['SERVER'] = line.split('SERVER:')[1].strip()
  319. elif 'APP_KEY:' in line:
  320. data['APP_KEY'] = line.split('APP_KEY:')[1].strip()
  321. if data.get('GL_UID') and data.get('GL_TOKEN'):
  322. return data
  323. return None
  324. def _frida_sign(self, url, body, headers=None):
  325. if not self.frida_pid:
  326. self.frida_pid = self._get_app_pid()
  327. if not self.frida_pid:
  328. logger.error('无法获取APP PID,请确保大神APP已打开')
  329. return None
  330. headers_code = ""
  331. if headers:
  332. for k, v in headers.items():
  333. v = v.replace("'", "\\'")
  334. headers_code += f"map.put('{k}', '{v}');\n"
  335. body_escaped = body.replace("\\", "\\\\").replace("'", "\\'")
  336. script = f"""
  337. Java.perform(function() {{
  338. var Tools = Java.use('com.netease.nep.Tools');
  339. var HashMap = Java.use('java.util.HashMap');
  340. var map = HashMap.$new();
  341. {headers_code}
  342. var result = Tools.getPostMethodSignatures('{url}', '{body_escaped}', map);
  343. console.log('SIGNED_URL:' + result);
  344. }});
  345. """
  346. output = self._run_frida_script(self.frida_pid, script, wait_time=2, timeout=15)
  347. if not output:
  348. return None
  349. for line in output.split('\n'):
  350. if 'SIGNED_URL:' in line:
  351. return line.split('SIGNED_URL:')[1].strip()
  352. return None
  353. # ======================== HTTP API ========================
  354. def _generate_nonce(self):
  355. return str(random.randint(-9000000000000000000, 9000000000000000000))
  356. def _build_headers(self, nonce=None):
  357. if not nonce:
  358. nonce = self._generate_nonce()
  359. return {
  360. "Content-Type": "application/json",
  361. "Accept": "application/json",
  362. "User-Agent": f"Mozilla/5.0 (Linux; Android 12) Godlike/{GL_VERSION}",
  363. "gl-version": GL_VERSION,
  364. "gl-source": self.gl_source,
  365. "gl-deviceid": self.gl_deviceid,
  366. "gl-token": self.gl_token,
  367. "gl-clienttype": GL_CLIENTTYPE,
  368. "gl-uid": self.gl_uid,
  369. "gl-nonce": nonce,
  370. "Origin": "https://act.ds.163.com",
  371. "Referer": "https://act.ds.163.com/",
  372. }
  373. def _get_rewards(self):
  374. url = f"{WELFARE_BASE}/v1/welfare/getAppInfos"
  375. payload = {
  376. "appKey": self.app_key,
  377. "roleId": self.role_id,
  378. "server": self.server,
  379. }
  380. try:
  381. resp = self.session.post(url, json=payload, headers=self._build_headers(), timeout=15)
  382. data = resp.json()
  383. if data.get('code') != 200:
  384. logger.warning(f'获取礼包失败: {data.get("errmsg")}')
  385. return []
  386. rewards = []
  387. for app_info in data.get('result', []):
  388. for bag in app_info.get('rewardBags', []):
  389. bag_id = bag.get('id')
  390. title = bag.get('title', '')
  391. completed = bag.get('completed', False)
  392. has_apply = bag.get('hasApplay', False)
  393. desc = bag.get('fixedRewardDesc', '')
  394. if has_apply:
  395. logger.info(f' [已领取] {title}')
  396. elif completed:
  397. logger.info(f' [可领取] {title} - {desc}')
  398. rewards.append({'id': bag_id, 'title': title})
  399. else:
  400. logger.info(f' [未完成] {title}')
  401. return rewards
  402. except Exception as e:
  403. logger.error(f'获取礼包请求异常: {e}')
  404. return []
  405. def _claim_reward(self, bag_id, title):
  406. base_url = f"{WELFARE_BASE}/v1/welfare/applyRewardV2"
  407. payload = {
  408. "appKey": self.app_key,
  409. "rewardBagId": bag_id,
  410. "roleId": self.role_id,
  411. "server": self.server,
  412. }
  413. nonce = self._generate_nonce()
  414. sign_headers = {
  415. "GL-ClientType": GL_CLIENTTYPE,
  416. "GL-DeviceId": self.gl_deviceid,
  417. "GL-Nonce": nonce,
  418. "GL-Token": self.gl_token,
  419. "GL-Uid": self.gl_uid,
  420. }
  421. logger.info(f' 正在领取: {title}...')
  422. signed_url = self._frida_sign(base_url, json.dumps(payload), sign_headers)
  423. if not signed_url:
  424. logger.warning(f' 签名失败: {title}')
  425. return False
  426. try:
  427. headers = self._build_headers(nonce)
  428. resp = self.session.post(signed_url, json=payload, headers=headers, timeout=15)
  429. data = resp.json()
  430. code = data.get('code')
  431. msg = data.get('errmsg', '')
  432. if code == 200:
  433. logger.info(f' 领取成功: {title}')
  434. return True
  435. elif code == 801 or '已领取' in msg:
  436. logger.info(f' 已领取过: {title}')
  437. else:
  438. logger.warning(f' 领取失败: {title} - {msg}')
  439. except Exception as e:
  440. logger.error(f' 领取异常: {title} - {e}')
  441. return False