Worker.js 56 KB

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