Worker.js 57 KB

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