Worker.js 41 KB

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