Worker.js 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535
  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. // 登录失效/过期(多种文案变体)
  71. m.includes('乐跑账号登录已过期') ||
  72. m.includes('登录已过期') ||
  73. m.includes('登录信息失效') ||
  74. m.includes('登录失效') ||
  75. m.includes('登录状态异常') ||
  76. m.includes('token已过期') ||
  77. m.includes('token 过期') ||
  78. m.includes('Token已过期') ||
  79. m.includes('Token 过期') ||
  80. // 兜底:出现“重新登录”通常也是登录态问题
  81. m.includes('请重新登录')
  82. )
  83. }
  84. async notifyAdminsUncommonLepaoError(payload) {
  85. try {
  86. const { account, traceId, taskType, reason, code, name } = payload || {}
  87. if (!account || !reason) return
  88. if (this.isCommonLepaoErrorMessage(reason)) return
  89. const day = this.formatYmdLocal()
  90. const msgHash = this.simpleHash(reason)
  91. const rateKey = `lepao:adminWarn:${account}:${day}:${msgHash}`
  92. const existed = await Redis.get(rateKey)
  93. if (existed) return
  94. await Redis.set(rateKey, '1', { EX: 86400 })
  95. const adminSql = `
  96. SELECT email
  97. FROM users
  98. WHERE email IS NOT NULL
  99. AND email <> ''
  100. AND (JSON_CONTAINS(permission, '"admin"') OR JSON_CONTAINS(permission, '"service"'))
  101. `
  102. const adminRows = await db.query(adminSql)
  103. if (!adminRows || adminRows.length === 0) {
  104. this.logger.warn(`[lepaoAdminWarn][${traceId}] 未找到可通知的管理员邮箱`)
  105. return
  106. }
  107. const emails = [...new Set(adminRows.map(r => r.email).filter(Boolean))]
  108. for (const email of emails) {
  109. await EmailTemplate.lepaoAdminWarning(email, {
  110. server: (() => {
  111. try {
  112. // config.json 可能在其他模块缓存读取,这里动态 require 一次避免循环依赖
  113. // eslint-disable-next-line global-require
  114. const cfg = require('../../config.json')
  115. return cfg?.server || ''
  116. } catch (_) {
  117. return ''
  118. }
  119. })(),
  120. account,
  121. name: name || '',
  122. taskType: taskType || 'lepao.startRun',
  123. traceId: traceId || '',
  124. reason,
  125. code: code || ''
  126. })
  127. }
  128. } catch (e) {
  129. this.logger.error(`[lepaoAdminWarn] 告警邮件发送失败:${e.message || e}`)
  130. }
  131. }
  132. api(path) {
  133. return this.baseUrl + path
  134. }
  135. traceId() {
  136. return Date.now() + '_' + Math.random().toString(36).slice(2, 8)
  137. }
  138. sleep(ms) {
  139. return new Promise(r => setTimeout(r, ms))
  140. }
  141. buildOssBaseClientConfig(sts) {
  142. return {
  143. bucket: sts.bucket,
  144. region: sts.region || 'oss-cn-hangzhou',
  145. accessKeyId: sts.AccessKeyId,
  146. accessKeySecret: sts.AccessKeySecret,
  147. stsToken: sts.SecurityToken,
  148. secure: true
  149. }
  150. }
  151. buildProxyUrlFromFragment(fragment) {
  152. if (!fragment || fragment.proxy === false || !fragment.proxy) return null
  153. const { host, port, auth } = fragment.proxy
  154. let userPart = ''
  155. if (auth && String(auth.username || '').length > 0) {
  156. const u = encodeURIComponent(auth.username)
  157. const p = encodeURIComponent(auth.password != null ? String(auth.password) : '')
  158. userPart = `${u}:${p}@`
  159. }
  160. return `http://${userPart}${host}:${port}`
  161. }
  162. async putOssWithFallback(sts, ossPath, content) {
  163. const directClient = new OSS(this.buildOssBaseClientConfig(sts))
  164. await directClient.put(ossPath, content)
  165. }
  166. isRunSuccess(bindResponse) {
  167. const payload = bindResponse?.data
  168. if (!bindResponse || bindResponse.status !== 1 || !payload) {
  169. return {
  170. ok: false,
  171. reason: bindResponse?.info || '系统繁忙,请联系客服或稍后再试'
  172. }
  173. }
  174. const failedReason = payload.record_failed_reason || ''
  175. if (failedReason === '' || failedReason === '自动确认有效') {
  176. return { ok: true, payload }
  177. }
  178. return {
  179. ok: false,
  180. reason: failedReason,
  181. payload
  182. }
  183. }
  184. maskClientReason(reason) {
  185. const s = String(reason || '')
  186. if (s.includes('非法请求')) {
  187. return '系统繁忙,请稍后再试'
  188. }
  189. return s
  190. }
  191. extractApiErrorMessage(name, result) {
  192. if (!result) {
  193. this.logger.error(`${name} 接口无响应数据: ${this.safeStringify(result)}`)
  194. return `系统繁忙,请联系客服或稍后再试`
  195. }
  196. const candidates = [
  197. result.info,
  198. result.msg,
  199. result.message,
  200. result?.data?.info,
  201. result?.data?.msg,
  202. result?.data?.message,
  203. result?.data?.record_failed_reason
  204. ]
  205. const reason = candidates.find(v => typeof v === 'string' && v.trim() !== '')
  206. if (reason) {
  207. return this.maskClientReason(reason)
  208. }
  209. if (result.code !== undefined || result.status !== undefined) {
  210. this.logger.error(`${name} 接口返回异常: ${this.safeStringify(result)}`)
  211. return `系统繁忙,请联系客服或稍后再试`
  212. }
  213. return `系统繁忙,请联系客服或稍后再试`
  214. }
  215. async markLoginExpired(account) {
  216. if (!account) return
  217. try {
  218. const sql = 'UPDATE lepao_account SET state = 0 WHERE student_num = ?'
  219. await db.query(sql, [account])
  220. this.logger.warn(`${account} 登录状态已失效,已自动更新为未登录`)
  221. } catch (error) {
  222. this.logger.error(`更新账号登录状态失败:${error.stack || error}`)
  223. }
  224. }
  225. async writeSuccessRedis(account) {
  226. if (!account) return
  227. try {
  228. const now = new Date()
  229. const tomorrow = new Date().setHours(24, 0, 0, 0)
  230. const exp = Math.floor((tomorrow - now) / 1000)
  231. await Redis.set(`lepaoSuccess:${account}`, account, { EX: exp })
  232. } catch (error) {
  233. this.logger.error(`写入乐跑成功缓存失败: ${error.stack || error}`)
  234. }
  235. }
  236. async addLepaoRecord(uuid, account, result, pathId, pointData, runMode = 'auto') {
  237. if (!uuid || !account || !result || !pathId) return
  238. try {
  239. const time = Date.now()
  240. const publicId = uuidv4()
  241. const safeRunMode = runMode === 'manual' ? 'manual' : 'auto'
  242. const sql = 'INSERT INTO lepao_record (public_id, uuid, time, lepao_account, result, path_id, point_data, state, run_mode) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'
  243. await db.query(sql, [publicId, uuid, time, account, result, pathId, JSON.stringify(pointData || []), 1, safeRunMode])
  244. } catch (error) {
  245. this.logger.error(`写入乐跑记录失败: ${error.stack || error}`)
  246. }
  247. }
  248. async syncRunCount(req, ctx) {
  249. try {
  250. const sid = req?.student_id || req?.account
  251. if (
  252. req?.uid == null ||
  253. req?.token == null ||
  254. String(req.token).trim() === '' ||
  255. req?.school_id == null ||
  256. !sid
  257. ) {
  258. return { ok: false, reason: '缺少同步乐跑次数所需凭证' }
  259. }
  260. const recordData = await this.handlers['lepao.getRecord'](req, ctx)
  261. const data = recordData?.data
  262. if (!data) {
  263. return { ok: false, reason: 'getRecord 无有效 data' }
  264. }
  265. const term_num = Number(data.term_num ?? 30)
  266. const total_num = Number(data.total_num ?? 0)
  267. const sql = 'UPDATE lepao_account SET term_num = ?, total_num = ? WHERE student_num = ?'
  268. const rows = await db.query(sql, [term_num, total_num, req.account])
  269. if (!rows || rows.affectedRows !== 1) {
  270. this.logger.warn(`${req.account}更新乐跑次数失败`)
  271. return { ok: false, reason: '数据库更新 lepao_account 失败', term_num, total_num }
  272. }
  273. this.logger.info(`${req.account}更新乐跑次数成功 term_num=${term_num}, total_num=${total_num}`)
  274. return { ok: true, term_num, total_num }
  275. } catch (error) {
  276. this.logger.warn(`${req?.account || 'unknown'}同步乐跑次数失败: ${error.message || error}`)
  277. return { ok: false, reason: error.message || String(error) }
  278. }
  279. }
  280. lepaoTimestamp() {
  281. return Number((Date.now() / 1000).toFixed(3))
  282. }
  283. async enqueueTask(channel, type, data, options = {}) {
  284. const payload = {
  285. id: options.id || this.traceId(),
  286. type,
  287. data,
  288. retry: options.retry ?? 0
  289. }
  290. await channel.sendToQueue(
  291. this.taskQueue,
  292. Buffer.from(JSON.stringify(payload)),
  293. { persistent: true, contentType: 'application/json' }
  294. )
  295. return payload.id
  296. }
  297. async withTimeout(promise, name, timeoutMs, options = {}) {
  298. const ms = Number.isFinite(Number(timeoutMs)) ? Number(timeoutMs) : this.taskTimeoutMs
  299. const { code = 'TIMEOUT', retryable = false } = options || {}
  300. return Promise.race([
  301. promise,
  302. new Promise((_, reject) =>
  303. setTimeout(() => {
  304. const err = new Error(`${name} 超时`)
  305. err.code = code
  306. err.retryable = !!retryable
  307. reject(err)
  308. }, ms)
  309. )
  310. ])
  311. }
  312. async retry(fn, name) {
  313. let lastErr
  314. for (let i = 0; i < this.maxRetry; i++) {
  315. try {
  316. return await fn()
  317. } catch (err) {
  318. lastErr = err
  319. if (!this.isRetryableTaskError(err)) {
  320. throw err
  321. }
  322. this.logger.warn(`[RETRY] ${name} 第${i + 1}次失败`)
  323. await this.sleep(1000 * (i + 1)) // 指数退避
  324. }
  325. }
  326. throw lastErr
  327. }
  328. isNetworkError(err) {
  329. if (!err) return false
  330. if (err.code && ['ECONNRESET', 'ECONNABORTED', 'ETIMEDOUT', 'ENOTFOUND', 'EAI_AGAIN'].includes(err.code)) {
  331. return true
  332. }
  333. if (err.isAxiosError && !err.response) return true
  334. const msg = (err.message || '').toLowerCase()
  335. return msg.includes('timeout') || msg.includes('network')
  336. }
  337. isRetryableTaskError(err) {
  338. if (!err) return false
  339. if (err.retryable === true) return true
  340. if (this.isNetworkError(err)) return true
  341. return ['PATH_SELECT_FAILED', 'CHECKPOINT_FETCH_FAILED', 'CHECKPOINT_INSUFFICIENT'].includes(err.code)
  342. }
  343. safeStringify(obj) {
  344. const seen = new WeakSet();
  345. return JSON.stringify(obj, (key, value) => {
  346. if (typeof value === 'object' && value !== null) {
  347. if (seen.has(value)) return '[Circular]';
  348. seen.add(value);
  349. }
  350. return value;
  351. })
  352. }
  353. log(traceId, type, msg, data) {
  354. this.logger.info(`[${traceId}] [${type}] ${msg} ${data ? this.safeStringify(data) : ''}`)
  355. }
  356. logErr(traceId, msg, err) {
  357. this.logger.error(`[${traceId}] ${msg} ${err.stack || err}`)
  358. }
  359. async request(traceId, name, url, raw, headers = {}, ctx = null) {
  360. return this.retry(async () => {
  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. }),
  384. name,
  385. this.httpTimeoutMs,
  386. { code: 'HTTP_TIMEOUT', retryable: true }
  387. )
  388. let result = res.data
  389. if (result?.data && result?.is_encrypt === 1) {
  390. result.data = JSON.parse(dataDecrypt(result.data))
  391. }
  392. this.log(traceId, 'RES', name, result)
  393. // 除 bindData 外,其余调用若接口已明确返回失败,直接抛出该失败原因
  394. // bindData 需要保留完整响应由 isRunSuccess 统一判定。
  395. if (name !== 'bindData') {
  396. const hasCode = result && Object.prototype.hasOwnProperty.call(result, 'code')
  397. const hasStatus = result && Object.prototype.hasOwnProperty.call(result, 'status')
  398. const failedByCode = hasCode && Number(result.code) !== 1 && Number(result.code) !== 200
  399. const failedByStatus = hasStatus && Number(result.status) !== 1
  400. if (failedByCode || failedByStatus) {
  401. const message = this.extractApiErrorMessage(name, result)
  402. const err = new Error(message)
  403. // 学习 Lepao.js:若明确提示重新登录,自动标记账号失效
  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. const now = this.lepaoTimestamp()
  1005. const raw = {
  1006. uid: req.uid,
  1007. token: req.token,
  1008. school_id: req.school_id,
  1009. term_id: 0,
  1010. course_id: 0,
  1011. class_id: 0,
  1012. student_num: req.student_id,
  1013. card_id: req.student_id,
  1014. timestamp: now,
  1015. version: 1,
  1016. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1017. ostype: 5
  1018. }
  1019. raw.sign = dataSign(raw)
  1020. return this.request(
  1021. ctx.traceId,
  1022. 'getRecord',
  1023. this.api('/Run2/beforeRunV260'),
  1024. raw,
  1025. {
  1026. 'User-Agent': req.userAgent,
  1027. 'charset': 'utf-8',
  1028. 'Referer': 'https://servicewechat.com/wxf94c4ddb63d87ede/32/page-frame.html',
  1029. },
  1030. ctx
  1031. )
  1032. })
  1033. /* ---------------- 切换跑区 ---------------- */
  1034. this.register('lepao.setZone', async (req, ctx) => {
  1035. const runZoneMap = {
  1036. '兰花湖校区跑区': 2,
  1037. '主校区北跑区': 3,
  1038. '主校区南跑区': 5,
  1039. '重庆工商大学茶园校区': 6
  1040. }
  1041. const { pathData } = req
  1042. const runZoneId = runZoneMap[pathData.run_zone_name]
  1043. if (!runZoneId) throw new Error('跑区不存在')
  1044. const raw = {
  1045. uid: req.uid,
  1046. token: req.token,
  1047. school_id: req.school_id,
  1048. term_id: 0,
  1049. course_id: 0,
  1050. class_id: 0,
  1051. student_num: req.student_id,
  1052. card_id: req.student_id,
  1053. timestamp: this.lepaoTimestamp(),
  1054. version: 1,
  1055. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1056. ostype: 5,
  1057. run_zone_id: String(runZoneId)
  1058. }
  1059. raw.sign = dataSign(raw)
  1060. await this.request(
  1061. ctx.traceId,
  1062. 'setZone',
  1063. this.api('/Run/setRunZone'),
  1064. raw,
  1065. {},
  1066. ctx
  1067. )
  1068. return { run_zone_id: runZoneId }
  1069. })
  1070. /* ---------------- 获取 OSS STS ---------------- */
  1071. this.register('lepao.getOssSts', async (req, ctx) => {
  1072. const raw = {
  1073. uid: req.uid,
  1074. token: req.token,
  1075. school_id: req.school_id,
  1076. term_id: 0,
  1077. course_id: 0,
  1078. class_id: 0,
  1079. student_num: req.student_id,
  1080. card_id: req.student_id,
  1081. timestamp: this.lepaoTimestamp(),
  1082. version: 1,
  1083. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1084. ostype: 5
  1085. }
  1086. raw.sign = dataSign(raw)
  1087. const res = await this.request(
  1088. ctx.traceId,
  1089. 'getOssSts',
  1090. this.api('/WpIndex/getOssSts'),
  1091. raw,
  1092. {},
  1093. ctx
  1094. )
  1095. return res.data
  1096. })
  1097. /* ---------------- 上传 OSS 文件 ---------------- */
  1098. this.register('lepao.uploadOssFile', async (req, ctx) => {
  1099. const { pathData, newPathData, ossSts: sts } = req
  1100. // 处理跑步路径
  1101. const pathResult = dataEncrypt(JSON.stringify(newPathData))
  1102. // 获取跑步规则参数
  1103. const runRule = await this.handlers['lepao.getRecord'](req, ctx)
  1104. const ruleData = runRule?.data
  1105. if (!ruleData?.run_line_info?.point_list || !ruleData?.time_rule_arr?.length) {
  1106. const err = new Error('获取打卡点规则失败')
  1107. err.code = 'CHECKPOINT_FETCH_FAILED'
  1108. err.retryable = true
  1109. throw err
  1110. }
  1111. const check_points = ruleData.run_line_info.point_list
  1112. let min_log_num = ruleData.time_rule_arr[0]?.min_log_num || 4
  1113. const point_update_distance = parseFloat(ruleData.run_line_info.point_update_distance || 0) * 1000
  1114. const log_max_distance = Number(ruleData.run_line_info.log_max_distance || 0)
  1115. // 生成打卡点
  1116. const point_data = selectCheckpoints(newPathData, check_points, min_log_num, point_update_distance, log_max_distance, req.run_end_time, pathData.time)
  1117. if (!point_data) {
  1118. this.logger.warn(`[RETRY] 打卡点数量不足,重新更换路径`)
  1119. const err = new Error('打卡点数量不足')
  1120. err.code = 'CHECKPOINT_INSUFFICIENT'
  1121. err.retryable = true
  1122. throw err
  1123. }
  1124. const now = new Date()
  1125. const yyyy = now.getFullYear()
  1126. const mm = String(now.getMonth() + 1).padStart(2, '0')
  1127. const dd = String(now.getDate()).padStart(2, '0')
  1128. const formattedToday = `${yyyy}-${mm}-${dd}`
  1129. const boundary = String(Date.now())
  1130. const timestamp = String(Date.now())
  1131. const ossPath = `Public/Upload/file/run_record/${boundary.slice(-3)}/${formattedToday}/${timestamp}-${Math.floor(Math.random() * 150)}.txt`
  1132. await this.putOssWithFallback(sts, ossPath, Buffer.from(pathResult, 'utf-8'))
  1133. return { oss_path: ossPath, point_data: point_data }
  1134. })
  1135. this.register('lepao.uploadGyrOssFile', async (req, ctx) => {
  1136. const { newPathData, ossSts: sts, record_id } = req
  1137. // 生成加速度数据
  1138. const gyrData = generateGyrFromPath(newPathData)
  1139. if (!Array.isArray(gyrData) || gyrData.length === 0) {
  1140. this.logger.error('生成加速度数据失败')
  1141. return { status: 0, info: '生成加速度数据失败' }
  1142. }
  1143. const now = new Date()
  1144. const yyyy = now.getFullYear()
  1145. const mm = String(now.getMonth() + 1).padStart(2, '0')
  1146. const dd = String(now.getDate()).padStart(2, '0')
  1147. const formattedToday = `${yyyy}-${mm}-${dd}`
  1148. const boundary = String(Date.now())
  1149. const timestamp = String(Date.now())
  1150. const ossPath = `Public/Upload/file/run_gyroscope/${boundary.slice(-3)}/${formattedToday}/${timestamp}-${Math.floor(Math.random() * 150)}.txt`
  1151. await this.putOssWithFallback(sts, ossPath, Buffer.from(JSON.stringify(gyrData), 'utf-8'))
  1152. const data = {
  1153. uid: req.uid,
  1154. token: req.token,
  1155. school_id: req.school_id,
  1156. term_id: 0,
  1157. course_id: 0,
  1158. class_id: 0,
  1159. student_num: req.student_id,
  1160. card_id: req.student_id,
  1161. timestamp: this.lepaoTimestamp(),
  1162. version: 1,
  1163. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1164. ostype: 5,
  1165. record_id: record_id,
  1166. gyroscope_file: ossPath
  1167. }
  1168. data.sign = dataSign(data)
  1169. return this.request(
  1170. ctx.traceId,
  1171. 'bindData',
  1172. this.api('/Run2/gyroscope'),
  1173. data,
  1174. {},
  1175. ctx
  1176. )
  1177. })
  1178. /* ---------------- 提交跑步数据 ---------------- */
  1179. this.register('lepao.bindData', async (req, ctx) => {
  1180. const { pathData } = req
  1181. const distance = Number(Number(pathData.distance || 0).toFixed(2))
  1182. const stepData = generateCadence(distance, pathData.time)
  1183. const stepInfo = JSON.stringify({ interval: 60, list: stepData.cadence_list })
  1184. let points = req.point_data.map(({ address, jingwei, ...rest }) => rest)
  1185. points = JSON.stringify(points)
  1186. const data = {
  1187. uid: req.uid,
  1188. token: req.token,
  1189. school_id: req.school_id,
  1190. term_id: 1,
  1191. course_id: 0,
  1192. class_id: 0,
  1193. student_num: req.student_id,
  1194. card_id: req.student_id,
  1195. timestamp: this.lepaoTimestamp(),
  1196. version: 1,
  1197. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1198. ostype: 5,
  1199. game_id: String(req.run_zone_id || 0),
  1200. start_time: req.run_end_time - Number(pathData.time),
  1201. end_time: req.run_end_time,
  1202. distance,
  1203. record_img: "",
  1204. log_data: points,
  1205. file_img: "",
  1206. is_running_area_valid: 1,
  1207. mobileDeviceId: 1,
  1208. mobileModel: req.deviceModel,
  1209. step_info: stepInfo,
  1210. step_num: stepData.total_steps,
  1211. used_time: pathData.time,
  1212. mobileOsVersion: 1,
  1213. record_file: req.record_file
  1214. }
  1215. data.sign = dataSign(data)
  1216. return this.request(
  1217. ctx.traceId,
  1218. 'bindData',
  1219. this.api('/Run/stopRunV278'),
  1220. data,
  1221. {},
  1222. ctx
  1223. )
  1224. })
  1225. }
  1226. /* ================= Worker核心 ================= */
  1227. async start() {
  1228. if (this.running) return
  1229. this.running = true
  1230. this.logger.info('Worker 启动中...')
  1231. try {
  1232. this.initHandlers()
  1233. const channel = await mq.getChannel(this.channelName)
  1234. await channel.prefetch(5)
  1235. await assertRunforgeTaskIngress(channel, this.logger)
  1236. await channel.assertQueue(this.resultQueue, {
  1237. durable: true,
  1238. arguments: {
  1239. 'x-max-length': this.maxQueueLength
  1240. }
  1241. })
  1242. await channel.assertQueue(this.deadQueue, {
  1243. durable: true,
  1244. arguments: {
  1245. 'x-max-length': this.maxQueueLength
  1246. }
  1247. })
  1248. await channel.consume(this.taskQueue, async (msg) => {
  1249. if (!msg) return
  1250. let content
  1251. try {
  1252. content = JSON.parse(msg.content.toString())
  1253. } catch {
  1254. return channel.ack(msg)
  1255. }
  1256. const { id, type, data, retry = 0 } = content
  1257. const traceId = this.traceId()
  1258. const handler = this.handlers[type]
  1259. if (!handler) {
  1260. this.log(traceId, 'ERROR', '未知任务', { type })
  1261. return channel.ack(msg)
  1262. }
  1263. try {
  1264. const proxyEnabled = await QgProxyManager.isOutboundProxyEnabled()
  1265. const outboundMode = proxyEnabled ? 'proxy' : 'direct'
  1266. const result = await this.withTimeout(
  1267. handler(data, {
  1268. traceId,
  1269. channel,
  1270. taskId: id,
  1271. outboundMode,
  1272. retry,
  1273. maxRetry: this.maxRetry
  1274. }),
  1275. type,
  1276. this.taskTimeoutMs,
  1277. { code: 'TASK_TIMEOUT', retryable: true }
  1278. )
  1279. await this.sendResult(channel, {
  1280. id,
  1281. success: true,
  1282. result
  1283. })
  1284. this.log(traceId, 'DONE', `任务完成 ${type}`)
  1285. channel.ack(msg)
  1286. } catch (err) {
  1287. this.logErr(traceId, `任务失败 ${type}`, err)
  1288. if (retry < this.maxRetry && this.isRetryableTaskError(err)) {
  1289. // 重试
  1290. await channel.sendToQueue(
  1291. this.taskQueue,
  1292. Buffer.from(JSON.stringify({
  1293. ...content,
  1294. retry: retry + 1
  1295. })),
  1296. { persistent: true }
  1297. )
  1298. this.log(traceId, 'RETRY', `重试第${retry + 1}次`)
  1299. } else {
  1300. // 死信
  1301. await channel.sendToQueue(
  1302. this.deadQueue,
  1303. Buffer.from(JSON.stringify(content)),
  1304. { persistent: true }
  1305. )
  1306. this.log(traceId, 'DEAD', '进入死信队列')
  1307. }
  1308. await this.sendResult(channel, {
  1309. id,
  1310. success: false,
  1311. error: err.code === 'TASK_TIMEOUT' ? '系统繁忙,请稍后再试' : this.maskClientReason(err.message)
  1312. })
  1313. channel.ack(msg)
  1314. }
  1315. })
  1316. this.logger.info('RunForge Worker 启动成功')
  1317. } catch (err) {
  1318. this.logger.error('RunForge Worker 启动失败: ' + err.stack)
  1319. }
  1320. }
  1321. async sendResult(channel, data) {
  1322. channel.sendToQueue(
  1323. this.resultQueue,
  1324. Buffer.from(JSON.stringify(data)),
  1325. { persistent: true }
  1326. )
  1327. }
  1328. async stop() {
  1329. this.running = false
  1330. await mq.close()
  1331. this.logger.info('RunForge Worker 已停止')
  1332. }
  1333. }
  1334. module.exports = Worker