Worker.js 41 KB

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