Worker.js 56 KB

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