Worker.js 59 KB

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