Worker.js 60 KB

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