Worker.js 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704
  1. const path = require('path')
  2. const mq = require('../../plugin/mq')
  3. const { mq: mqName } = require('../../plugin/mq/mqPrefix')
  4. const { assertRunforgeTaskIngress, TASK_QUEUE } = require('../../plugin/mq/runforgeTaskMq')
  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 { v4: uuidv4 } = require('uuid')
  15. const {
  16. dataEncrypt,
  17. dataDecrypt,
  18. dataSign
  19. } = require('../../plugin/Lepao/Crypto')
  20. const generateGyrFromPath = require('../../plugin/Lepao/generateGyrFromPath')
  21. const { syncAccountInfo } = require('./syncAccountInfo')
  22. const { postLepaoSchool } = require('./lepaoSchoolHttp')
  23. const { putOssWithQgOutbound } = require('./qgOssPut')
  24. const { isProxyForwardEnabled } = require('../ProxyForwardClient')
  25. const { insertLedgerRecord } = require('./CountLedger')
  26. const WeixinBindingService = require('../AIChat/WeixinBindingService')
  27. const LepaoWechatTemplate = require('../../plugin/Wechat/lepaoWechatTemplate')
  28. const Logger = require('../Logger')
  29. class Worker {
  30. constructor() {
  31. this.logger = new Logger(
  32. path.join(__dirname, '../logs/LepaoWorker.log'),
  33. 'INFO'
  34. )
  35. this.handlers = {}
  36. this.running = false
  37. this.baseUrl = 'https://lepao.ctbu.edu.cn/v3/api.php'
  38. this.taskQueue = TASK_QUEUE
  39. this.resultQueue = mqName('runforge_task_result_queue')
  40. this.deadQueue = mqName('runforge_task_dead_queue')
  41. this.noticeQueue = mqName('runforge_message_queue')
  42. this.channelName = 'lepao_worker'
  43. this.stopping = false
  44. this.restartTimer = null
  45. this.maxRetry = 5
  46. /** 单次学校接口 HTTP 超时(用于 this.request 内部) */
  47. this.httpTimeoutMs = 30000
  48. /** 单个 MQ 任务总超时(覆盖 startRun 多阶段 + 重试) */
  49. this.taskTimeoutMs = 180000
  50. this.maxQueueLength = 2000
  51. 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'
  52. // HTTP 出站(charles/fiddler / 青果)由 lepaoSchoolHttp 统一管理:LEPAO_DEBUG_PROXY=1 时强制走本地调试代理。
  53. }
  54. /* ================= 工具 ================= */
  55. formatYmdLocal(d = new Date()) {
  56. const yyyy = d.getFullYear()
  57. const mm = String(d.getMonth() + 1).padStart(2, '0')
  58. const dd = String(d.getDate()).padStart(2, '0')
  59. return `${yyyy}-${mm}-${dd}`
  60. }
  61. simpleHash(str) {
  62. const s = String(str || '')
  63. let h = 0
  64. for (let i = 0; i < s.length; i++) {
  65. h = ((h << 5) - h + s.charCodeAt(i)) | 0
  66. }
  67. return (h >>> 0).toString(16)
  68. }
  69. isCommonLepaoErrorMessage(msg) {
  70. const m = String(msg || '')
  71. return (
  72. m.includes('已乐跑成功') ||
  73. m.includes('已存在成功跑步记录') ||
  74. m.includes('不在有效乐跑时间范围内') ||
  75. m.includes('登录已过期') ||
  76. m.includes('登录信息失效') ||
  77. m.includes('登录失效') ||
  78. m.includes('登录状态异常') ||
  79. m.includes('已达到上限') ||
  80. m.includes('次数不足') ||
  81. m.includes('请重新登录')
  82. )
  83. }
  84. async notifyAdminsUncommonLepaoError(payload) {
  85. try {
  86. const { account, traceId, taskType, reason, code, name } = payload || {}
  87. if (!account || !reason) return
  88. if (this.isCommonLepaoErrorMessage(reason)) return
  89. const day = this.formatYmdLocal()
  90. const msgHash = this.simpleHash(reason)
  91. const rateKey = `lepao:adminWarn:${account}:${day}:${msgHash}`
  92. const existed = await Redis.get(rateKey)
  93. if (existed) return
  94. await Redis.set(rateKey, '1', { EX: 86400 })
  95. const adminSql = `
  96. SELECT email
  97. FROM users
  98. WHERE email IS NOT NULL
  99. AND email <> ''
  100. AND (JSON_CONTAINS(permission, '"admin"') OR JSON_CONTAINS(permission, '"service"'))
  101. `
  102. const adminRows = await db.query(adminSql)
  103. if (!adminRows || adminRows.length === 0) {
  104. this.logger.warn(`[lepaoAdminWarn][${traceId}] 未找到可通知的管理员邮箱`)
  105. return
  106. }
  107. const emails = [...new Set(adminRows.map(r => r.email).filter(Boolean))]
  108. for (const email of emails) {
  109. await EmailTemplate.lepaoAdminWarning(email, {
  110. server: (() => {
  111. try {
  112. // config.json 可能在其他模块缓存读取,这里动态 require 一次避免循环依赖
  113. // eslint-disable-next-line global-require
  114. const cfg = require('../../config.json')
  115. return cfg?.server || ''
  116. } catch (_) {
  117. return ''
  118. }
  119. })(),
  120. account,
  121. name: name || '',
  122. taskType: taskType || 'lepao.startRun',
  123. traceId: traceId || '',
  124. reason,
  125. code: code || ''
  126. })
  127. }
  128. } catch (e) {
  129. this.logger.error(`[lepaoAdminWarn] 告警邮件发送失败:${e.message || e}`)
  130. }
  131. }
  132. api(path) {
  133. return this.baseUrl + path
  134. }
  135. traceId() {
  136. return Date.now() + '_' + Math.random().toString(36).slice(2, 8)
  137. }
  138. sleep(ms) {
  139. return new Promise(r => setTimeout(r, ms))
  140. }
  141. async putOssWithFallback(sts, ossPath, content, ctx = {}) {
  142. // OSS 为阿里云签名 PUT,需原样发送二进制与 Authorization;不经 RunForge JSON 转发。
  143. await putOssWithQgOutbound(sts, ossPath, content, {
  144. logger: this.logger,
  145. traceId: ctx.traceId,
  146. taskId: ctx.taskId,
  147. outboundMode: 'direct',
  148. timeout: this.httpTimeoutMs * 2
  149. })
  150. }
  151. isRunSuccess(bindResponse) {
  152. const payload = bindResponse?.data
  153. const info = String(bindResponse?.info || '')
  154. const idempotentExists =
  155. info.includes('跑步记录已存在') ||
  156. info.includes('记录已存在')
  157. // 幂等兜底:首包可能已成功落库,但响应在代理链路丢失,重发后会返回“记录已存在”。
  158. // 该场景应按成功处理,避免误判失败后返还次数。
  159. if (idempotentExists) {
  160. return {
  161. ok: true,
  162. reason: info || '跑步记录已存在',
  163. payload
  164. }
  165. }
  166. if (!bindResponse || bindResponse.status !== 1 || !payload) {
  167. return {
  168. ok: false,
  169. reason: bindResponse?.info || '系统繁忙,请联系客服或稍后再试'
  170. }
  171. }
  172. const failedReason = payload.record_failed_reason || ''
  173. if (failedReason === '' || failedReason === '自动确认有效') {
  174. return { ok: true, payload }
  175. }
  176. return {
  177. ok: false,
  178. reason: failedReason,
  179. payload
  180. }
  181. }
  182. maskClientReason(reason) {
  183. const s = String(reason || '')
  184. if (s.includes('非法请求')) {
  185. return '系统繁忙,请稍后再试'
  186. }
  187. return s
  188. }
  189. extractApiErrorMessage(name, result) {
  190. if (!result) {
  191. this.logger.error(`${name} 接口无响应数据: ${this.safeStringify(result)}`)
  192. return `系统繁忙,请联系客服或稍后再试`
  193. }
  194. const candidates = [
  195. result.info,
  196. result.msg,
  197. result.message,
  198. result?.data?.info,
  199. result?.data?.msg,
  200. result?.data?.message,
  201. result?.data?.record_failed_reason
  202. ]
  203. const reason = candidates.find(v => typeof v === 'string' && v.trim() !== '')
  204. if (reason) {
  205. return this.maskClientReason(reason)
  206. }
  207. if (result.code !== undefined || result.status !== undefined) {
  208. this.logger.error(`${name} 接口返回异常: ${this.safeStringify(result)}`)
  209. return `系统繁忙,请联系客服或稍后再试`
  210. }
  211. return `系统繁忙,请联系客服或稍后再试`
  212. }
  213. async markLoginExpired(account) {
  214. if (!account) return
  215. try {
  216. const sql = 'UPDATE lepao_account SET state = 0 WHERE student_num = ?'
  217. await db.query(sql, [account])
  218. this.logger.warn(`${account} 登录状态已失效,已自动更新为未登录`)
  219. } catch (error) {
  220. this.logger.error(`更新账号登录状态失败:${error.stack || error}`)
  221. }
  222. }
  223. async writeSuccessRedis(account) {
  224. if (!account) return
  225. try {
  226. const now = new Date()
  227. const tomorrow = new Date().setHours(24, 0, 0, 0)
  228. const exp = Math.floor((tomorrow - now) / 1000)
  229. await Redis.set(`lepaoSuccess:${account}`, account, { EX: exp })
  230. } catch (error) {
  231. this.logger.error(`写入乐跑成功缓存失败: ${error.stack || error}`)
  232. }
  233. }
  234. async addLepaoRecord(uuid, account, result, pathId, pointData, runMode = 'auto') {
  235. if (!uuid || !account || !result || !pathId) return
  236. try {
  237. const time = Date.now()
  238. const publicId = uuidv4()
  239. const safeRunMode = runMode === 'manual' ? 'manual' : 'auto'
  240. const sql = 'INSERT INTO lepao_record (public_id, uuid, time, lepao_account, result, path_id, point_data, state, run_mode) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'
  241. await db.query(sql, [publicId, uuid, time, account, result, pathId, JSON.stringify(pointData || []), 1, safeRunMode])
  242. } catch (error) {
  243. this.logger.error(`写入乐跑记录失败: ${error.stack || error}`)
  244. }
  245. }
  246. async syncRunCount(req, ctx) {
  247. try {
  248. const sid = req?.student_id || req?.account
  249. if (
  250. req?.uid == null ||
  251. req?.token == null ||
  252. String(req.token).trim() === '' ||
  253. req?.school_id == null ||
  254. !sid
  255. ) {
  256. return { ok: false, reason: '缺少同步乐跑次数所需凭证' }
  257. }
  258. const recordData = await this.handlers['lepao.getRecord'](req, ctx)
  259. const data = recordData?.data
  260. if (!data) {
  261. return { ok: false, reason: 'getRecord 无有效 data' }
  262. }
  263. const term_num = Number(data.term_num ?? 30)
  264. const total_num = Number(data.total_num ?? 0)
  265. const sql = 'UPDATE lepao_account SET term_num = ?, total_num = ? WHERE student_num = ?'
  266. const rows = await db.query(sql, [term_num, total_num, req.account])
  267. if (!rows || rows.affectedRows !== 1) {
  268. this.logger.warn(`${req.account}更新乐跑次数失败`)
  269. return { ok: false, reason: '数据库更新 lepao_account 失败', term_num, total_num }
  270. }
  271. this.logger.info(`${req.account}更新乐跑次数成功 term_num=${term_num}, total_num=${total_num}`)
  272. return { ok: true, term_num, total_num }
  273. } catch (error) {
  274. this.logger.warn(`${req?.account || 'unknown'}同步乐跑次数失败: ${error.message || error}`)
  275. return { ok: false, reason: error.message || String(error) }
  276. }
  277. }
  278. lepaoTimestamp() {
  279. return Number((Date.now() / 1000).toFixed(3))
  280. }
  281. async enqueueTask(_channel, type, data, options = {}) {
  282. const payload = {
  283. id: options.id || this.traceId(),
  284. type,
  285. data,
  286. retry: options.retry ?? 0
  287. }
  288. await this.publishJson(this.taskQueue, payload, {
  289. channelName: 'lepao_worker_publish_task',
  290. contentType: 'application/json'
  291. })
  292. return payload.id
  293. }
  294. async sleep(ms) {
  295. return new Promise(resolve => setTimeout(resolve, ms))
  296. }
  297. async preparePublishQueue(channel, queue) {
  298. if (queue === this.taskQueue) {
  299. await assertRunforgeTaskIngress(channel, this.logger)
  300. return
  301. }
  302. if (queue === this.resultQueue || queue === this.deadQueue) {
  303. await channel.assertQueue(queue, {
  304. durable: true,
  305. arguments: {
  306. 'x-max-length': this.maxQueueLength
  307. }
  308. })
  309. return
  310. }
  311. await channel.assertQueue(queue, { durable: true })
  312. }
  313. async publishJson(queue, data, options = {}) {
  314. const channelName = options.channelName || `lepao_publish_${queue}`
  315. const contentType = options.contentType || 'application/json'
  316. const body = Buffer.from(JSON.stringify(data))
  317. let lastErr
  318. for (let attempt = 1; attempt <= 2; attempt++) {
  319. try {
  320. const ch = await mq.getChannel(channelName)
  321. await this.preparePublishQueue(ch, queue)
  322. const ok = ch.sendToQueue(queue, body, {
  323. persistent: true,
  324. contentType
  325. })
  326. if (!ok) {
  327. const err = new Error(`MQ 背压,未能写入队列 ${queue}`)
  328. err.code = 'MQ_BACKPRESSURE'
  329. throw err
  330. }
  331. return
  332. } catch (e) {
  333. lastErr = e
  334. mq.invalidateChannel(channelName)
  335. if (attempt < 2) {
  336. this.logger.warn(`MQ 发布失败,准备重试 queue=${queue}: ${e.message || e}`)
  337. await this.sleep(500)
  338. }
  339. }
  340. }
  341. throw lastErr
  342. }
  343. safeAck(channel, msg, traceId) {
  344. try {
  345. if (!channel?.__runforgeClosed) channel.ack(msg)
  346. } catch (e) {
  347. this.logger.warn(`[${traceId || 'unknown'}] MQ ack 失败,可能连接已断开: ${e.message || e}`)
  348. }
  349. }
  350. safeNack(channel, msg, traceId, requeue = true) {
  351. try {
  352. if (!channel?.__runforgeClosed) channel.nack(msg, false, requeue)
  353. } catch (e) {
  354. this.logger.warn(`[${traceId || 'unknown'}] MQ nack 失败,可能连接已断开: ${e.message || e}`)
  355. }
  356. }
  357. scheduleRestart(reason) {
  358. if (this.stopping || this.restartTimer) return
  359. this.running = false
  360. this.logger.warn(`RunForge Worker 消费通道已不可用,准备重启消费器: ${reason || 'unknown'}`)
  361. mq.invalidateChannel(this.channelName)
  362. this.restartTimer = setTimeout(() => {
  363. this.restartTimer = null
  364. this.start().catch(err => {
  365. this.logger.error(`RunForge Worker 重启失败: ${err.stack || err}`)
  366. this.scheduleRestart('restart_failed')
  367. })
  368. }, 5000)
  369. }
  370. async withTimeout(promise, name, timeoutMs, options = {}) {
  371. const ms = Number.isFinite(Number(timeoutMs)) ? Number(timeoutMs) : this.taskTimeoutMs
  372. const { code = 'TIMEOUT', retryable = false } = options || {}
  373. return Promise.race([
  374. promise,
  375. new Promise((_, reject) =>
  376. setTimeout(() => {
  377. const err = new Error(`${name} 超时`)
  378. err.code = code
  379. err.retryable = !!retryable
  380. reject(err)
  381. }, ms)
  382. )
  383. ])
  384. }
  385. async retry(fn, name) {
  386. let lastErr
  387. for (let i = 0; i < this.maxRetry; i++) {
  388. try {
  389. return await fn()
  390. } catch (err) {
  391. lastErr = err
  392. if (!this.isRetryableTaskError(err)) {
  393. throw err
  394. }
  395. this.logger.warn(`[RETRY] ${name} 第${i + 1}次失败`)
  396. await this.sleep(1000 * (i + 1)) // 指数退避
  397. }
  398. }
  399. throw lastErr
  400. }
  401. isNetworkError(err) {
  402. if (!err) return false
  403. if (err.code && ['ECONNRESET', 'ECONNABORTED', 'ETIMEDOUT', 'ENOTFOUND', 'EAI_AGAIN'].includes(err.code)) {
  404. return true
  405. }
  406. if (err.isAxiosError && !err.response) return true
  407. const msg = (err.message || '').toLowerCase()
  408. return msg.includes('timeout') || msg.includes('network')
  409. }
  410. isRetryableTaskError(err) {
  411. if (!err) return false
  412. if (err.retryable === true) return true
  413. if (this.isNetworkError(err)) return true
  414. return ['PATH_SELECT_FAILED', 'CHECKPOINT_FETCH_FAILED', 'CHECKPOINT_INSUFFICIENT'].includes(err.code)
  415. }
  416. safeStringify(obj) {
  417. const seen = new WeakSet();
  418. return JSON.stringify(obj, (key, value) => {
  419. if (typeof value === 'object' && value !== null) {
  420. if (seen.has(value)) return '[Circular]';
  421. seen.add(value);
  422. }
  423. return value;
  424. })
  425. }
  426. log(traceId, type, msg, data) {
  427. this.logger.info(`[${traceId}] [${type}] ${msg} ${data ? this.safeStringify(data) : ''}`)
  428. }
  429. logErr(traceId, msg, err) {
  430. this.logger.error(`[${traceId}] ${msg} ${err.stack || err}`)
  431. }
  432. /**
  433. * 学校接口请求:内层 retry 每次重新生成 raw 并签名,避免重试复用同一 timestamp/nonce/sign 触发「非法请求2」。
  434. * @param {() => object | object} getRaw 返回请求明文对象的函数,或为兼容旧代码传入 plain object
  435. */
  436. async request(traceId, name, url, getRaw, headers = {}, ctx = null) {
  437. return this.retry(async () => {
  438. const raw = typeof getRaw === 'function' ? getRaw() : getRaw
  439. this.log(traceId, 'REQ', name, raw)
  440. const mergedHeaders = {
  441. 'Content-Type': 'application/x-www-form-urlencoded',
  442. 'Accept': '*/*',
  443. 'Accept-Language': 'zh-CN,zh-Hans;q=0.9',
  444. 'Accept-Encoding': 'gzip, deflate, br',
  445. 'Referer': 'https://servicewechat.com/wxf94c4ddb63d87ede/32/page-frame.html',
  446. ...headers
  447. }
  448. if (!mergedHeaders['User-Agent']) {
  449. mergedHeaders['User-Agent'] = this.defaultUserAgent
  450. }
  451. const form = new URLSearchParams()
  452. form.append('ostype', '5')
  453. form.append('data', dataEncrypt(JSON.stringify(raw)))
  454. const res = await this.withTimeout(
  455. postLepaoSchool(url, form, {
  456. headers: mergedHeaders,
  457. timeout: this.httpTimeoutMs,
  458. logger: this.logger,
  459. outboundMode: ctx?.outboundMode || 'auto',
  460. mqTaskId: ctx?.taskId,
  461. traceId
  462. }),
  463. name,
  464. this.httpTimeoutMs,
  465. { code: 'HTTP_TIMEOUT', retryable: true }
  466. )
  467. let result = res.data
  468. if (result?.data && result?.is_encrypt === 1) {
  469. result.data = JSON.parse(dataDecrypt(result.data))
  470. }
  471. this.log(traceId, 'RES', name, result)
  472. // 除 bindData 外,其余调用若接口已明确返回失败,直接抛出该失败原因
  473. // bindData 需要保留完整响应由 isRunSuccess 统一判定。
  474. if (name !== 'bindData') {
  475. const hasCode = result && Object.prototype.hasOwnProperty.call(result, 'code')
  476. const hasStatus = result && Object.prototype.hasOwnProperty.call(result, 'status')
  477. const failedByCode = hasCode && Number(result.code) !== 1 && Number(result.code) !== 200
  478. const failedByStatus = hasStatus && Number(result.status) !== 1
  479. if (failedByCode || failedByStatus) {
  480. const message = this.extractApiErrorMessage(name, result)
  481. const err = new Error(message)
  482. if (message.includes('重新登录')) {
  483. await this.markLoginExpired(raw?.student_num)
  484. }
  485. // 接口已返回业务错误,禁止重试
  486. err.retryable = false
  487. throw err
  488. }
  489. }
  490. return result
  491. }, name)
  492. }
  493. /**
  494. * 累计完成次数 >= 跑友目标(且目标>0)时:关闭 auto_run,并发送乐跑目标完成邮件 / Bot 通知
  495. */
  496. async handleLepaoTargetComplete(account, user, totalNum, traceId) {
  497. const target = Number(user?.target_count) || 0
  498. const total = Number(totalNum) || 0
  499. if (target <= 0 || total < target) return
  500. try {
  501. const up = await db.query(
  502. 'UPDATE lepao_account SET auto_run = 0 WHERE student_num = ? AND auto_run = 1',
  503. [account]
  504. )
  505. if (up?.affectedRows !== 1) {
  506. return
  507. }
  508. this.logger.info(
  509. `${account} 已达目标次数(${total}/${target}),关闭自动乐跑`
  510. )
  511. } catch (e) {
  512. this.logger.error(`关闭自动乐跑失败 ${account}: ${e.message || e}`)
  513. return
  514. }
  515. const noticeType = user.notice_type || 'none'
  516. const overPayload = {
  517. type: 'lepao_over',
  518. umo: user.bot_umo,
  519. name: user.name,
  520. account,
  521. total_num: total,
  522. target_count: target,
  523. traceId
  524. }
  525. if (noticeType === 'email' && user.email) {
  526. try {
  527. await EmailTemplate.lepaoOver(user.email, {
  528. name: user.name,
  529. account
  530. })
  531. } catch (e) {
  532. this.logger.error(`lepaoOver 邮件发送失败: ${e.message || e}`)
  533. }
  534. }
  535. if (noticeType === 'bot' && user.bot_umo) {
  536. try {
  537. await this.publishJson(this.noticeQueue, overPayload, {
  538. channelName: 'lepao_worker_publish_notice'
  539. })
  540. } catch (e) {
  541. this.logger.error(`lepao_over Bot 通知失败: ${e.message || e}`)
  542. }
  543. }
  544. if (noticeType === 'wechat' && user.create_user) {
  545. try {
  546. await WeixinBindingService.sendTextToUser(
  547. user.create_user,
  548. LepaoWechatTemplate.buildTargetComplete({
  549. name: user.name,
  550. account,
  551. total_num: total,
  552. target_count: target,
  553. traceId
  554. })
  555. )
  556. } catch (e) {
  557. this.logger.error(`lepao_over WeChat notice failed: ${e.message || e}`)
  558. }
  559. }
  560. }
  561. buildWechatNoticeText({ success, account, payload, reason }) {
  562. if (success) {
  563. return LepaoWechatTemplate.buildRunSuccess({
  564. ...(payload || {}),
  565. account
  566. })
  567. }
  568. return LepaoWechatTemplate.buildRunFail({
  569. ...(payload || {}),
  570. account,
  571. reason
  572. })
  573. }
  574. register(type, handler) {
  575. this.handlers[type] = handler
  576. this.logger.info(`注册任务: ${type}`)
  577. }
  578. /* ================= 业务 ================= */
  579. initHandlers() {
  580. this.register('lepao.syncAccountInfo', async (req) => {
  581. const studentNum = req?.student_num
  582. if (!studentNum) {
  583. throw new Error('同步乐跑账号失败:缺少 student_num')
  584. }
  585. const syncResult = await syncAccountInfo({
  586. studentNum,
  587. logger: this.logger
  588. })
  589. if (!syncResult.ok) {
  590. const err = new Error(syncResult.msg || '同步乐跑账号失败')
  591. err.retryable = false
  592. throw err
  593. }
  594. return syncResult.data
  595. })
  596. /* ---------------- 开始乐跑 ---------------- */
  597. this.register('lepao.startRun', async (req, ctx) => {
  598. const traceId = ctx.traceId
  599. const maxPathRetry = 20 // 自动获取路径失败最大重试次数
  600. let pathRetry = 0
  601. let pointData = null
  602. let pathData = null
  603. let newPathData = null
  604. let ossPath = null
  605. let ossSts = null
  606. let userData = null
  607. let pathId = null
  608. let runZoneId = 0
  609. let bindRes = null
  610. try {
  611. // 检查redis是否存在当天乐跑成功记录
  612. const isSuccess = await Redis.get(`lepaoSuccess:${req.account}`)
  613. if (isSuccess)
  614. throw new Error('该账号当天已乐跑成功!请勿重复乐跑')
  615. userData = await this.handlers['lepao.getUserData'](req, ctx)
  616. // 立刻合并账号凭证,保证后续任意 throw 时 finally 里 syncRunCount 不会用空 token 调 getRecord
  617. req = {
  618. ...req,
  619. ...userData,
  620. student_id: req.account
  621. }
  622. // 进入乐跑进程后写入进行中缓存
  623. const progressKey = `lepaoProgress:${req.account}`
  624. const inProgress = await Redis.get(progressKey)
  625. if (inProgress) {
  626. throw new Error('该账号已进入乐跑任务队列,请等待乐跑完成后再进行乐跑操作')
  627. }
  628. await Redis.set(progressKey, req.account, { EX: 1800 })
  629. ossSts = await this.handlers['lepao.getOssSts'](req, ctx)
  630. if (!ossSts?.bucket || !ossSts?.AccessKeyId || !ossSts?.AccessKeySecret || !ossSts?.SecurityToken) {
  631. throw new Error('获取 OSS 凭证失败,请联系客服或稍后再试')
  632. }
  633. req = {
  634. ...req,
  635. ossSts
  636. }
  637. // 晚上10点后提前
  638. let run_end_time = Math.floor(Date.now() / 1000) - 300 // 提前5分钟
  639. let hour = new Date().getHours()
  640. if (hour < 7)
  641. throw new Error('当前不在有效乐跑时间范围内。RunForge支持乐跑时间段为7:00~24:00')
  642. if (hour >= 22) {
  643. const minSec = 2 * 60 * 60
  644. const maxSec = 12 * 60 * 60
  645. const advanceSec = Math.floor(Math.random() * (maxSec - minSec + 1)) + minSec
  646. this.logger.info(`${req.account}当前时间为${hour}点,调整run_end_time提前${advanceSec}秒(约${(advanceSec / 3600).toFixed(2)}小时)`)
  647. run_end_time -= advanceSec
  648. }
  649. req = {
  650. ...req,
  651. run_end_time
  652. }
  653. // 1.5️⃣ 乐跑开始前扣减次数(同一 MQ taskId 仅扣一次;仅当所有重试均失败后在 catch 中返还)
  654. await this.handlers['lepao.consumeCount']({
  655. account: req.account,
  656. uuid: userData?.create_user
  657. }, ctx)
  658. while (pathRetry < maxPathRetry) {
  659. try {
  660. // 2️⃣ 获取路径(仅路径选择失败时重试)
  661. const pathRes = await this.handlers['lepao.getPath'](req, ctx)
  662. pathData = pathRes.pathData
  663. pathId = pathData?.id || null
  664. newPathData = getPathData(pathData.data, req.run_end_time, pathData.time)
  665. // 3️⃣ 切换跑区
  666. const zoneRes = await this.handlers['lepao.setZone']({ ...req, pathData }, ctx)
  667. runZoneId = zoneRes?.run_zone_id || 0
  668. // 4️⃣ 上传 OSS 文件、生成打卡点
  669. const uploadRes = await this.handlers['lepao.uploadOssFile']({ ...req, pathData, newPathData }, ctx)
  670. ossPath = uploadRes.oss_path
  671. pointData = uploadRes.point_data
  672. if (!pointData) {
  673. pathRetry++
  674. this.logger.warn(`[${traceId}] 打卡点不满足要求,重新获取路径 第${pathRetry}次`)
  675. continue
  676. }
  677. // 打卡点符合要求,跳出循环
  678. break
  679. } catch (err) {
  680. if (!this.isRetryableTaskError(err)) {
  681. throw err
  682. }
  683. this.logger.warn(`[${traceId}] 可重试错误,重新获取路径 第${pathRetry + 1}次,原因:${err.message}`)
  684. pathRetry++
  685. await this.sleep(1000 * pathRetry)
  686. }
  687. }
  688. if (!pointData) {
  689. throw new Error('打卡点获取失败,乐跑任务终止')
  690. }
  691. // 5️⃣ 提交跑步数据
  692. bindRes = await this.handlers['lepao.bindData']({
  693. ...req,
  694. pathData,
  695. run_zone_id: runZoneId,
  696. record_file: ossPath,
  697. point_data: pointData
  698. }, ctx)
  699. // 绑定接口有返回即入库
  700. if (bindRes && bindRes.data) {
  701. await this.addLepaoRecord(userData?.create_user, req.account, bindRes.data, pathId, pointData, req.runMode)
  702. }
  703. const runResult = this.isRunSuccess(bindRes)
  704. if (runResult.ok || runResult.reason === '当天关联成绩次数已达到上限') {
  705. await this.writeSuccessRedis(req.account)
  706. }
  707. if (!runResult.ok) {
  708. throw new Error(this.maskClientReason(runResult.reason))
  709. }
  710. if (bindRes && bindRes.data && bindRes.data.record_id) {
  711. const gyrRes = await this.handlers['lepao.uploadGyrOssFile']({ ...req, newPathData, record_id: bindRes.data.record_id }, ctx)
  712. if (gyrRes?.status === 1) {
  713. this.logger.info(`${req.account}上传加速度数据成功!`)
  714. } else {
  715. this.logger.error(`${req.account}上传加速度数据失败!原因:${gyrRes.info || '未知错误'}`)
  716. }
  717. }
  718. // 同步乐跑次数(通知里要带 total_num / term_num,与 getRecord 一致)
  719. const syncResult = await this.syncRunCount(req, ctx)
  720. if (!syncResult?.ok) {
  721. this.logger.error(
  722. `[${traceId}] 同步乐跑次数失败:${syncResult?.reason || 'unknown'}`
  723. )
  724. }
  725. // 6️⃣ 发送通知(把同步后的学期次数、累计完成次数传给 Bot / 邮件)
  726. if (ctx.channel) {
  727. await this.enqueueTask(
  728. ctx.channel,
  729. 'lepao.sendNotice',
  730. {
  731. account: req.account,
  732. success: true,
  733. data: runResult.payload,
  734. traceId,
  735. total_num: syncResult?.ok ? syncResult.total_num : undefined
  736. },
  737. { id: `${traceId}:notice:success` }
  738. )
  739. }
  740. return { traceId, ossPath, pointData, bindRes }
  741. } catch (err) {
  742. this.logger.error(`[${traceId}] 乐跑流程失败:`, err)
  743. const retryNow = Number(ctx?.retry || 0)
  744. const maxRetry = Number(ctx?.maxRetry ?? this.maxRetry)
  745. const canRetry = this.isRetryableTaskError(err) && retryNow < maxRetry
  746. const isFinalAttemptFail = !canRetry
  747. // 仅在所有重试均失败后才发异常告警/失败通知,避免每次重试都打扰
  748. if (isFinalAttemptFail) {
  749. Promise.resolve().then(async () => {
  750. try {
  751. await this.notifyAdminsUncommonLepaoError({
  752. account: req?.account,
  753. name: userData?.name,
  754. traceId,
  755. taskType: 'lepao.startRun',
  756. reason: err?.message || '未知错误',
  757. code: err?.code
  758. })
  759. } catch (_) { }
  760. })
  761. }
  762. // 仅终局失败(不可再 MQ 重试)时返还;中间重试保持已扣次数,避免重复扣/退抖动
  763. if (isFinalAttemptFail) {
  764. try {
  765. await this.handlers['lepao.refundCount']({
  766. account: req.account,
  767. uuid: userData?.create_user
  768. }, ctx)
  769. } catch (e) {
  770. this.logger.error(`[${traceId}] 返还乐跑次数失败:${e.stack || e}`)
  771. }
  772. }
  773. if (ctx.channel && isFinalAttemptFail) {
  774. await this.enqueueTask(ctx.channel, 'lepao.sendNotice', {
  775. account: req.account,
  776. success: false,
  777. reason:
  778. err?.code === 'TASK_TIMEOUT'
  779. ? '系统繁忙,请稍后再试'
  780. : this.maskClientReason(err.message || '未知错误'),
  781. traceId
  782. }, { id: `${traceId}:notice:fail` })
  783. }
  784. throw err
  785. } finally {
  786. await Redis.del(`lepaoProgress:${req.account}`)
  787. }
  788. })
  789. /* ---------------- 发送通知(独立 MQ 任务) ---------------- */
  790. this.register('lepao.sendNotice', async (req, ctx) => {
  791. const { account, success, data, reason, traceId, total_num: totalNumArg } = req || {}
  792. if (!account) {
  793. throw new Error('发送通知失败:缺少 account')
  794. }
  795. const emailSql = `
  796. SELECT
  797. a.name,
  798. a.email,
  799. a.target_count,
  800. a.notice_type,
  801. a.create_user,
  802. e.bot_umo,
  803. a.update_type
  804. FROM
  805. lepao_account a
  806. LEFT JOIN
  807. lepao_extra e
  808. ON
  809. a.student_num = e.student_num
  810. WHERE
  811. a.student_num = ?
  812. `
  813. const rows = await db.query(emailSql, [account])
  814. if (!rows || rows.length === 0) {
  815. throw new Error('发送通知失败:未找到用户通知配置')
  816. }
  817. const user = rows[0]
  818. const noticeType = user.notice_type || 'none'
  819. let totalForNotice = totalNumArg
  820. if (
  821. success &&
  822. (totalForNotice === undefined || totalForNotice === null)
  823. ) {
  824. const accRows = await db.query(
  825. 'SELECT total_num FROM lepao_account WHERE student_num = ?',
  826. [account]
  827. )
  828. if (accRows && accRows[0]) {
  829. totalForNotice = accRows[0].total_num
  830. }
  831. }
  832. if (totalForNotice === undefined || totalForNotice === null) {
  833. totalForNotice = 0
  834. }
  835. totalForNotice = Number(totalForNotice)
  836. const targetCount = Number(user.target_count) || 0
  837. const payload = success ? {
  838. ...(data && typeof data === 'object' ? data : {}),
  839. type: 'lepao_success',
  840. umo: user.bot_umo,
  841. total_num: totalForNotice,
  842. target_count: targetCount,
  843. name: user.name,
  844. update_type: user.update_type,
  845. account,
  846. traceId
  847. } : {
  848. type: 'lepao_fail',
  849. umo: user.bot_umo,
  850. name: user.name,
  851. update_type: user.update_type,
  852. account,
  853. reason,
  854. traceId
  855. }
  856. const afterSuccessNotify = async () => {
  857. if (success) {
  858. await this.handleLepaoTargetComplete(account, user, totalForNotice, traceId)
  859. }
  860. }
  861. if (noticeType === 'bot' && user.bot_umo) {
  862. await this.publishJson(this.noticeQueue, payload, {
  863. channelName: 'lepao_worker_publish_notice'
  864. })
  865. await afterSuccessNotify()
  866. return { delivered: true, via: 'bot' }
  867. }
  868. if (noticeType === 'wechat' && user.create_user) {
  869. try {
  870. await WeixinBindingService.sendTextToUser(user.create_user, this.buildWechatNoticeText({ success, account, payload, reason }))
  871. await afterSuccessNotify()
  872. return { delivered: true, via: 'wechat' }
  873. } catch (e) {
  874. this.logger.error(`lepao WeChat notice failed: ${e.message || e}`)
  875. await afterSuccessNotify()
  876. return { delivered: false, via: 'wechat' }
  877. }
  878. }
  879. if (noticeType === 'email' && user.email) {
  880. if (success) {
  881. await EmailTemplate.lepaoSuccess(user.email, payload)
  882. await afterSuccessNotify()
  883. return { delivered: true, via: 'email' }
  884. }
  885. await EmailTemplate.lepaoFail(user.email, {
  886. name: user.name,
  887. account,
  888. reason: reason || '系统繁忙,请联系客服或稍后再试',
  889. traceId
  890. })
  891. return { delivered: true, via: 'email' }
  892. }
  893. await afterSuccessNotify()
  894. return { delivered: false, via: 'none' }
  895. })
  896. /* ---------------- 扣减次数 ---------------- */
  897. this.register('lepao.consumeCount', async (req, ctx) => {
  898. const account = req?.account
  899. const uuid = req?.uuid
  900. if (!uuid) {
  901. throw new Error('扣减乐跑次数失败:缺少 uuid')
  902. }
  903. // 幂等:同一 MQ taskId 全程(含多次重试投递)只扣一次;终局失败再一次性返还
  904. const consumeKey = `lepao:consume:${ctx?.taskId || ctx?.traceId || account || uuid}`
  905. const existed = await Redis.get(consumeKey)
  906. if (existed) {
  907. return true
  908. }
  909. this.logger.info(`${account || uuid}开始扣减乐跑次数`)
  910. const conn = await db.connect()
  911. try {
  912. await conn.beginTransaction()
  913. const [userRows] = await conn.execute(
  914. 'SELECT lepao_count FROM users WHERE uuid = ? FOR UPDATE',
  915. [uuid]
  916. )
  917. if (!userRows || userRows.length !== 1) {
  918. await conn.rollback()
  919. throw new Error('扣减乐跑次数失败:用户不存在')
  920. }
  921. const beforeCount = Number(userRows[0].lepao_count || 0)
  922. if (beforeCount < 1) {
  923. await conn.rollback()
  924. throw new Error('用户乐跑次数不足,请购买乐跑次数后重试!')
  925. }
  926. const [r] = await conn.execute(
  927. 'UPDATE users SET lepao_count = lepao_count - 1 WHERE uuid = ?',
  928. [uuid]
  929. )
  930. if (!r || r.affectedRows !== 1) {
  931. await conn.rollback()
  932. throw new Error('扣减乐跑次数失败:数据库更新失败')
  933. }
  934. await insertLedgerRecord({
  935. executor: conn,
  936. userUuid: uuid,
  937. delta: -1,
  938. balanceBefore: beforeCount,
  939. balanceAfter: beforeCount - 1,
  940. bizType: 'run_consume',
  941. bizId: consumeKey,
  942. remark: `${account || uuid}乐跑扣除`
  943. })
  944. await conn.commit()
  945. } catch (error) {
  946. try { await conn.rollback() } catch (_) { }
  947. throw error
  948. } finally {
  949. if (conn?.connection && typeof conn.connection.release === 'function' && typeof conn?.release === 'function') {
  950. conn.release()
  951. }
  952. }
  953. this.logger.info(`${account || uuid}扣减乐跑次数完成`)
  954. await Redis.set(consumeKey, '1', { EX: 3600 })
  955. return true
  956. })
  957. /* ---------------- 返还次数(整次任务所有 MQ 重试耗尽后失败时执行) ---------------- */
  958. this.register('lepao.refundCount', async (req, ctx) => {
  959. const account = req?.account
  960. const uuid = req?.uuid
  961. if (!uuid) {
  962. return true
  963. }
  964. const baseKey = `${ctx?.taskId || ctx?.traceId || account || uuid}`
  965. const consumeKey = `lepao:consume:${baseKey}`
  966. const refundKey = `lepao:refund:${baseKey}`
  967. const consumed = await Redis.get(consumeKey)
  968. if (!consumed) {
  969. return true
  970. }
  971. const refunded = await Redis.get(refundKey)
  972. if (refunded) {
  973. return true
  974. }
  975. this.logger.info(`${account || uuid}开始返还乐跑次数`)
  976. const conn = await db.connect()
  977. try {
  978. await conn.beginTransaction()
  979. const [userRows] = await conn.execute(
  980. 'SELECT lepao_count FROM users WHERE uuid = ? FOR UPDATE',
  981. [uuid]
  982. )
  983. if (!userRows || userRows.length !== 1) {
  984. await conn.rollback()
  985. throw new Error('返还乐跑次数失败:用户不存在')
  986. }
  987. const beforeCount = Number(userRows[0].lepao_count || 0)
  988. const [r] = await conn.execute(
  989. 'UPDATE users SET lepao_count = lepao_count + 1 WHERE uuid = ?',
  990. [uuid]
  991. )
  992. if (!r || r.affectedRows !== 1) {
  993. await conn.rollback()
  994. throw new Error('返还乐跑次数失败:数据库更新失败')
  995. }
  996. await insertLedgerRecord({
  997. executor: conn,
  998. userUuid: uuid,
  999. delta: 1,
  1000. balanceBefore: beforeCount,
  1001. balanceAfter: beforeCount + 1,
  1002. bizType: 'run_refund',
  1003. bizId: refundKey,
  1004. remark: `${account || uuid}乐跑失败返还`
  1005. })
  1006. await conn.commit()
  1007. } catch (error) {
  1008. try { await conn.rollback() } catch (_) { }
  1009. throw error
  1010. } finally {
  1011. if (conn?.connection && typeof conn.connection.release === 'function' && typeof conn?.release === 'function') {
  1012. conn.release()
  1013. }
  1014. }
  1015. this.logger.info(`${account || uuid}返还乐跑次数完成`)
  1016. await Redis.set(refundKey, '1', { EX: 3600 })
  1017. return true
  1018. })
  1019. this.register('lepao.getUserData', async (req, ctx) => {
  1020. const account = req.account
  1021. this.logger.info(`${account}开始获取用户数据`)
  1022. const accountSql = `
  1023. SELECT
  1024. u.uuid,
  1025. u.lepao_count,
  1026. l.create_user,
  1027. l.name,
  1028. l.student_num,
  1029. l.area,
  1030. l.sex,
  1031. l.state,
  1032. l.token,
  1033. l.uid,
  1034. l.school_id,
  1035. l.userAgent,
  1036. l.deviceModel,
  1037. l.notice_type,
  1038. l.email,
  1039. e.bot_account
  1040. FROM
  1041. lepao_account l
  1042. LEFT JOIN
  1043. users u
  1044. ON
  1045. l.create_user = u.uuid
  1046. LEFT JOIN
  1047. lepao_extra e
  1048. ON
  1049. l.student_num = e.student_num
  1050. WHERE
  1051. l.student_num = ?
  1052. `
  1053. const rows = await db.query(accountSql, [account])
  1054. if (!rows || rows.length === 0) {
  1055. this.logger.error(`${account}无法获取账号数据`)
  1056. throw new Error('无法获取账号数据,请联系客服或稍后再试')
  1057. }
  1058. let userData = rows[0]
  1059. if (!userData.create_user || !userData.uuid) {
  1060. this.logger.warn(`${account}账号状态异常`)
  1061. throw new Error('当前账号状态异常,请联系客服')
  1062. }
  1063. if (userData.state !== 1) {
  1064. this.logger.warn(`${account}登录状态异常 state=${userData.state}`)
  1065. throw new Error('乐跑账号登录已过期,请尝试使用登录器重新登录')
  1066. }
  1067. if (userData.lepao_count < 1) {
  1068. this.logger.warn(`${account}乐跑次数不足`)
  1069. throw new Error('用户乐跑次数不足,请购买乐跑次数后重试!')
  1070. }
  1071. if (!userData.userAgent)
  1072. 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'
  1073. if (!userData.deviceModel)
  1074. userData.deviceModel = '2211133C'
  1075. return userData
  1076. })
  1077. this.register('lepao.getPath', async (req, ctx) => {
  1078. const account = req.account
  1079. this.logger.info(`${account}开始获取路径`)
  1080. const accountSql = 'SELECT area, sex FROM lepao_account WHERE student_num = ?'
  1081. const rows = await db.query(accountSql, [account])
  1082. if (!rows || rows.length === 0) {
  1083. this.logger.error(`${account}无法获取账号数据`)
  1084. throw new Error('无法获取账号数据')
  1085. }
  1086. const { area, sex } = rows[0]
  1087. let max = 4.00
  1088. let min = 2.00
  1089. if (sex === 2) {
  1090. max = 2.00
  1091. min = 1.60
  1092. }
  1093. this.logger.info(`${account}路径参数: area=${area ?? '随机'}, max_distance=${max}, min_distance=${min}`)
  1094. let pathSql = 'SELECT * FROM path_data WHERE state = 1 AND distance < ? AND distance > ? '
  1095. const pathParams = [max, min]
  1096. if (area) {
  1097. pathSql += ' AND run_zone_name = ?'
  1098. pathParams.push(area)
  1099. }
  1100. pathSql += ' ORDER BY count ASC LIMIT 1'
  1101. const paths = await db.query(pathSql, pathParams)
  1102. if (!paths || paths.length === 0) {
  1103. this.logger.error(`${account}未找到符合条件的路线`)
  1104. const err = new Error('未找到符合条件的路线,请改变路径选择条件')
  1105. err.code = 'PATH_SELECT_FAILED'
  1106. err.retryable = true
  1107. throw err
  1108. }
  1109. const randomPath = paths[0]
  1110. const updateSql = 'UPDATE path_data SET count = count + 1 WHERE id = ?'
  1111. await db.query(updateSql, [randomPath.id])
  1112. this.logger.info(`${account}路径选中id=${randomPath.id},计数加1成功`)
  1113. return { pathData: randomPath }
  1114. })
  1115. /* ---------------- 获取跑步记录 ---------------- */
  1116. this.register('lepao.getRecord', async (req, ctx) => {
  1117. return this.request(
  1118. ctx.traceId,
  1119. 'getRecord',
  1120. this.api('/Run2/beforeRunV260'),
  1121. () => {
  1122. const now = this.lepaoTimestamp()
  1123. const raw = {
  1124. uid: req.uid,
  1125. token: req.token,
  1126. school_id: req.school_id,
  1127. term_id: 0,
  1128. course_id: 0,
  1129. class_id: 0,
  1130. student_num: req.student_id,
  1131. card_id: req.student_id,
  1132. timestamp: now,
  1133. version: 1,
  1134. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1135. ostype: 5
  1136. }
  1137. raw.sign = dataSign(raw)
  1138. return raw
  1139. },
  1140. {
  1141. 'User-Agent': req.userAgent,
  1142. 'charset': 'utf-8',
  1143. 'Referer': 'https://servicewechat.com/wxf94c4ddb63d87ede/32/page-frame.html',
  1144. },
  1145. ctx
  1146. )
  1147. })
  1148. /* ---------------- 切换跑区 ---------------- */
  1149. this.register('lepao.setZone', async (req, ctx) => {
  1150. const runZoneMap = {
  1151. '兰花湖校区跑区': 2,
  1152. '主校区北跑区': 3,
  1153. '主校区南跑区': 5,
  1154. '重庆工商大学茶园校区': 6
  1155. }
  1156. const { pathData } = req
  1157. const runZoneId = runZoneMap[pathData.run_zone_name]
  1158. if (!runZoneId) throw new Error('跑区不存在')
  1159. await this.request(
  1160. ctx.traceId,
  1161. 'setZone',
  1162. this.api('/Run/setRunZone'),
  1163. () => {
  1164. const raw = {
  1165. uid: req.uid,
  1166. token: req.token,
  1167. school_id: req.school_id,
  1168. term_id: 0,
  1169. course_id: 0,
  1170. class_id: 0,
  1171. student_num: req.student_id,
  1172. card_id: req.student_id,
  1173. timestamp: this.lepaoTimestamp(),
  1174. version: 1,
  1175. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1176. ostype: 5,
  1177. run_zone_id: String(runZoneId)
  1178. }
  1179. raw.sign = dataSign(raw)
  1180. return raw
  1181. },
  1182. {},
  1183. ctx
  1184. )
  1185. return { run_zone_id: runZoneId }
  1186. })
  1187. /* ---------------- 获取 OSS STS ---------------- */
  1188. this.register('lepao.getOssSts', async (req, ctx) => {
  1189. const res = await this.request(
  1190. ctx.traceId,
  1191. 'getOssSts',
  1192. this.api('/WpIndex/getOssSts'),
  1193. () => {
  1194. const raw = {
  1195. uid: req.uid,
  1196. token: req.token,
  1197. school_id: req.school_id,
  1198. term_id: 0,
  1199. course_id: 0,
  1200. class_id: 0,
  1201. student_num: req.student_id,
  1202. card_id: req.student_id,
  1203. timestamp: this.lepaoTimestamp(),
  1204. version: 1,
  1205. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1206. ostype: 5
  1207. }
  1208. raw.sign = dataSign(raw)
  1209. return raw
  1210. },
  1211. {},
  1212. ctx
  1213. )
  1214. return res.data
  1215. })
  1216. /* ---------------- 上传 OSS 文件 ---------------- */
  1217. this.register('lepao.uploadOssFile', async (req, ctx) => {
  1218. const { account, pathData, newPathData, ossSts: sts } = req
  1219. // 处理跑步路径
  1220. const pathResult = dataEncrypt(JSON.stringify(newPathData))
  1221. // 获取跑步规则参数
  1222. const runRule = await this.handlers['lepao.getRecord'](req, ctx)
  1223. const ruleData = runRule?.data
  1224. if (!ruleData?.run_line_info?.point_list || !ruleData?.time_rule_arr?.length) {
  1225. const err = new Error('获取打卡点规则失败')
  1226. err.code = 'CHECKPOINT_FETCH_FAILED'
  1227. err.retryable = true
  1228. throw err
  1229. }
  1230. const check_points = ruleData.run_line_info.point_list
  1231. let min_log_num = ruleData.time_rule_arr[0]?.min_log_num || 4
  1232. const point_update_distance = parseFloat(ruleData.run_line_info.point_update_distance || 0) * 1000
  1233. const log_max_distance = Number(ruleData.run_line_info.log_max_distance || 0)
  1234. // 生成打卡点
  1235. const point_data = selectCheckpoints(newPathData, check_points, min_log_num, point_update_distance, log_max_distance, req.run_end_time, pathData.time)
  1236. if (!point_data) {
  1237. this.logger.warn(`[RETRY] 打卡点数量不足,重新更换路径`)
  1238. const err = new Error('打卡点数量不足')
  1239. err.code = 'CHECKPOINT_INSUFFICIENT'
  1240. err.retryable = true
  1241. throw err
  1242. }
  1243. const now = new Date()
  1244. let day = now.getDay()
  1245. if (day === 0) day = 7
  1246. // 判断当天是否有成功记录
  1247. if(!ruleData?.weekData?.list || ruleData?.weekData?.list?.length !== 7) {
  1248. const err = new Error('获取当天跑步记录失败,请联系客服或稍后再试')
  1249. err.code = 'DAILY_RECORD_FETCH_FAILED'
  1250. err.retryable = false
  1251. throw err
  1252. }
  1253. const weekData = ruleData?.weekData?.list[day - 1]
  1254. if (!weekData) {
  1255. const err = new Error('获取当天跑步记录失败,请联系客服或稍后再试')
  1256. err.code = 'DAILY_RECORD_FETCH_FAILED'
  1257. err.retryable = false
  1258. throw err
  1259. }
  1260. if(Number(weekData?.distance) > 1.6) {
  1261. this.logger.warn(`${account}当天已存在成功跑步记录,距离:${weekData?.distance}km,请勿重复跑步`)
  1262. await this.writeSuccessRedis(account)
  1263. const err = new Error('当天已存在成功跑步记录,请勿重复跑步')
  1264. err.code = 'DAILY_ALREADY_COMPLETED'
  1265. err.retryable = false
  1266. throw err
  1267. }
  1268. const yyyy = now.getFullYear()
  1269. const mm = String(now.getMonth() + 1).padStart(2, '0')
  1270. const dd = String(now.getDate()).padStart(2, '0')
  1271. const formattedToday = `${yyyy}-${mm}-${dd}`
  1272. const boundary = String(Date.now())
  1273. const timestamp = String(Date.now())
  1274. const ossPath = `Public/Upload/file/run_record/${boundary.slice(-3)}/${formattedToday}/${timestamp}-${Math.floor(Math.random() * 150)}.txt`
  1275. await this.putOssWithFallback(sts, ossPath, Buffer.from(pathResult, 'utf-8'), ctx)
  1276. return { oss_path: ossPath, point_data: point_data }
  1277. })
  1278. this.register('lepao.uploadGyrOssFile', async (req, ctx) => {
  1279. const { newPathData, ossSts: sts, record_id } = req
  1280. // 生成加速度数据
  1281. const gyrData = generateGyrFromPath(newPathData)
  1282. if (!Array.isArray(gyrData) || gyrData.length === 0) {
  1283. this.logger.error('生成加速度数据失败')
  1284. return { status: 0, info: '生成加速度数据失败' }
  1285. }
  1286. const now = new Date()
  1287. const yyyy = now.getFullYear()
  1288. const mm = String(now.getMonth() + 1).padStart(2, '0')
  1289. const dd = String(now.getDate()).padStart(2, '0')
  1290. const formattedToday = `${yyyy}-${mm}-${dd}`
  1291. const boundary = String(Date.now())
  1292. const timestamp = String(Date.now())
  1293. const ossPath = `Public/Upload/file/run_gyroscope/${boundary.slice(-3)}/${formattedToday}/${timestamp}-${Math.floor(Math.random() * 150)}.txt`
  1294. await this.putOssWithFallback(sts, ossPath, Buffer.from(JSON.stringify(gyrData), 'utf-8'), ctx)
  1295. return this.request(
  1296. ctx.traceId,
  1297. 'bindData',
  1298. this.api('/Run2/gyroscope'),
  1299. () => {
  1300. const data = {
  1301. uid: req.uid,
  1302. token: req.token,
  1303. school_id: req.school_id,
  1304. term_id: 0,
  1305. course_id: 0,
  1306. class_id: 0,
  1307. student_num: req.student_id,
  1308. card_id: req.student_id,
  1309. timestamp: this.lepaoTimestamp(),
  1310. version: 1,
  1311. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1312. ostype: 5,
  1313. record_id: record_id,
  1314. gyroscope_file: ossPath
  1315. }
  1316. data.sign = dataSign(data)
  1317. return data
  1318. },
  1319. {},
  1320. ctx
  1321. )
  1322. })
  1323. /* ---------------- 提交跑步数据 ---------------- */
  1324. this.register('lepao.bindData', async (req, ctx) => {
  1325. const { pathData } = req
  1326. const distance = Number(Number(pathData.distance || 0).toFixed(2))
  1327. const stepData = generateCadence(distance, pathData.time)
  1328. const stepInfo = JSON.stringify({ interval: 60, list: stepData.cadence_list })
  1329. let points = req.point_data.map(({ address, jingwei, ...rest }) => rest)
  1330. points = JSON.stringify(points)
  1331. return this.request(
  1332. ctx.traceId,
  1333. 'bindData',
  1334. this.api('/Run/stopRunV278'),
  1335. () => {
  1336. const data = {
  1337. uid: req.uid,
  1338. token: req.token,
  1339. school_id: req.school_id,
  1340. term_id: 1,
  1341. course_id: 0,
  1342. class_id: 0,
  1343. student_num: req.student_id,
  1344. card_id: req.student_id,
  1345. timestamp: this.lepaoTimestamp(),
  1346. version: 1,
  1347. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1348. ostype: 5,
  1349. game_id: String(req.run_zone_id || 0),
  1350. start_time: req.run_end_time - Number(pathData.time),
  1351. end_time: req.run_end_time,
  1352. distance,
  1353. record_img: "",
  1354. log_data: points,
  1355. file_img: "",
  1356. is_running_area_valid: 1,
  1357. mobileDeviceId: 1,
  1358. mobileModel: req.deviceModel,
  1359. step_info: stepInfo,
  1360. step_num: stepData.total_steps,
  1361. used_time: pathData.time,
  1362. mobileOsVersion: 1,
  1363. record_file: req.record_file
  1364. }
  1365. data.sign = dataSign(data)
  1366. return data
  1367. },
  1368. {},
  1369. ctx
  1370. )
  1371. })
  1372. }
  1373. /* ================= Worker核心 ================= */
  1374. async start() {
  1375. if (this.running) return
  1376. this.stopping = false
  1377. this.running = true
  1378. this.logger.info('Worker 启动中...')
  1379. try {
  1380. this.initHandlers()
  1381. const channel = await mq.getChannel(this.channelName)
  1382. channel.once('close', () => {
  1383. this.scheduleRestart('consumer_channel_close')
  1384. })
  1385. channel.once('error', (err) => {
  1386. this.scheduleRestart(`consumer_channel_error:${err.message || err}`)
  1387. })
  1388. await channel.prefetch(5)
  1389. await assertRunforgeTaskIngress(channel, this.logger)
  1390. await channel.assertQueue(this.resultQueue, {
  1391. durable: true,
  1392. arguments: {
  1393. 'x-max-length': this.maxQueueLength
  1394. }
  1395. })
  1396. await channel.assertQueue(this.deadQueue, {
  1397. durable: true,
  1398. arguments: {
  1399. 'x-max-length': this.maxQueueLength
  1400. }
  1401. })
  1402. await channel.consume(this.taskQueue, async (msg) => {
  1403. if (!msg) return
  1404. let content
  1405. try {
  1406. content = JSON.parse(msg.content.toString())
  1407. } catch {
  1408. return this.safeAck(channel, msg, 'bad_json')
  1409. }
  1410. const { id, type, data, retry = 0 } = content
  1411. const traceId = this.traceId()
  1412. const handler = this.handlers[type]
  1413. if (!handler) {
  1414. this.log(traceId, 'ERROR', '未知任务', { type })
  1415. return this.safeAck(channel, msg, traceId)
  1416. }
  1417. try {
  1418. const proxyEnabled = await isProxyForwardEnabled()
  1419. const outboundMode = proxyEnabled ? 'proxy' : 'direct'
  1420. const result = await this.withTimeout(
  1421. handler(data, {
  1422. traceId,
  1423. channel,
  1424. taskId: id,
  1425. outboundMode,
  1426. retry,
  1427. maxRetry: this.maxRetry
  1428. }),
  1429. type,
  1430. this.taskTimeoutMs,
  1431. { code: 'TASK_TIMEOUT', retryable: true }
  1432. )
  1433. try {
  1434. await this.sendResult(null, {
  1435. id,
  1436. success: true,
  1437. result
  1438. })
  1439. } catch (resultErr) {
  1440. this.logger.error(`[${traceId}] 任务已完成但结果投递失败: ${resultErr.stack || resultErr}`)
  1441. }
  1442. this.log(traceId, 'DONE', `任务完成 ${type}`)
  1443. this.safeAck(channel, msg, traceId)
  1444. } catch (err) {
  1445. this.logErr(traceId, `任务失败 ${type}`, err)
  1446. try {
  1447. if (retry < this.maxRetry && this.isRetryableTaskError(err)) {
  1448. await this.publishJson(this.taskQueue, {
  1449. ...content,
  1450. retry: retry + 1
  1451. }, { channelName: 'lepao_worker_publish_task' })
  1452. this.log(traceId, 'RETRY', `重试第${retry + 1}次`)
  1453. } else {
  1454. await this.publishJson(this.deadQueue, content, {
  1455. channelName: 'lepao_worker_publish_dead'
  1456. })
  1457. this.log(traceId, 'DEAD', '进入死信队列')
  1458. }
  1459. await this.sendResult(null, {
  1460. id,
  1461. success: false,
  1462. error: err.code === 'TASK_TIMEOUT' ? '系统繁忙,请稍后再试' : this.maskClientReason(err.message)
  1463. })
  1464. this.safeAck(channel, msg, traceId)
  1465. } catch (publishErr) {
  1466. this.logger.error(`[${traceId}] MQ 失败处理投递失败,原消息保留等待重投: ${publishErr.stack || publishErr}`)
  1467. this.safeNack(channel, msg, traceId, true)
  1468. }
  1469. }
  1470. })
  1471. this.logger.info(`RunForge Worker 启动成功,消费队列 ${this.taskQueue}`)
  1472. } catch (err) {
  1473. this.logger.error('RunForge Worker 启动失败: ' + err.stack)
  1474. this.running = false
  1475. throw err
  1476. }
  1477. }
  1478. async sendResult(_channel, data) {
  1479. await this.publishJson(this.resultQueue, data, {
  1480. channelName: 'lepao_worker_publish_result',
  1481. contentType: 'application/json'
  1482. })
  1483. }
  1484. async stop() {
  1485. this.stopping = true
  1486. if (this.restartTimer) {
  1487. clearTimeout(this.restartTimer)
  1488. this.restartTimer = null
  1489. }
  1490. this.running = false
  1491. await mq.close()
  1492. this.logger.info('RunForge Worker 已停止')
  1493. }
  1494. }
  1495. module.exports = Worker