Worker.js 59 KB

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