Worker.js 58 KB

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