Worker.js 39 KB

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