Worker.js 58 KB

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