Worker.js 61 KB

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