Worker.js 56 KB

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