Worker.js 53 KB

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