Worker.js 57 KB

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