Worker.js 60 KB

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