Worker.js 47 KB

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