Worker.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  1. const path = require('path')
  2. const axios = require('axios')
  3. const OSS = require('ali-oss')
  4. const mq = require('../../plugin/mq')
  5. const { assertRunforgeTaskIngress } = require('../../plugin/mq/runforgeTaskMq')
  6. const db = require('../../plugin/DataBase/db')
  7. const Redis = require('../../plugin/DataBase/Redis')
  8. const EmailTemplate = require('../../plugin/Email/emailTemplate')
  9. const { URLSearchParams } = require('url')
  10. const {
  11. getPathData,
  12. selectCheckpoints,
  13. generateCadence
  14. } = require('../../plugin/Lepao/Path')
  15. const {
  16. dataEncrypt,
  17. dataDecrypt,
  18. dataSign
  19. } = require('../../plugin/Lepao/Crypto')
  20. const Logger = require('../Logger')
  21. class Worker {
  22. constructor() {
  23. this.logger = new Logger(
  24. path.join(__dirname, '../logs/LepaoWorker.log'),
  25. 'INFO'
  26. )
  27. this.handlers = {}
  28. this.running = false
  29. this.baseUrl = 'https://lepao.ctbu.edu.cn/v3/api.php'
  30. this.taskQueue = 'runforge_task_queue'
  31. this.resultQueue = 'runforge_task_result_queue'
  32. this.deadQueue = 'runforge_task_dead_queue'
  33. this.noticeQueue = 'runforge_message_queue'
  34. this.channelName = 'lepao_worker'
  35. this.maxRetry = 3
  36. this.timeout = 15000
  37. this.defaultUserAgent = 'Mozilla/5.0 (Linux; Android 16; 2211133C Build/BP2A.250605.031.A3; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/138.0.7204.180 Mobile Safari/537.36 XWEB/1380347 MMWEBSDK/20250202 MMWEBID/1020 wxwork/5.0.6.66174 MicroMessenger/8.0.28.48(0x28001c30) MiniProgramEnv/android Luggage/3.0.2.95ef3f83 NetType/WIFI Language/zh_CN ABI/arm64'
  38. // 调试模式:将 axios 请求走本地代理(例如 charles/fiddler)
  39. // 开启方式:设置环境变量 LEPAO_DEBUG_PROXY=1
  40. this.debugProxyEnabled = String(process.env.LEPAO_DEBUG_PROXY || '').trim() === '1'
  41. this.debugProxyHost = process.env.LEPAO_DEBUG_PROXY_HOST || '127.0.0.1'
  42. this.debugProxyPort = Number(process.env.LEPAO_DEBUG_PROXY_PORT || 9000)
  43. }
  44. /* ================= 工具 ================= */
  45. api(path) {
  46. return this.baseUrl + path
  47. }
  48. traceId() {
  49. return Date.now() + '_' + Math.random().toString(36).slice(2, 8)
  50. }
  51. sleep(ms) {
  52. return new Promise(r => setTimeout(r, ms))
  53. }
  54. isRunSuccess(bindResponse) {
  55. const payload = bindResponse?.data
  56. if (!bindResponse || bindResponse.status !== 1 || !payload) {
  57. return {
  58. ok: false,
  59. reason: bindResponse?.info || '系统繁忙,请联系客服或稍后再试'
  60. }
  61. }
  62. const failedReason = payload.record_failed_reason || ''
  63. if (failedReason === '' || failedReason === '自动确认有效') {
  64. return { ok: true, payload }
  65. }
  66. return {
  67. ok: false,
  68. reason: failedReason,
  69. payload
  70. }
  71. }
  72. extractApiErrorMessage(name, result) {
  73. if (!result) {
  74. this.logger.error(`${name} 接口无响应数据: ${this.safeStringify(result)}`)
  75. return `系统繁忙,请联系客服或稍后再试`
  76. }
  77. const candidates = [
  78. result.info,
  79. result.msg,
  80. result.message,
  81. result?.data?.info,
  82. result?.data?.msg,
  83. result?.data?.message,
  84. result?.data?.record_failed_reason
  85. ]
  86. const reason = candidates.find(v => typeof v === 'string' && v.trim() !== '')
  87. if (reason) {
  88. return reason
  89. }
  90. if (result.code !== undefined || result.status !== undefined) {
  91. this.logger.error(`${name} 接口返回异常: ${this.safeStringify(result)}`)
  92. return `系统繁忙,请联系客服或稍后再试`
  93. }
  94. return `系统繁忙,请联系客服或稍后再试`
  95. }
  96. async markLoginExpired(account) {
  97. if (!account) return
  98. try {
  99. const sql = 'UPDATE lepao_account SET state = 0 WHERE student_num = ?'
  100. await db.query(sql, [account])
  101. this.logger.warn(`${account} 登录状态已失效,已自动更新为未登录`)
  102. } catch (error) {
  103. this.logger.error(`更新账号登录状态失败:${error.stack || error}`)
  104. }
  105. }
  106. async writeSuccessRedis(account) {
  107. if (!account) return
  108. try {
  109. const now = new Date()
  110. const tomorrow = new Date().setHours(24, 0, 0, 0)
  111. const exp = Math.floor((tomorrow - now) / 1000)
  112. await Redis.set(`lepaoSuccess:${account}`, account, { EX: exp })
  113. } catch (error) {
  114. this.logger.error(`写入乐跑成功缓存失败: ${error.stack || error}`)
  115. }
  116. }
  117. async addLepaoRecord(uuid, account, result, pathId, pointData) {
  118. if (!uuid || !account || !result || !pathId) return
  119. try {
  120. const time = Date.now()
  121. const sql = 'INSERT INTO lepao_record (uuid, time, lepao_account, result, path_id, point_data, state) VALUES (?, ?, ?, ?, ?, ?, ?)'
  122. await db.query(sql, [uuid, time, account, result, pathId, JSON.stringify(pointData || []), 1])
  123. } catch (error) {
  124. this.logger.error(`写入乐跑记录失败: ${error.stack || error}`)
  125. }
  126. }
  127. async syncRunCount(req, ctx) {
  128. try {
  129. const sid = req?.student_id || req?.account
  130. if (
  131. req?.uid == null ||
  132. req?.token == null ||
  133. String(req.token).trim() === '' ||
  134. req?.school_id == null ||
  135. !sid
  136. ) {
  137. return { ok: false, reason: '缺少同步乐跑次数所需凭证' }
  138. }
  139. const recordData = await this.handlers['lepao.getRecord'](req, ctx)
  140. const data = recordData?.data
  141. if (!data) {
  142. return { ok: false, reason: 'getRecord 无有效 data' }
  143. }
  144. const term_num = Number(data.term_num ?? 30)
  145. const total_num = Number(data.total_num ?? 0)
  146. const sql = 'UPDATE lepao_account SET term_num = ?, total_num = ? WHERE student_num = ?'
  147. const rows = await db.query(sql, [term_num, total_num, req.account])
  148. if (!rows || rows.affectedRows !== 1) {
  149. this.logger.warn(`${req.account}更新乐跑次数失败`)
  150. return { ok: false, reason: '数据库更新 lepao_account 失败', term_num, total_num }
  151. }
  152. this.logger.info(`${req.account}更新乐跑次数成功 term_num=${term_num}, total_num=${total_num}`)
  153. return { ok: true, term_num, total_num }
  154. } catch (error) {
  155. this.logger.warn(`${req?.account || 'unknown'}同步乐跑次数失败: ${error.message || error}`)
  156. return { ok: false, reason: error.message || String(error) }
  157. }
  158. }
  159. lepaoTimestamp() {
  160. return Number((Date.now() / 1000).toFixed(3))
  161. }
  162. axiosProxyConfig() {
  163. if (!this.debugProxyEnabled) {
  164. return { proxy: false }
  165. }
  166. this.logger.info(`使用本地代理: ${this.debugProxyHost}:${this.debugProxyPort}`)
  167. return {
  168. proxy: {
  169. host: this.debugProxyHost,
  170. port: this.debugProxyPort,
  171. protocol: 'http'
  172. }
  173. }
  174. }
  175. async enqueueTask(channel, type, data, options = {}) {
  176. const payload = {
  177. id: options.id || this.traceId(),
  178. type,
  179. data,
  180. retry: options.retry ?? 0
  181. }
  182. await channel.sendToQueue(
  183. this.taskQueue,
  184. Buffer.from(JSON.stringify(payload)),
  185. { persistent: true, contentType: 'application/json' }
  186. )
  187. return payload.id
  188. }
  189. async withTimeout(promise, name) {
  190. return Promise.race([
  191. promise,
  192. new Promise((_, reject) =>
  193. setTimeout(() => reject(new Error(`${name} 超时`)), this.timeout)
  194. )
  195. ])
  196. }
  197. async retry(fn, name) {
  198. let lastErr
  199. for (let i = 0; i < this.maxRetry; i++) {
  200. try {
  201. return await fn()
  202. } catch (err) {
  203. lastErr = err
  204. if (!this.isRetryableTaskError(err)) {
  205. throw err
  206. }
  207. this.logger.warn(`[RETRY] ${name} 第${i + 1}次失败`)
  208. await this.sleep(1000 * (i + 1)) // 指数退避
  209. }
  210. }
  211. throw lastErr
  212. }
  213. isNetworkError(err) {
  214. if (!err) return false
  215. if (err.code && ['ECONNRESET', 'ECONNABORTED', 'ETIMEDOUT', 'ENOTFOUND', 'EAI_AGAIN'].includes(err.code)) {
  216. return true
  217. }
  218. if (err.isAxiosError && !err.response) return true
  219. const msg = (err.message || '').toLowerCase()
  220. return msg.includes('timeout') || msg.includes('network')
  221. }
  222. isRetryableTaskError(err) {
  223. if (!err) return false
  224. if (err.retryable === true) return true
  225. if (this.isNetworkError(err)) return true
  226. return ['PATH_SELECT_FAILED', 'CHECKPOINT_FETCH_FAILED', 'CHECKPOINT_INSUFFICIENT'].includes(err.code)
  227. }
  228. safeStringify(obj) {
  229. const seen = new WeakSet();
  230. return JSON.stringify(obj, (key, value) => {
  231. if (typeof value === 'object' && value !== null) {
  232. if (seen.has(value)) return '[Circular]';
  233. seen.add(value);
  234. }
  235. return value;
  236. })
  237. }
  238. log(traceId, type, msg, data) {
  239. this.logger.info(`[${traceId}] [${type}] ${msg} ${data ? this.safeStringify(data) : ''}`)
  240. }
  241. logErr(traceId, msg, err) {
  242. this.logger.error(`[${traceId}] ${msg} ${err.stack || err}`)
  243. }
  244. async request(traceId, name, url, raw, headers = {}) {
  245. return this.retry(async () => {
  246. this.log(traceId, 'REQ', name, raw)
  247. const mergedHeaders = {
  248. 'Content-Type': 'application/x-www-form-urlencoded',
  249. 'Accept': '*/*',
  250. 'Accept-Language': 'zh-CN,zh-Hans;q=0.9',
  251. 'Accept-Encoding': 'gzip, deflate, br',
  252. 'Referer': 'https://servicewechat.com/wxf94c4ddb63d87ede/32/page-frame.html',
  253. ...headers
  254. }
  255. if (!mergedHeaders['User-Agent']) {
  256. mergedHeaders['User-Agent'] = this.defaultUserAgent
  257. }
  258. const form = new URLSearchParams()
  259. form.append('ostype', '5')
  260. form.append('data', dataEncrypt(JSON.stringify(raw)))
  261. const res = await this.withTimeout(
  262. axios.post(
  263. url,
  264. form,
  265. {
  266. headers: mergedHeaders,
  267. ...this.axiosProxyConfig()
  268. }
  269. ),
  270. name
  271. )
  272. let result = res.data
  273. if (result?.data && result?.is_encrypt === 1) {
  274. result.data = JSON.parse(dataDecrypt(result.data))
  275. }
  276. this.log(traceId, 'RES', name, result)
  277. // 除 bindData 外,其余调用若接口已明确返回失败,直接抛出该失败原因
  278. // bindData 需要保留完整响应由 isRunSuccess 统一判定。
  279. if (name !== 'bindData') {
  280. const hasCode = result && Object.prototype.hasOwnProperty.call(result, 'code')
  281. const hasStatus = result && Object.prototype.hasOwnProperty.call(result, 'status')
  282. const failedByCode = hasCode && Number(result.code) !== 1 && Number(result.code) !== 200
  283. const failedByStatus = hasStatus && Number(result.status) !== 1
  284. if (failedByCode || failedByStatus) {
  285. const message = this.extractApiErrorMessage(name, result)
  286. const err = new Error(message)
  287. // 学习 Lepao.js:若明确提示重新登录,自动标记账号失效
  288. if (message.includes('重新登录')) {
  289. await this.markLoginExpired(raw?.student_num)
  290. }
  291. // 接口已返回业务错误,禁止重试
  292. err.retryable = false
  293. throw err
  294. }
  295. }
  296. return result
  297. }, name)
  298. }
  299. /**
  300. * 累计完成次数 >= 跑友目标(且目标>0)时:关闭 auto_run,并发送乐跑目标完成邮件 / Bot 通知
  301. */
  302. async handleLepaoTargetComplete(account, user, totalNum, traceId) {
  303. const target = Number(user?.target_count) || 0
  304. const total = Number(totalNum) || 0
  305. if (target <= 0 || total < target) return
  306. try {
  307. const up = await db.query(
  308. 'UPDATE lepao_account SET auto_run = 0 WHERE student_num = ? AND auto_run = 1',
  309. [account]
  310. )
  311. if (up?.affectedRows !== 1) {
  312. return
  313. }
  314. this.logger.info(
  315. `${account} 已达目标次数(${total}/${target}),关闭自动乐跑`
  316. )
  317. } catch (e) {
  318. this.logger.error(`关闭自动乐跑失败 ${account}: ${e.message || e}`)
  319. return
  320. }
  321. const noticeType = user.notice_type || 'none'
  322. const overPayload = {
  323. type: 'lepao_over',
  324. umo: user.bot_umo,
  325. name: user.name,
  326. account,
  327. total_num: total,
  328. target_count: target,
  329. traceId
  330. }
  331. if (noticeType === 'email' && user.email) {
  332. try {
  333. await EmailTemplate.lepaoOver(user.email, {
  334. name: user.name,
  335. account
  336. })
  337. } catch (e) {
  338. this.logger.error(`lepaoOver 邮件发送失败: ${e.message || e}`)
  339. }
  340. }
  341. if (noticeType === 'bot' && user.bot_umo) {
  342. try {
  343. const ch = await mq.getChannel(this.noticeQueue)
  344. await ch.assertQueue(this.noticeQueue, { durable: true })
  345. ch.sendToQueue(
  346. this.noticeQueue,
  347. Buffer.from(JSON.stringify(overPayload)),
  348. {
  349. persistent: true,
  350. contentType: 'application/json'
  351. }
  352. )
  353. } catch (e) {
  354. this.logger.error(`lepao_over Bot 通知失败: ${e.message || e}`)
  355. }
  356. }
  357. }
  358. register(type, handler) {
  359. this.handlers[type] = handler
  360. this.logger.info(`注册任务: ${type}`)
  361. }
  362. /* ================= 业务 ================= */
  363. initHandlers() {
  364. /* ---------------- 开始乐跑 ---------------- */
  365. this.register('lepao.startRun', async (req, ctx) => {
  366. const traceId = ctx.traceId
  367. const maxPathRetry = 20 // 自动获取路径失败最大重试次数
  368. let pathRetry = 0
  369. let pointData = null
  370. let ossPath = null
  371. let userData = null
  372. let pathId = null
  373. let runZoneId = 0
  374. let bindRes = null
  375. try {
  376. // 检查redis是否存在当天乐跑成功记录
  377. const isSuccess = await Redis.get(`lepaoSuccess:${req.account}`)
  378. if (isSuccess)
  379. throw new Error('该账号当天已乐跑成功!请勿重复乐跑')
  380. userData = await this.handlers['lepao.getUserData'](req, ctx)
  381. // 立刻合并账号凭证,保证后续任意 throw 时 finally 里 syncRunCount 不会用空 token 调 getRecord
  382. req = {
  383. ...req,
  384. ...userData,
  385. student_id: req.account
  386. }
  387. // 进入乐跑进程后写入进行中缓存
  388. const progressKey = `lepaoProgress:${req.account}`
  389. const inProgress = await Redis.get(progressKey)
  390. if (inProgress) {
  391. throw new Error('该账号已进入乐跑任务队列,请等待乐跑完成后再进行乐跑操作')
  392. }
  393. await Redis.set(progressKey, req.account, { EX: 1800 })
  394. // 晚上10点后提前
  395. let run_end_time = Math.floor(Date.now() / 1000) - 300 // 提前5分钟
  396. let hour = new Date().getHours()
  397. if (hour < 7)
  398. throw new Error('当前不在有效乐跑时间范围内。RunForge支持乐跑时间段为7:00~24:00')
  399. if (hour >= 22) {
  400. this.logger.info(`${req.account}当前时间为${hour}点,调整run_end_time提前5小时`)
  401. run_end_time -= 18000
  402. }
  403. req = {
  404. ...req,
  405. run_end_time
  406. }
  407. // 1.5️⃣ 乐跑开始前扣减次数(失败会返还,且有幂等保护)
  408. await this.handlers['lepao.consumeCount']({
  409. account: req.account,
  410. uuid: userData?.create_user
  411. }, ctx)
  412. while (pathRetry < maxPathRetry) {
  413. try {
  414. // 2️⃣ 获取路径(仅路径选择失败时重试)
  415. const pathRes = await this.handlers['lepao.getPath'](req, ctx)
  416. pathId = pathRes.path_id
  417. // 3️⃣ 切换跑区
  418. const zoneRes = await this.handlers['lepao.setZone']({ ...req, random_id: pathId }, ctx)
  419. runZoneId = zoneRes?.run_zone_id || 0
  420. // 4️⃣ 上传 OSS 文件、生成打卡点
  421. const uploadRes = await this.handlers['lepao.uploadOssFile']({ ...req, random_id: pathId }, ctx)
  422. ossPath = uploadRes.oss_path
  423. pointData = uploadRes.point_data
  424. if (!pointData) {
  425. pathRetry++
  426. this.logger.warn(`[${traceId}] 打卡点不满足要求,重新获取路径 第${pathRetry}次`)
  427. continue
  428. }
  429. // 打卡点符合要求,跳出循环
  430. break
  431. } catch (err) {
  432. if (!this.isRetryableTaskError(err)) {
  433. throw err
  434. }
  435. this.logger.warn(`[${traceId}] 可重试错误,重新获取路径 第${pathRetry + 1}次,原因:${err.message}`)
  436. pathRetry++
  437. await this.sleep(1000 * pathRetry)
  438. }
  439. }
  440. if (!pointData) {
  441. throw new Error('打卡点获取失败,乐跑任务终止')
  442. }
  443. // 5️⃣ 提交跑步数据
  444. bindRes = await this.handlers['lepao.bindData']({
  445. ...req,
  446. random_id: pathId,
  447. run_zone_id: runZoneId,
  448. record_file: ossPath,
  449. point_data: pointData
  450. }, ctx)
  451. // 绑定接口有返回即入库
  452. if (bindRes && bindRes.data) {
  453. await this.addLepaoRecord(userData?.create_user, req.account, bindRes.data, pathId, pointData)
  454. }
  455. const runResult = this.isRunSuccess(bindRes)
  456. if (runResult.ok || runResult.reason === '当天关联成绩次数已达到上限') {
  457. await this.writeSuccessRedis(req.account)
  458. }
  459. if (!runResult.ok) {
  460. throw new Error(runResult.reason)
  461. }
  462. // 同步乐跑次数(通知里要带 total_num / term_num,与 getRecord 一致)
  463. const syncResult = await this.syncRunCount(req, ctx)
  464. if (!syncResult?.ok) {
  465. this.logger.error(
  466. `[${traceId}] 同步乐跑次数失败:${syncResult?.reason || 'unknown'}`
  467. )
  468. }
  469. // 6️⃣ 发送通知(把同步后的学期次数、累计完成次数传给 Bot / 邮件)
  470. if (ctx.channel) {
  471. await this.enqueueTask(
  472. ctx.channel,
  473. 'lepao.sendNotice',
  474. {
  475. account: req.account,
  476. success: true,
  477. data: runResult.payload,
  478. traceId,
  479. total_num: syncResult?.ok ? syncResult.total_num : undefined
  480. },
  481. { id: `${traceId}:notice:success` }
  482. )
  483. }
  484. return { traceId, ossPath, pointData, bindRes }
  485. } catch (err) {
  486. this.logger.error(`[${traceId}] 乐跑流程失败:`, err)
  487. // 若已扣减次数,则失败时返还(幂等)
  488. try {
  489. await this.handlers['lepao.refundCount']({
  490. account: req.account,
  491. uuid: userData?.create_user
  492. }, ctx)
  493. } catch (e) {
  494. this.logger.error(`[${traceId}] 返还乐跑次数失败:${e.stack || e}`)
  495. }
  496. if (ctx.channel) {
  497. await this.enqueueTask(ctx.channel, 'lepao.sendNotice', {
  498. account: req.account,
  499. success: false,
  500. reason: err.message || '未知错误',
  501. traceId
  502. }, { id: `${traceId}:notice:fail` })
  503. }
  504. // 将失败消息发送到结果队列或死信队列
  505. if (ctx.channel) {
  506. await this.sendResult(ctx.channel, {
  507. id: req.taskId,
  508. success: false,
  509. error: err.message
  510. })
  511. await ctx.channel.sendToQueue(
  512. this.deadQueue,
  513. Buffer.from(JSON.stringify({ ...req, error: err.message })),
  514. { persistent: true }
  515. )
  516. }
  517. throw err
  518. } finally {
  519. await Redis.del(`lepaoProgress:${req.account}`)
  520. }
  521. })
  522. /* ---------------- 发送通知(独立 MQ 任务) ---------------- */
  523. this.register('lepao.sendNotice', async (req, ctx) => {
  524. const { account, success, data, reason, traceId, total_num: totalNumArg } = req || {}
  525. if (!account) {
  526. throw new Error('发送通知失败:缺少 account')
  527. }
  528. const emailSql = `
  529. SELECT
  530. a.name,
  531. a.email,
  532. a.target_count,
  533. a.notice_type,
  534. e.bot_umo
  535. FROM
  536. lepao_account a
  537. LEFT JOIN
  538. lepao_extra e
  539. ON
  540. a.student_num = e.student_num
  541. WHERE
  542. a.student_num = ?
  543. `
  544. const rows = await db.query(emailSql, [account])
  545. if (!rows || rows.length === 0) {
  546. throw new Error('发送通知失败:未找到用户通知配置')
  547. }
  548. const user = rows[0]
  549. const noticeType = user.notice_type || 'none'
  550. let totalForNotice = totalNumArg
  551. if (
  552. success &&
  553. (totalForNotice === undefined || totalForNotice === null)
  554. ) {
  555. const accRows = await db.query(
  556. 'SELECT total_num FROM lepao_account WHERE student_num = ?',
  557. [account]
  558. )
  559. if (accRows && accRows[0]) {
  560. totalForNotice = accRows[0].total_num
  561. }
  562. }
  563. if (totalForNotice === undefined || totalForNotice === null) {
  564. totalForNotice = 0
  565. }
  566. totalForNotice = Number(totalForNotice)
  567. const targetCount = Number(user.target_count) || 0
  568. const payload = success ? {
  569. ...(data && typeof data === 'object' ? data : {}),
  570. type: 'lepao_success',
  571. umo: user.bot_umo,
  572. total_num: totalForNotice,
  573. target_count: targetCount,
  574. name: user.name,
  575. account,
  576. traceId
  577. } : {
  578. type: 'lepao_fail',
  579. umo: user.bot_umo,
  580. name: user.name,
  581. account,
  582. reason,
  583. traceId
  584. }
  585. const afterSuccessNotify = async () => {
  586. if (success) {
  587. await this.handleLepaoTargetComplete(account, user, totalForNotice, traceId)
  588. }
  589. }
  590. if (noticeType === 'bot' && user.bot_umo) {
  591. const ch = await mq.getChannel(this.noticeQueue)
  592. await ch.assertQueue(this.noticeQueue, { durable: true })
  593. ch.sendToQueue(
  594. this.noticeQueue,
  595. Buffer.from(JSON.stringify(payload)),
  596. {
  597. persistent: true,
  598. contentType: 'application/json'
  599. }
  600. )
  601. await afterSuccessNotify()
  602. return { delivered: true, via: 'bot' }
  603. }
  604. if (noticeType === 'email' && user.email) {
  605. if (success) {
  606. await EmailTemplate.lepaoSuccess(user.email, payload)
  607. await afterSuccessNotify()
  608. return { delivered: true, via: 'email' }
  609. }
  610. await EmailTemplate.lepaoFail(user.email, {
  611. name: user.name,
  612. account,
  613. reason: reason || '系统繁忙,请联系客服或稍后再试',
  614. traceId
  615. })
  616. return { delivered: true, via: 'email' }
  617. }
  618. await afterSuccessNotify()
  619. return { delivered: false, via: 'none' }
  620. })
  621. /* ---------------- 扣减次数 ---------------- */
  622. this.register('lepao.consumeCount', async (req, ctx) => {
  623. const account = req?.account
  624. const uuid = req?.uuid
  625. if (!uuid) {
  626. throw new Error('扣减乐跑次数失败:缺少 uuid')
  627. }
  628. // 幂等:同一 taskId 只扣一次
  629. const consumeKey = `lepao:consume:${ctx?.taskId || ctx?.traceId || account || uuid}`
  630. const existed = await Redis.get(consumeKey)
  631. if (existed) {
  632. return true
  633. }
  634. this.logger.info(`${account || uuid}开始扣减乐跑次数`)
  635. const useLepaoCountSql = 'UPDATE users SET lepao_count = lepao_count - 1 WHERE uuid = ?'
  636. const r = await db.query(useLepaoCountSql, [uuid])
  637. if (!r || r.affectedRows !== 1) {
  638. throw new Error('扣减乐跑次数失败:数据库更新失败')
  639. }
  640. this.logger.info(`${account || uuid}扣减乐跑次数完成`)
  641. await Redis.set(consumeKey, '1', { EX: 3600 })
  642. return true
  643. })
  644. /* ---------------- 返还次数(失败时执行) ---------------- */
  645. this.register('lepao.refundCount', async (req, ctx) => {
  646. const account = req?.account
  647. const uuid = req?.uuid
  648. if (!uuid) {
  649. return true
  650. }
  651. const baseKey = `${ctx?.taskId || ctx?.traceId || account || uuid}`
  652. const consumeKey = `lepao:consume:${baseKey}`
  653. const refundKey = `lepao:refund:${baseKey}`
  654. const consumed = await Redis.get(consumeKey)
  655. if (!consumed) {
  656. return true
  657. }
  658. const refunded = await Redis.get(refundKey)
  659. if (refunded) {
  660. return true
  661. }
  662. this.logger.info(`${account || uuid}开始返还乐跑次数`)
  663. const sql = 'UPDATE users SET lepao_count = lepao_count + 1 WHERE uuid = ?'
  664. const r = await db.query(sql, [uuid])
  665. if (!r || r.affectedRows !== 1) {
  666. throw new Error('返还乐跑次数失败:数据库更新失败')
  667. }
  668. this.logger.info(`${account || uuid}返还乐跑次数完成`)
  669. await Redis.set(refundKey, '1', { EX: 3600 })
  670. return true
  671. })
  672. this.register('lepao.getUserData', async (req, ctx) => {
  673. const account = req.account
  674. this.logger.info(`${account}开始获取用户数据`)
  675. const accountSql = `
  676. SELECT
  677. u.uuid,
  678. u.lepao_count,
  679. l.create_user,
  680. l.name,
  681. l.student_num,
  682. l.area,
  683. l.sex,
  684. l.state,
  685. l.token,
  686. l.uid,
  687. l.school_id,
  688. l.userAgent,
  689. l.deviceModel,
  690. l.notice_type,
  691. l.email,
  692. e.bot_account
  693. FROM
  694. lepao_account l
  695. LEFT JOIN
  696. users u
  697. ON
  698. l.create_user = u.uuid
  699. LEFT JOIN
  700. lepao_extra e
  701. ON
  702. l.student_num = e.student_num
  703. WHERE
  704. l.student_num = ?
  705. `
  706. const rows = await db.query(accountSql, [account])
  707. if (!rows || rows.length === 0) {
  708. this.logger.error(`${account}无法获取账号数据`)
  709. throw new Error('无法获取账号数据,请联系客服或稍后再试')
  710. }
  711. let userData = rows[0]
  712. if (!userData.create_user || !userData.uuid) {
  713. this.logger.warn(`${account}账号状态异常`)
  714. throw new Error('当前账号状态异常,请联系客服')
  715. }
  716. if (userData.state !== 1) {
  717. this.logger.warn(`${account}登录状态异常 state=${userData.state}`)
  718. throw new Error('乐跑账号登录已过期,请尝试使用登录器重新登录')
  719. }
  720. if (userData.lepao_count < 1) {
  721. this.logger.warn(`${account}乐跑次数不足`)
  722. throw new Error('用户乐跑次数不足,请购买乐跑次数后重试!')
  723. }
  724. if (!userData.userAgent)
  725. userData.userAgent = 'Mozilla/5.0 (Linux; Android 16; 2211133C Build/BP2A.250605.031.A3; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/138.0.7204.180 Mobile Safari/537.36 XWEB/1380347 MMWEBSDK/20250202 MMWEBID/1020 wxwork/5.0.6.66174 MicroMessenger/8.0.28.48(0x28001c30) MiniProgramEnv/android Luggage/3.0.2.95ef3f83 NetType/WIFI Language/zh_CN ABI/arm64'
  726. if (!userData.deviceModel)
  727. userData.deviceModel = '2211133C'
  728. return userData
  729. })
  730. this.register('lepao.getPath', async (req, ctx) => {
  731. const account = req.account
  732. this.logger.info(`${account}开始获取路径`)
  733. const accountSql = 'SELECT area, sex FROM lepao_account WHERE student_num = ?'
  734. const rows = await db.query(accountSql, [account])
  735. if (!rows || rows.length === 0) {
  736. this.logger.error(`${account}无法获取账号数据`)
  737. throw new Error('无法获取账号数据')
  738. }
  739. const { area, sex } = rows[0]
  740. let max = 4.00
  741. let min = 2.00
  742. if (sex === 2) {
  743. max = 2.00
  744. min = 1.60
  745. }
  746. this.logger.info(`${account}路径参数: area=${area ?? '随机'}, max_distance=${max}, min_distance=${min}`)
  747. let pathSql = 'SELECT id FROM path_data WHERE state = 1 AND distance < ? AND distance > ? '
  748. const pathParams = [max, min]
  749. if (area) {
  750. pathSql += ' AND run_zone_name = ?'
  751. pathParams.push(area)
  752. }
  753. pathSql += ' ORDER BY count ASC LIMIT 1'
  754. const paths = await db.query(pathSql, pathParams)
  755. if (!paths || paths.length === 0) {
  756. this.logger.error(`${account}未找到符合条件的路线`)
  757. const err = new Error('未找到符合条件的路线,请改变路径选择条件')
  758. err.code = 'PATH_SELECT_FAILED'
  759. err.retryable = true
  760. throw err
  761. }
  762. const randomPath = paths[0]
  763. const updateSql = 'UPDATE path_data SET count = count + 1 WHERE id = ?'
  764. await db.query(updateSql, [randomPath.id])
  765. this.logger.info(`${account}路径选中id=${randomPath.id},计数加1成功`)
  766. return { path_id: randomPath.id }
  767. })
  768. /* ---------------- 获取跑步记录 ---------------- */
  769. this.register('lepao.getRecord', async (req, ctx) => {
  770. const now = this.lepaoTimestamp()
  771. const raw = {
  772. uid: req.uid,
  773. token: req.token,
  774. school_id: req.school_id,
  775. term_id: 0,
  776. course_id: 0,
  777. class_id: 0,
  778. student_num: req.student_id,
  779. card_id: req.student_id,
  780. timestamp: now,
  781. version: 1,
  782. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  783. ostype: 5
  784. }
  785. raw.sign = dataSign(raw)
  786. return this.request(
  787. ctx.traceId,
  788. 'getRecord',
  789. this.api('/Run2/beforeRunV260'),
  790. raw,
  791. {
  792. 'User-Agent': req.userAgent,
  793. 'charset': 'utf-8',
  794. 'Referer': 'https://servicewechat.com/wxf94c4ddb63d87ede/32/page-frame.html',
  795. }
  796. )
  797. })
  798. /* ---------------- 切换跑区 ---------------- */
  799. this.register('lepao.setZone', async (req, ctx) => {
  800. const runZoneMap = {
  801. '兰花湖校区跑区': 2,
  802. '主校区北跑区': 3,
  803. '主校区南跑区': 5,
  804. '重庆工商大学茶园校区': 6
  805. }
  806. const record = await db.query(
  807. 'SELECT run_zone_name FROM path_data WHERE id = ?',
  808. [req.random_id]
  809. )
  810. if (!record || record.length === 0) {
  811. throw new Error('跑区不存在')
  812. }
  813. const runZoneId = runZoneMap[record[0].run_zone_name]
  814. if (!runZoneId) throw new Error('跑区不存在')
  815. const raw = {
  816. uid: req.uid,
  817. token: req.token,
  818. school_id: req.school_id,
  819. term_id: 0,
  820. course_id: 0,
  821. class_id: 0,
  822. student_num: req.student_id,
  823. card_id: req.student_id,
  824. timestamp: this.lepaoTimestamp(),
  825. version: 1,
  826. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  827. ostype: 5,
  828. run_zone_id: String(runZoneId)
  829. }
  830. raw.sign = dataSign(raw)
  831. await this.request(
  832. ctx.traceId,
  833. 'setZone',
  834. this.api('/Run/setRunZone'),
  835. raw
  836. )
  837. return { run_zone_id: runZoneId }
  838. })
  839. /* ---------------- 获取 OSS STS ---------------- */
  840. this.register('lepao.getOssSts', async (req, ctx) => {
  841. const raw = {
  842. uid: req.uid,
  843. token: req.token,
  844. school_id: req.school_id,
  845. term_id: 0,
  846. course_id: 0,
  847. class_id: 0,
  848. student_num: req.student_id,
  849. card_id: req.student_id,
  850. timestamp: this.lepaoTimestamp(),
  851. version: 1,
  852. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  853. ostype: 5
  854. }
  855. raw.sign = dataSign(raw)
  856. const res = await this.request(
  857. ctx.traceId,
  858. 'getOssSts',
  859. this.api('/WpIndex/getOssSts'),
  860. raw
  861. )
  862. return res.data
  863. })
  864. /* ---------------- 上传 OSS 文件 ---------------- */
  865. this.register('lepao.uploadOssFile', async (req, ctx) => {
  866. const pathRow = await db.query(
  867. 'SELECT * FROM path_data WHERE id=?',
  868. [req.random_id]
  869. )
  870. if (!pathRow || pathRow.length === 0) {
  871. throw new Error('路径数据不存在')
  872. }
  873. const pathData = pathRow[0]
  874. // 处理跑步路径
  875. const newPathData = getPathData(pathData.data, req.run_end_time, pathData.time)
  876. const pathResult = dataEncrypt(JSON.stringify(newPathData))
  877. // 获取跑步规则参数
  878. const runRule = await this.handlers['lepao.getRecord'](req, ctx)
  879. const ruleData = runRule?.data
  880. if (!ruleData?.run_line_info?.point_list || !ruleData?.time_rule_arr?.length) {
  881. const err = new Error('获取打卡点规则失败')
  882. err.code = 'CHECKPOINT_FETCH_FAILED'
  883. err.retryable = true
  884. throw err
  885. }
  886. const check_points = ruleData.run_line_info.point_list
  887. let min_log_num = ruleData.time_rule_arr[0]?.min_log_num || 4
  888. const point_update_distance = parseFloat(ruleData.run_line_info.point_update_distance || 0) * 1000
  889. const log_max_distance = Number(ruleData.run_line_info.log_max_distance || 0)
  890. // 生成打卡点
  891. const point_data = selectCheckpoints(newPathData, check_points, min_log_num, point_update_distance, log_max_distance, req.run_end_time, pathData.time)
  892. if (!point_data) {
  893. this.logger.warn(`[RETRY] 打卡点数量不足,重新更换路径`)
  894. const err = new Error('打卡点数量不足')
  895. err.code = 'CHECKPOINT_INSUFFICIENT'
  896. err.retryable = true
  897. throw err
  898. }
  899. const sts = await this.handlers['lepao.getOssSts'](req, ctx)
  900. if (!sts?.bucket || !sts?.AccessKeyId || !sts?.AccessKeySecret || !sts?.SecurityToken) {
  901. throw new Error('获取 OSS STS 失败')
  902. }
  903. const now = new Date()
  904. const yyyy = now.getFullYear()
  905. const mm = String(now.getMonth() + 1).padStart(2, '0')
  906. const dd = String(now.getDate()).padStart(2, '0')
  907. const formattedToday = `${yyyy}-${mm}-${dd}`
  908. const boundary = String(Date.now())
  909. const timestamp = String(Date.now())
  910. const ossPath = `Public/Upload/file/run_record/${boundary.slice(-3)}/${formattedToday}/${timestamp}-${Math.floor(Math.random() * 150)}.txt`
  911. const client = new OSS({
  912. bucket: sts.bucket,
  913. region: sts.region || 'oss-cn-hangzhou',
  914. accessKeyId: sts.AccessKeyId,
  915. accessKeySecret: sts.AccessKeySecret,
  916. stsToken: sts.SecurityToken,
  917. secure: true
  918. })
  919. await client.put(ossPath, Buffer.from(pathResult, 'utf-8'))
  920. return { oss_path: ossPath, point_data: point_data }
  921. })
  922. /* ---------------- 提交跑步数据 ---------------- */
  923. this.register('lepao.bindData', async (req, ctx) => {
  924. if (req?.random_id === undefined || req?.random_id === null || req?.random_id === '') {
  925. throw new Error('提交跑步数据失败:缺少 random_id')
  926. }
  927. const pathRow = await db.query(
  928. 'SELECT * FROM path_data WHERE id=?',
  929. [req.random_id]
  930. )
  931. if (!pathRow || pathRow.length === 0) {
  932. throw new Error(`提交跑步数据失败:未找到路径数据(random_id=${req.random_id})`)
  933. }
  934. const pathData = pathRow[0]
  935. const distance = Number(Number(pathData.distance || 0).toFixed(2))
  936. const stepData = generateCadence(distance, pathData.time)
  937. const stepInfo = JSON.stringify({ interval: 60, list: stepData.cadence_list })
  938. let points = req.point_data.map(({ address, jingwei, ...rest }) => rest)
  939. points = JSON.stringify(points)
  940. const data = {
  941. uid: req.uid,
  942. token: req.token,
  943. school_id: req.school_id,
  944. term_id: 1,
  945. course_id: 0,
  946. class_id: 0,
  947. student_num: req.student_id,
  948. card_id: req.student_id,
  949. timestamp: this.lepaoTimestamp(),
  950. version: 1,
  951. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  952. ostype: 5,
  953. game_id: String(req.run_zone_id || 0),
  954. start_time: req.run_end_time - Number(pathData.time),
  955. end_time: req.run_end_time,
  956. distance,
  957. record_img: "",
  958. log_data: points,
  959. file_img: "",
  960. is_running_area_valid: 1,
  961. mobileDeviceId: 1,
  962. mobileModel: req.deviceModel,
  963. step_info: stepInfo,
  964. step_num: stepData.total_steps,
  965. used_time: pathData.time,
  966. mobileOsVersion: 1,
  967. record_file: req.record_file
  968. }
  969. data.sign = dataSign(data)
  970. return this.request(
  971. ctx.traceId,
  972. 'bindData',
  973. this.api('/Run/stopRunV278'),
  974. data
  975. )
  976. })
  977. }
  978. /* ================= Worker核心 ================= */
  979. async start() {
  980. if (this.running) return
  981. this.running = true
  982. this.logger.info('Worker 启动中...')
  983. try {
  984. this.initHandlers()
  985. const channel = await mq.getChannel(this.channelName)
  986. await channel.prefetch(5)
  987. await assertRunforgeTaskIngress(channel, this.logger)
  988. await channel.assertQueue(this.resultQueue, { durable: true })
  989. await channel.assertQueue(this.deadQueue, { durable: true })
  990. await channel.consume(this.taskQueue, async (msg) => {
  991. if (!msg) return
  992. let content
  993. try {
  994. content = JSON.parse(msg.content.toString())
  995. } catch {
  996. return channel.ack(msg)
  997. }
  998. const { id, type, data, retry = 0 } = content
  999. const traceId = this.traceId()
  1000. const handler = this.handlers[type]
  1001. if (!handler) {
  1002. this.log(traceId, 'ERROR', '未知任务', { type })
  1003. return channel.ack(msg)
  1004. }
  1005. try {
  1006. const result = await this.withTimeout(
  1007. handler(data, { traceId, channel, taskId: id }),
  1008. type
  1009. )
  1010. await this.sendResult(channel, {
  1011. id,
  1012. success: true,
  1013. result
  1014. })
  1015. this.log(traceId, 'DONE', `任务完成 ${type}`)
  1016. channel.ack(msg)
  1017. } catch (err) {
  1018. this.logErr(traceId, `任务失败 ${type}`, err)
  1019. if (retry < this.maxRetry && this.isRetryableTaskError(err)) {
  1020. // 重试
  1021. await channel.sendToQueue(
  1022. this.taskQueue,
  1023. Buffer.from(JSON.stringify({
  1024. ...content,
  1025. retry: retry + 1
  1026. })),
  1027. { persistent: true }
  1028. )
  1029. this.log(traceId, 'RETRY', `重试第${retry + 1}次`)
  1030. } else {
  1031. // 死信
  1032. await channel.sendToQueue(
  1033. this.deadQueue,
  1034. Buffer.from(JSON.stringify(content)),
  1035. { persistent: true }
  1036. )
  1037. this.log(traceId, 'DEAD', '进入死信队列')
  1038. }
  1039. await this.sendResult(channel, {
  1040. id,
  1041. success: false,
  1042. error: err.message
  1043. })
  1044. channel.ack(msg)
  1045. }
  1046. })
  1047. this.logger.info('RunForge Worker 启动成功')
  1048. } catch (err) {
  1049. this.logger.error('RunForge Worker 启动失败: ' + err.stack)
  1050. }
  1051. }
  1052. async sendResult(channel, data) {
  1053. channel.sendToQueue(
  1054. this.resultQueue,
  1055. Buffer.from(JSON.stringify(data)),
  1056. { persistent: true }
  1057. )
  1058. }
  1059. async stop() {
  1060. this.running = false
  1061. await mq.close()
  1062. this.logger.info('RunForge Worker 已停止')
  1063. }
  1064. }
  1065. module.exports = Worker