Worker.js 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575
  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. const minSec = 2 * 60 * 60
  545. const maxSec = 12 * 60 * 60
  546. const advanceSec = Math.floor(Math.random() * (maxSec - minSec + 1)) + minSec
  547. this.logger.info(`${req.account}当前时间为${hour}点,调整run_end_time提前${advanceSec}秒(约${(advanceSec / 3600).toFixed(2)}小时)`)
  548. run_end_time -= advanceSec
  549. }
  550. req = {
  551. ...req,
  552. run_end_time
  553. }
  554. // 1.5️⃣ 乐跑开始前扣减次数(同一 MQ taskId 仅扣一次;仅当所有重试均失败后在 catch 中返还)
  555. await this.handlers['lepao.consumeCount']({
  556. account: req.account,
  557. uuid: userData?.create_user
  558. }, ctx)
  559. while (pathRetry < maxPathRetry) {
  560. try {
  561. // 2️⃣ 获取路径(仅路径选择失败时重试)
  562. const pathRes = await this.handlers['lepao.getPath'](req, ctx)
  563. pathData = pathRes.pathData
  564. pathId = pathData?.id || null
  565. newPathData = getPathData(pathData.data, req.run_end_time, pathData.time)
  566. // 3️⃣ 切换跑区
  567. const zoneRes = await this.handlers['lepao.setZone']({ ...req, pathData }, ctx)
  568. runZoneId = zoneRes?.run_zone_id || 0
  569. // 4️⃣ 上传 OSS 文件、生成打卡点
  570. const uploadRes = await this.handlers['lepao.uploadOssFile']({ ...req, pathData, newPathData }, ctx)
  571. ossPath = uploadRes.oss_path
  572. pointData = uploadRes.point_data
  573. if (!pointData) {
  574. pathRetry++
  575. this.logger.warn(`[${traceId}] 打卡点不满足要求,重新获取路径 第${pathRetry}次`)
  576. continue
  577. }
  578. // 打卡点符合要求,跳出循环
  579. break
  580. } catch (err) {
  581. if (!this.isRetryableTaskError(err)) {
  582. throw err
  583. }
  584. this.logger.warn(`[${traceId}] 可重试错误,重新获取路径 第${pathRetry + 1}次,原因:${err.message}`)
  585. pathRetry++
  586. await this.sleep(1000 * pathRetry)
  587. }
  588. }
  589. if (!pointData) {
  590. throw new Error('打卡点获取失败,乐跑任务终止')
  591. }
  592. // 5️⃣ 提交跑步数据
  593. bindRes = await this.handlers['lepao.bindData']({
  594. ...req,
  595. pathData,
  596. run_zone_id: runZoneId,
  597. record_file: ossPath,
  598. point_data: pointData
  599. }, ctx)
  600. // 绑定接口有返回即入库
  601. if (bindRes && bindRes.data) {
  602. await this.addLepaoRecord(userData?.create_user, req.account, bindRes.data, pathId, pointData, req.runMode)
  603. }
  604. const runResult = this.isRunSuccess(bindRes)
  605. if (runResult.ok || runResult.reason === '当天关联成绩次数已达到上限') {
  606. await this.writeSuccessRedis(req.account)
  607. }
  608. if (!runResult.ok) {
  609. throw new Error(this.maskClientReason(runResult.reason))
  610. }
  611. if (bindRes && bindRes.data && bindRes.data.record_id) {
  612. const gyrRes = await this.handlers['lepao.uploadGyrOssFile']({ ...req, newPathData, record_id: bindRes.data.record_id }, ctx)
  613. if (gyrRes?.status === 1) {
  614. this.logger.info(`${req.account}上传加速度数据成功!`)
  615. } else {
  616. this.logger.error(`${req.account}上传加速度数据失败!原因:${gyrRes.info || '未知错误'}`)
  617. }
  618. }
  619. // 同步乐跑次数(通知里要带 total_num / term_num,与 getRecord 一致)
  620. const syncResult = await this.syncRunCount(req, ctx)
  621. if (!syncResult?.ok) {
  622. this.logger.error(
  623. `[${traceId}] 同步乐跑次数失败:${syncResult?.reason || 'unknown'}`
  624. )
  625. }
  626. // 6️⃣ 发送通知(把同步后的学期次数、累计完成次数传给 Bot / 邮件)
  627. if (ctx.channel) {
  628. await this.enqueueTask(
  629. ctx.channel,
  630. 'lepao.sendNotice',
  631. {
  632. account: req.account,
  633. success: true,
  634. data: runResult.payload,
  635. traceId,
  636. total_num: syncResult?.ok ? syncResult.total_num : undefined
  637. },
  638. { id: `${traceId}:notice:success` }
  639. )
  640. }
  641. return { traceId, ossPath, pointData, bindRes }
  642. } catch (err) {
  643. this.logger.error(`[${traceId}] 乐跑流程失败:`, err)
  644. const retryNow = Number(ctx?.retry || 0)
  645. const maxRetry = Number(ctx?.maxRetry ?? this.maxRetry)
  646. const canRetry = this.isRetryableTaskError(err) && retryNow < maxRetry
  647. const isFinalAttemptFail = !canRetry
  648. // 仅在所有重试均失败后才发异常告警/失败通知,避免每次重试都打扰
  649. if (isFinalAttemptFail) {
  650. Promise.resolve().then(async () => {
  651. try {
  652. await this.notifyAdminsUncommonLepaoError({
  653. account: req?.account,
  654. name: userData?.name,
  655. traceId,
  656. taskType: 'lepao.startRun',
  657. reason: err?.message || '未知错误',
  658. code: err?.code
  659. })
  660. } catch (_) { }
  661. })
  662. }
  663. // 仅终局失败(不可再 MQ 重试)时返还;中间重试保持已扣次数,避免重复扣/退抖动
  664. if (isFinalAttemptFail) {
  665. try {
  666. await this.handlers['lepao.refundCount']({
  667. account: req.account,
  668. uuid: userData?.create_user
  669. }, ctx)
  670. } catch (e) {
  671. this.logger.error(`[${traceId}] 返还乐跑次数失败:${e.stack || e}`)
  672. }
  673. }
  674. if (ctx.channel && isFinalAttemptFail) {
  675. await this.enqueueTask(ctx.channel, 'lepao.sendNotice', {
  676. account: req.account,
  677. success: false,
  678. reason:
  679. err?.code === 'TASK_TIMEOUT'
  680. ? '系统繁忙,请稍后再试'
  681. : this.maskClientReason(err.message || '未知错误'),
  682. traceId
  683. }, { id: `${traceId}:notice:fail` })
  684. }
  685. throw err
  686. } finally {
  687. await Redis.del(`lepaoProgress:${req.account}`)
  688. }
  689. })
  690. /* ---------------- 发送通知(独立 MQ 任务) ---------------- */
  691. this.register('lepao.sendNotice', async (req, ctx) => {
  692. const { account, success, data, reason, traceId, total_num: totalNumArg } = req || {}
  693. if (!account) {
  694. throw new Error('发送通知失败:缺少 account')
  695. }
  696. const emailSql = `
  697. SELECT
  698. a.name,
  699. a.email,
  700. a.target_count,
  701. a.notice_type,
  702. e.bot_umo,
  703. a.update_type
  704. FROM
  705. lepao_account a
  706. LEFT JOIN
  707. lepao_extra e
  708. ON
  709. a.student_num = e.student_num
  710. WHERE
  711. a.student_num = ?
  712. `
  713. const rows = await db.query(emailSql, [account])
  714. if (!rows || rows.length === 0) {
  715. throw new Error('发送通知失败:未找到用户通知配置')
  716. }
  717. const user = rows[0]
  718. const noticeType = user.notice_type || 'none'
  719. let totalForNotice = totalNumArg
  720. if (
  721. success &&
  722. (totalForNotice === undefined || totalForNotice === null)
  723. ) {
  724. const accRows = await db.query(
  725. 'SELECT total_num FROM lepao_account WHERE student_num = ?',
  726. [account]
  727. )
  728. if (accRows && accRows[0]) {
  729. totalForNotice = accRows[0].total_num
  730. }
  731. }
  732. if (totalForNotice === undefined || totalForNotice === null) {
  733. totalForNotice = 0
  734. }
  735. totalForNotice = Number(totalForNotice)
  736. const targetCount = Number(user.target_count) || 0
  737. const payload = success ? {
  738. ...(data && typeof data === 'object' ? data : {}),
  739. type: 'lepao_success',
  740. umo: user.bot_umo,
  741. total_num: totalForNotice,
  742. target_count: targetCount,
  743. name: user.name,
  744. update_type: user.update_type,
  745. account,
  746. traceId
  747. } : {
  748. type: 'lepao_fail',
  749. umo: user.bot_umo,
  750. name: user.name,
  751. update_type: user.update_type,
  752. account,
  753. reason,
  754. traceId
  755. }
  756. const afterSuccessNotify = async () => {
  757. if (success) {
  758. await this.handleLepaoTargetComplete(account, user, totalForNotice, traceId)
  759. }
  760. }
  761. if (noticeType === 'bot' && user.bot_umo) {
  762. const ch = await mq.getChannel(this.noticeQueue)
  763. await ch.assertQueue(this.noticeQueue, { durable: true })
  764. ch.sendToQueue(
  765. this.noticeQueue,
  766. Buffer.from(JSON.stringify(payload)),
  767. {
  768. persistent: true,
  769. contentType: 'application/json'
  770. }
  771. )
  772. await afterSuccessNotify()
  773. return { delivered: true, via: 'bot' }
  774. }
  775. if (noticeType === 'email' && user.email) {
  776. if (success) {
  777. await EmailTemplate.lepaoSuccess(user.email, payload)
  778. await afterSuccessNotify()
  779. return { delivered: true, via: 'email' }
  780. }
  781. await EmailTemplate.lepaoFail(user.email, {
  782. name: user.name,
  783. account,
  784. reason: reason || '系统繁忙,请联系客服或稍后再试',
  785. traceId
  786. })
  787. return { delivered: true, via: 'email' }
  788. }
  789. await afterSuccessNotify()
  790. return { delivered: false, via: 'none' }
  791. })
  792. /* ---------------- 扣减次数 ---------------- */
  793. this.register('lepao.consumeCount', async (req, ctx) => {
  794. const account = req?.account
  795. const uuid = req?.uuid
  796. if (!uuid) {
  797. throw new Error('扣减乐跑次数失败:缺少 uuid')
  798. }
  799. // 幂等:同一 MQ taskId 全程(含多次重试投递)只扣一次;终局失败再一次性返还
  800. const consumeKey = `lepao:consume:${ctx?.taskId || ctx?.traceId || account || uuid}`
  801. const existed = await Redis.get(consumeKey)
  802. if (existed) {
  803. return true
  804. }
  805. this.logger.info(`${account || uuid}开始扣减乐跑次数`)
  806. const conn = await db.connect()
  807. try {
  808. await conn.beginTransaction()
  809. const [userRows] = await conn.execute(
  810. 'SELECT lepao_count FROM users WHERE uuid = ? FOR UPDATE',
  811. [uuid]
  812. )
  813. if (!userRows || userRows.length !== 1) {
  814. await conn.rollback()
  815. throw new Error('扣减乐跑次数失败:用户不存在')
  816. }
  817. const beforeCount = Number(userRows[0].lepao_count || 0)
  818. if (beforeCount < 1) {
  819. await conn.rollback()
  820. throw new Error('用户乐跑次数不足,请购买乐跑次数后重试!')
  821. }
  822. const [r] = await conn.execute(
  823. 'UPDATE users SET lepao_count = lepao_count - 1 WHERE uuid = ?',
  824. [uuid]
  825. )
  826. if (!r || r.affectedRows !== 1) {
  827. await conn.rollback()
  828. throw new Error('扣减乐跑次数失败:数据库更新失败')
  829. }
  830. await insertLedgerRecord({
  831. executor: conn,
  832. userUuid: uuid,
  833. delta: -1,
  834. balanceBefore: beforeCount,
  835. balanceAfter: beforeCount - 1,
  836. bizType: 'run_consume',
  837. bizId: consumeKey,
  838. remark: `${account || uuid}乐跑扣除`
  839. })
  840. await conn.commit()
  841. } catch (error) {
  842. try { await conn.rollback() } catch (_) { }
  843. throw error
  844. } finally {
  845. if (conn?.connection && typeof conn.connection.release === 'function' && typeof conn?.release === 'function') {
  846. conn.release()
  847. }
  848. }
  849. this.logger.info(`${account || uuid}扣减乐跑次数完成`)
  850. await Redis.set(consumeKey, '1', { EX: 3600 })
  851. return true
  852. })
  853. /* ---------------- 返还次数(整次任务所有 MQ 重试耗尽后失败时执行) ---------------- */
  854. this.register('lepao.refundCount', async (req, ctx) => {
  855. const account = req?.account
  856. const uuid = req?.uuid
  857. if (!uuid) {
  858. return true
  859. }
  860. const baseKey = `${ctx?.taskId || ctx?.traceId || account || uuid}`
  861. const consumeKey = `lepao:consume:${baseKey}`
  862. const refundKey = `lepao:refund:${baseKey}`
  863. const consumed = await Redis.get(consumeKey)
  864. if (!consumed) {
  865. return true
  866. }
  867. const refunded = await Redis.get(refundKey)
  868. if (refunded) {
  869. return true
  870. }
  871. this.logger.info(`${account || uuid}开始返还乐跑次数`)
  872. const conn = await db.connect()
  873. try {
  874. await conn.beginTransaction()
  875. const [userRows] = await conn.execute(
  876. 'SELECT lepao_count FROM users WHERE uuid = ? FOR UPDATE',
  877. [uuid]
  878. )
  879. if (!userRows || userRows.length !== 1) {
  880. await conn.rollback()
  881. throw new Error('返还乐跑次数失败:用户不存在')
  882. }
  883. const beforeCount = Number(userRows[0].lepao_count || 0)
  884. const [r] = await conn.execute(
  885. 'UPDATE users SET lepao_count = lepao_count + 1 WHERE uuid = ?',
  886. [uuid]
  887. )
  888. if (!r || r.affectedRows !== 1) {
  889. await conn.rollback()
  890. throw new Error('返还乐跑次数失败:数据库更新失败')
  891. }
  892. await insertLedgerRecord({
  893. executor: conn,
  894. userUuid: uuid,
  895. delta: 1,
  896. balanceBefore: beforeCount,
  897. balanceAfter: beforeCount + 1,
  898. bizType: 'run_refund',
  899. bizId: refundKey,
  900. remark: `${account || uuid}乐跑失败返还`
  901. })
  902. await conn.commit()
  903. } catch (error) {
  904. try { await conn.rollback() } catch (_) { }
  905. throw error
  906. } finally {
  907. if (conn?.connection && typeof conn.connection.release === 'function' && typeof conn?.release === 'function') {
  908. conn.release()
  909. }
  910. }
  911. this.logger.info(`${account || uuid}返还乐跑次数完成`)
  912. await Redis.set(refundKey, '1', { EX: 3600 })
  913. return true
  914. })
  915. this.register('lepao.getUserData', async (req, ctx) => {
  916. const account = req.account
  917. this.logger.info(`${account}开始获取用户数据`)
  918. const accountSql = `
  919. SELECT
  920. u.uuid,
  921. u.lepao_count,
  922. l.create_user,
  923. l.name,
  924. l.student_num,
  925. l.area,
  926. l.sex,
  927. l.state,
  928. l.token,
  929. l.uid,
  930. l.school_id,
  931. l.userAgent,
  932. l.deviceModel,
  933. l.notice_type,
  934. l.email,
  935. e.bot_account
  936. FROM
  937. lepao_account l
  938. LEFT JOIN
  939. users u
  940. ON
  941. l.create_user = u.uuid
  942. LEFT JOIN
  943. lepao_extra e
  944. ON
  945. l.student_num = e.student_num
  946. WHERE
  947. l.student_num = ?
  948. `
  949. const rows = await db.query(accountSql, [account])
  950. if (!rows || rows.length === 0) {
  951. this.logger.error(`${account}无法获取账号数据`)
  952. throw new Error('无法获取账号数据,请联系客服或稍后再试')
  953. }
  954. let userData = rows[0]
  955. if (!userData.create_user || !userData.uuid) {
  956. this.logger.warn(`${account}账号状态异常`)
  957. throw new Error('当前账号状态异常,请联系客服')
  958. }
  959. if (userData.state !== 1) {
  960. this.logger.warn(`${account}登录状态异常 state=${userData.state}`)
  961. throw new Error('乐跑账号登录已过期,请尝试使用登录器重新登录')
  962. }
  963. if (userData.lepao_count < 1) {
  964. this.logger.warn(`${account}乐跑次数不足`)
  965. throw new Error('用户乐跑次数不足,请购买乐跑次数后重试!')
  966. }
  967. if (!userData.userAgent)
  968. 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'
  969. if (!userData.deviceModel)
  970. userData.deviceModel = '2211133C'
  971. return userData
  972. })
  973. this.register('lepao.getPath', async (req, ctx) => {
  974. const account = req.account
  975. this.logger.info(`${account}开始获取路径`)
  976. const accountSql = 'SELECT area, sex FROM lepao_account WHERE student_num = ?'
  977. const rows = await db.query(accountSql, [account])
  978. if (!rows || rows.length === 0) {
  979. this.logger.error(`${account}无法获取账号数据`)
  980. throw new Error('无法获取账号数据')
  981. }
  982. const { area, sex } = rows[0]
  983. let max = 4.00
  984. let min = 2.00
  985. if (sex === 2) {
  986. max = 2.00
  987. min = 1.60
  988. }
  989. this.logger.info(`${account}路径参数: area=${area ?? '随机'}, max_distance=${max}, min_distance=${min}`)
  990. let pathSql = 'SELECT * FROM path_data WHERE state = 1 AND distance < ? AND distance > ? '
  991. const pathParams = [max, min]
  992. if (area) {
  993. pathSql += ' AND run_zone_name = ?'
  994. pathParams.push(area)
  995. }
  996. pathSql += ' ORDER BY count ASC LIMIT 1'
  997. const paths = await db.query(pathSql, pathParams)
  998. if (!paths || paths.length === 0) {
  999. this.logger.error(`${account}未找到符合条件的路线`)
  1000. const err = new Error('未找到符合条件的路线,请改变路径选择条件')
  1001. err.code = 'PATH_SELECT_FAILED'
  1002. err.retryable = true
  1003. throw err
  1004. }
  1005. const randomPath = paths[0]
  1006. const updateSql = 'UPDATE path_data SET count = count + 1 WHERE id = ?'
  1007. await db.query(updateSql, [randomPath.id])
  1008. this.logger.info(`${account}路径选中id=${randomPath.id},计数加1成功`)
  1009. return { pathData: randomPath }
  1010. })
  1011. /* ---------------- 获取跑步记录 ---------------- */
  1012. this.register('lepao.getRecord', async (req, ctx) => {
  1013. return this.request(
  1014. ctx.traceId,
  1015. 'getRecord',
  1016. this.api('/Run2/beforeRunV260'),
  1017. () => {
  1018. const now = this.lepaoTimestamp()
  1019. const raw = {
  1020. uid: req.uid,
  1021. token: req.token,
  1022. school_id: req.school_id,
  1023. term_id: 0,
  1024. course_id: 0,
  1025. class_id: 0,
  1026. student_num: req.student_id,
  1027. card_id: req.student_id,
  1028. timestamp: now,
  1029. version: 1,
  1030. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1031. ostype: 5
  1032. }
  1033. raw.sign = dataSign(raw)
  1034. return raw
  1035. },
  1036. {
  1037. 'User-Agent': req.userAgent,
  1038. 'charset': 'utf-8',
  1039. 'Referer': 'https://servicewechat.com/wxf94c4ddb63d87ede/32/page-frame.html',
  1040. },
  1041. ctx
  1042. )
  1043. })
  1044. /* ---------------- 切换跑区 ---------------- */
  1045. this.register('lepao.setZone', async (req, ctx) => {
  1046. const runZoneMap = {
  1047. '兰花湖校区跑区': 2,
  1048. '主校区北跑区': 3,
  1049. '主校区南跑区': 5,
  1050. '重庆工商大学茶园校区': 6
  1051. }
  1052. const { pathData } = req
  1053. const runZoneId = runZoneMap[pathData.run_zone_name]
  1054. if (!runZoneId) throw new Error('跑区不存在')
  1055. await this.request(
  1056. ctx.traceId,
  1057. 'setZone',
  1058. this.api('/Run/setRunZone'),
  1059. () => {
  1060. const raw = {
  1061. uid: req.uid,
  1062. token: req.token,
  1063. school_id: req.school_id,
  1064. term_id: 0,
  1065. course_id: 0,
  1066. class_id: 0,
  1067. student_num: req.student_id,
  1068. card_id: req.student_id,
  1069. timestamp: this.lepaoTimestamp(),
  1070. version: 1,
  1071. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1072. ostype: 5,
  1073. run_zone_id: String(runZoneId)
  1074. }
  1075. raw.sign = dataSign(raw)
  1076. return raw
  1077. },
  1078. {},
  1079. ctx
  1080. )
  1081. return { run_zone_id: runZoneId }
  1082. })
  1083. /* ---------------- 获取 OSS STS ---------------- */
  1084. this.register('lepao.getOssSts', async (req, ctx) => {
  1085. const res = await this.request(
  1086. ctx.traceId,
  1087. 'getOssSts',
  1088. this.api('/WpIndex/getOssSts'),
  1089. () => {
  1090. const raw = {
  1091. uid: req.uid,
  1092. token: req.token,
  1093. school_id: req.school_id,
  1094. term_id: 0,
  1095. course_id: 0,
  1096. class_id: 0,
  1097. student_num: req.student_id,
  1098. card_id: req.student_id,
  1099. timestamp: this.lepaoTimestamp(),
  1100. version: 1,
  1101. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1102. ostype: 5
  1103. }
  1104. raw.sign = dataSign(raw)
  1105. return raw
  1106. },
  1107. {},
  1108. ctx
  1109. )
  1110. return res.data
  1111. })
  1112. /* ---------------- 上传 OSS 文件 ---------------- */
  1113. this.register('lepao.uploadOssFile', async (req, ctx) => {
  1114. const { account, pathData, newPathData, ossSts: sts } = req
  1115. // 处理跑步路径
  1116. const pathResult = dataEncrypt(JSON.stringify(newPathData))
  1117. // 获取跑步规则参数
  1118. const runRule = await this.handlers['lepao.getRecord'](req, ctx)
  1119. const ruleData = runRule?.data
  1120. if (!ruleData?.run_line_info?.point_list || !ruleData?.time_rule_arr?.length) {
  1121. const err = new Error('获取打卡点规则失败')
  1122. err.code = 'CHECKPOINT_FETCH_FAILED'
  1123. err.retryable = true
  1124. throw err
  1125. }
  1126. const check_points = ruleData.run_line_info.point_list
  1127. let min_log_num = ruleData.time_rule_arr[0]?.min_log_num || 4
  1128. const point_update_distance = parseFloat(ruleData.run_line_info.point_update_distance || 0) * 1000
  1129. const log_max_distance = Number(ruleData.run_line_info.log_max_distance || 0)
  1130. // 生成打卡点
  1131. const point_data = selectCheckpoints(newPathData, check_points, min_log_num, point_update_distance, log_max_distance, req.run_end_time, pathData.time)
  1132. if (!point_data) {
  1133. this.logger.warn(`[RETRY] 打卡点数量不足,重新更换路径`)
  1134. const err = new Error('打卡点数量不足')
  1135. err.code = 'CHECKPOINT_INSUFFICIENT'
  1136. err.retryable = true
  1137. throw err
  1138. }
  1139. const now = new Date()
  1140. let day = now.getDay()
  1141. if (day === 0) day = 7
  1142. // 判断当天是否有成功记录
  1143. if(!ruleData?.weekData?.list || ruleData?.weekData?.list?.length !== 7) {
  1144. const err = new Error('获取当天跑步记录失败,请联系客服或稍后再试')
  1145. err.code = 'DAILY_RECORD_FETCH_FAILED'
  1146. err.retryable = false
  1147. throw err
  1148. }
  1149. const weekData = ruleData?.weekData?.list[day - 1]
  1150. if (!weekData) {
  1151. const err = new Error('获取当天跑步记录失败,请联系客服或稍后再试')
  1152. err.code = 'DAILY_RECORD_FETCH_FAILED'
  1153. err.retryable = false
  1154. throw err
  1155. }
  1156. if(Number(weekData?.distance) > 1.6) {
  1157. this.logger.warn(`${account}当天已存在成功跑步记录,距离:${weekData?.distance}km,请勿重复跑步`)
  1158. await this.writeSuccessRedis(account)
  1159. const err = new Error('当天已存在成功跑步记录,请勿重复跑步')
  1160. err.code = 'DAILY_ALREADY_COMPLETED'
  1161. err.retryable = false
  1162. throw err
  1163. }
  1164. const yyyy = now.getFullYear()
  1165. const mm = String(now.getMonth() + 1).padStart(2, '0')
  1166. const dd = String(now.getDate()).padStart(2, '0')
  1167. const formattedToday = `${yyyy}-${mm}-${dd}`
  1168. const boundary = String(Date.now())
  1169. const timestamp = String(Date.now())
  1170. const ossPath = `Public/Upload/file/run_record/${boundary.slice(-3)}/${formattedToday}/${timestamp}-${Math.floor(Math.random() * 150)}.txt`
  1171. await this.putOssWithFallback(sts, ossPath, Buffer.from(pathResult, 'utf-8'))
  1172. return { oss_path: ossPath, point_data: point_data }
  1173. })
  1174. this.register('lepao.uploadGyrOssFile', async (req, ctx) => {
  1175. const { newPathData, ossSts: sts, record_id } = req
  1176. // 生成加速度数据
  1177. const gyrData = generateGyrFromPath(newPathData)
  1178. if (!Array.isArray(gyrData) || gyrData.length === 0) {
  1179. this.logger.error('生成加速度数据失败')
  1180. return { status: 0, info: '生成加速度数据失败' }
  1181. }
  1182. const now = new Date()
  1183. const yyyy = now.getFullYear()
  1184. const mm = String(now.getMonth() + 1).padStart(2, '0')
  1185. const dd = String(now.getDate()).padStart(2, '0')
  1186. const formattedToday = `${yyyy}-${mm}-${dd}`
  1187. const boundary = String(Date.now())
  1188. const timestamp = String(Date.now())
  1189. const ossPath = `Public/Upload/file/run_gyroscope/${boundary.slice(-3)}/${formattedToday}/${timestamp}-${Math.floor(Math.random() * 150)}.txt`
  1190. await this.putOssWithFallback(sts, ossPath, Buffer.from(JSON.stringify(gyrData), 'utf-8'))
  1191. return this.request(
  1192. ctx.traceId,
  1193. 'bindData',
  1194. this.api('/Run2/gyroscope'),
  1195. () => {
  1196. const data = {
  1197. uid: req.uid,
  1198. token: req.token,
  1199. school_id: req.school_id,
  1200. term_id: 0,
  1201. course_id: 0,
  1202. class_id: 0,
  1203. student_num: req.student_id,
  1204. card_id: req.student_id,
  1205. timestamp: this.lepaoTimestamp(),
  1206. version: 1,
  1207. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1208. ostype: 5,
  1209. record_id: record_id,
  1210. gyroscope_file: ossPath
  1211. }
  1212. data.sign = dataSign(data)
  1213. return data
  1214. },
  1215. {},
  1216. ctx
  1217. )
  1218. })
  1219. /* ---------------- 提交跑步数据 ---------------- */
  1220. this.register('lepao.bindData', async (req, ctx) => {
  1221. const { pathData } = req
  1222. const distance = Number(Number(pathData.distance || 0).toFixed(2))
  1223. const stepData = generateCadence(distance, pathData.time)
  1224. const stepInfo = JSON.stringify({ interval: 60, list: stepData.cadence_list })
  1225. let points = req.point_data.map(({ address, jingwei, ...rest }) => rest)
  1226. points = JSON.stringify(points)
  1227. return this.request(
  1228. ctx.traceId,
  1229. 'bindData',
  1230. this.api('/Run/stopRunV278'),
  1231. () => {
  1232. const data = {
  1233. uid: req.uid,
  1234. token: req.token,
  1235. school_id: req.school_id,
  1236. term_id: 1,
  1237. course_id: 0,
  1238. class_id: 0,
  1239. student_num: req.student_id,
  1240. card_id: req.student_id,
  1241. timestamp: this.lepaoTimestamp(),
  1242. version: 1,
  1243. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1244. ostype: 5,
  1245. game_id: String(req.run_zone_id || 0),
  1246. start_time: req.run_end_time - Number(pathData.time),
  1247. end_time: req.run_end_time,
  1248. distance,
  1249. record_img: "",
  1250. log_data: points,
  1251. file_img: "",
  1252. is_running_area_valid: 1,
  1253. mobileDeviceId: 1,
  1254. mobileModel: req.deviceModel,
  1255. step_info: stepInfo,
  1256. step_num: stepData.total_steps,
  1257. used_time: pathData.time,
  1258. mobileOsVersion: 1,
  1259. record_file: req.record_file
  1260. }
  1261. data.sign = dataSign(data)
  1262. return data
  1263. },
  1264. {},
  1265. ctx
  1266. )
  1267. })
  1268. }
  1269. /* ================= Worker核心 ================= */
  1270. async start() {
  1271. if (this.running) return
  1272. this.running = true
  1273. this.logger.info('Worker 启动中...')
  1274. try {
  1275. this.initHandlers()
  1276. const channel = await mq.getChannel(this.channelName)
  1277. await channel.prefetch(5)
  1278. await assertRunforgeTaskIngress(channel, this.logger)
  1279. await channel.assertQueue(this.resultQueue, {
  1280. durable: true,
  1281. arguments: {
  1282. 'x-max-length': this.maxQueueLength
  1283. }
  1284. })
  1285. await channel.assertQueue(this.deadQueue, {
  1286. durable: true,
  1287. arguments: {
  1288. 'x-max-length': this.maxQueueLength
  1289. }
  1290. })
  1291. await channel.consume(this.taskQueue, async (msg) => {
  1292. if (!msg) return
  1293. let content
  1294. try {
  1295. content = JSON.parse(msg.content.toString())
  1296. } catch {
  1297. return channel.ack(msg)
  1298. }
  1299. const { id, type, data, retry = 0 } = content
  1300. const traceId = this.traceId()
  1301. const handler = this.handlers[type]
  1302. if (!handler) {
  1303. this.log(traceId, 'ERROR', '未知任务', { type })
  1304. return channel.ack(msg)
  1305. }
  1306. try {
  1307. const proxyEnabled = await QgProxyManager.isOutboundProxyEnabled()
  1308. const outboundMode = proxyEnabled ? 'proxy' : 'direct'
  1309. const result = await this.withTimeout(
  1310. handler(data, {
  1311. traceId,
  1312. channel,
  1313. taskId: id,
  1314. outboundMode,
  1315. retry,
  1316. maxRetry: this.maxRetry
  1317. }),
  1318. type,
  1319. this.taskTimeoutMs,
  1320. { code: 'TASK_TIMEOUT', retryable: true }
  1321. )
  1322. await this.sendResult(channel, {
  1323. id,
  1324. success: true,
  1325. result
  1326. })
  1327. this.log(traceId, 'DONE', `任务完成 ${type}`)
  1328. channel.ack(msg)
  1329. } catch (err) {
  1330. this.logErr(traceId, `任务失败 ${type}`, err)
  1331. if (retry < this.maxRetry && this.isRetryableTaskError(err)) {
  1332. // 重试
  1333. await channel.sendToQueue(
  1334. this.taskQueue,
  1335. Buffer.from(JSON.stringify({
  1336. ...content,
  1337. retry: retry + 1
  1338. })),
  1339. { persistent: true }
  1340. )
  1341. this.log(traceId, 'RETRY', `重试第${retry + 1}次`)
  1342. } else {
  1343. // 死信
  1344. await channel.sendToQueue(
  1345. this.deadQueue,
  1346. Buffer.from(JSON.stringify(content)),
  1347. { persistent: true }
  1348. )
  1349. this.log(traceId, 'DEAD', '进入死信队列')
  1350. }
  1351. await this.sendResult(channel, {
  1352. id,
  1353. success: false,
  1354. error: err.code === 'TASK_TIMEOUT' ? '系统繁忙,请稍后再试' : this.maskClientReason(err.message)
  1355. })
  1356. channel.ack(msg)
  1357. }
  1358. })
  1359. this.logger.info('RunForge Worker 启动成功')
  1360. } catch (err) {
  1361. this.logger.error('RunForge Worker 启动失败: ' + err.stack)
  1362. }
  1363. }
  1364. async sendResult(channel, data) {
  1365. channel.sendToQueue(
  1366. this.resultQueue,
  1367. Buffer.from(JSON.stringify(data)),
  1368. { persistent: true }
  1369. )
  1370. }
  1371. async stop() {
  1372. this.running = false
  1373. await mq.close()
  1374. this.logger.info('RunForge Worker 已停止')
  1375. }
  1376. }
  1377. module.exports = Worker