Worker.js 41 KB

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