Worker.js 47 KB

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