Worker.js 58 KB

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