Lepao.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. const axios = require('axios')
  2. const Redis = require('../../plugin/DataBase/Redis')
  3. const db = require('../../plugin/DataBase/db')
  4. const Logger = require('../Logger')
  5. const path = require('path')
  6. const EmailTemplate = require('../../plugin/Email/emailTemplate')
  7. const config = require('../../config.json')
  8. const mq = require('../../plugin/mq')
  9. class Lepao {
  10. constructor() {
  11. this.logger = new Logger(path.join(__dirname, '../logs/Lepao.log'), 'INFO')
  12. this.runpy = config.runpy
  13. this.messageQueue = 'runforge_message_queue'
  14. }
  15. async getPath(account, vip) {
  16. this.logger.info(`${account}开始获取路径`)
  17. const accountSql = 'SELECT area, sex FROM lepao_account WHERE student_num = ?'
  18. const rows = await db.query(accountSql, [account])
  19. if (!rows || rows.length === 0) {
  20. this.logger.error(`${account}无法获取账号数据`)
  21. throw new Error('无法获取账号数据')
  22. }
  23. const { area, sex } = rows[0]
  24. let max = 4.00
  25. let min = 2.00
  26. if (sex === 2) {
  27. max = 2.00
  28. min = 1.60
  29. }
  30. this.logger.info(`${account}路径参数: area=${area ?? '随机'}, max_distance=${max}, min_distance=${min}`)
  31. let pathSql = 'SELECT id FROM path_data WHERE state = 1 AND distance < ? AND distance > ? '
  32. const pathParams = [max, min]
  33. if (area) {
  34. pathSql += ' AND run_zone_name = ?'
  35. pathParams.push(area)
  36. }
  37. pathSql += ' ORDER BY count ASC LIMIT 1'
  38. const paths = await db.query(pathSql, pathParams)
  39. if (!paths || paths.length === 0) {
  40. this.logger.error(`${account}未找到符合条件的路线`)
  41. throw new Error('未找到符合条件的路线,请改变路径选择条件')
  42. }
  43. const randomPath = paths[0]
  44. const updateSql = 'UPDATE path_data SET count = count + 1 WHERE id = ?'
  45. await db.query(updateSql, [randomPath.id])
  46. this.logger.info(`${account}路径选中id=${randomPath.id},计数加1成功`)
  47. return randomPath.id
  48. }
  49. async getRecord(uid, token, school_id, student_id, userAgent) {
  50. try {
  51. const reqData = { uid, token, school_id, student_id, userAgent }
  52. this.logger.info(`开始请求获取跑步次数 uid=${uid} student_id=${student_id}`)
  53. const recordUrl = this.runpy + '/get_record'
  54. let recordRes = await axios.post(recordUrl, reqData)
  55. const { data } = recordRes
  56. this.logger.info(`获取跑步次数返回结果: ${JSON.stringify(data)}`)
  57. if (!data || data.status !== 1 || !data.data) {
  58. this.logger.warn('获取剩余跑步次数失败,接口返回异常')
  59. return
  60. }
  61. return data.data
  62. } catch (error) {
  63. this.logger.error(`获取跑步次数失败: ${error.stack || error.message}`)
  64. return
  65. }
  66. }
  67. async writeRedis(account) {
  68. try {
  69. // 计算至明日0时过期的秒数
  70. const now = new Date()
  71. const tomorrow = new Date().setHours(24, 0, 0, 0)
  72. const exp = Math.floor((tomorrow - now) / 1000)
  73. await Redis.set(`lepaoSuccess:${account}`, account, {
  74. EX: exp
  75. })
  76. } catch (error) {
  77. this.logger.error(`redis缓存乐跑记录失败: ${error.stack || '未知错误'}`)
  78. }
  79. }
  80. async beginLepao(uuid, account, token, uid, school_id, state) {
  81. try {
  82. this.logger.info(`${account}开始执行乐跑流程`)
  83. // 检查redis是否存在当天乐跑成功记录
  84. const isSuccess = await Redis.get(`lepaoSuccess:${account}`)
  85. if (isSuccess)
  86. throw new Error('该账号当天已存在成功乐跑记录')
  87. const isProgress = await Redis.get(`lepaoProgress:${account}`)
  88. if (isProgress)
  89. throw new Error('该账号已进入乐跑任务队列,请等待乐跑完成后再进行乐跑操作')
  90. //已开始乐跑,存入Redis
  91. await Redis.set(`lepaoProgress:${account}`, account, {
  92. EX: 120
  93. })
  94. const userPermissionSql = 'SELECT vip, lepao_count FROM users WHERE uuid = ?'
  95. const userPermissionData = await db.query(userPermissionSql, [uuid])
  96. if (!userPermissionData || userPermissionData.length !== 1) {
  97. this.logger.error(`${account}无法获取用户信息`)
  98. throw new Error('无法获取用户信息,请重试或联系RunForge客服')
  99. }
  100. if (userPermissionData[0].lepao_count < 1) {
  101. this.logger.warn(`${account}乐跑次数不足`)
  102. throw new Error('用户乐跑次数不足,请购买乐跑套餐!')
  103. }
  104. if (state !== 1) {
  105. this.logger.warn(`${account}登录状态异常 state=${state}`)
  106. return this.sendFailEmail(account, '乐跑账号登录已过期,请尝试使用登录器重新登录')
  107. }
  108. // 获取路径 ID
  109. const path_id = await this.getPath(account, userPermissionData[0].vip)
  110. // 更换跑区
  111. this.logger.info(`${account}开始更换跑区,path_id=${path_id}`)
  112. const zoneUrl = this.runpy + '/set_zone'
  113. // 晚上10点后提前
  114. let run_end_time = Math.floor(Date.now() / 1000) - 300 // 提前5分钟
  115. let hour = new Date().getHours()
  116. if (hour < 7)
  117. throw new Error('当前不在有效乐跑时间范围内。RunForge支持乐跑时间段为7:00~24:00')
  118. if (hour >= 22) {
  119. this.logger.info(`${account}当前时间为${hour}点,调整run_end_time提前5小时`)
  120. run_end_time -= 18000
  121. }
  122. let phoneSql = 'SELECT userAgent, deviceModel FROM lepao_account WHERE student_num = ?'
  123. let phoneData = await db.query(phoneSql, [account])
  124. let userAgent = (phoneData && phoneData.length > 0 && phoneData[0].userAgent) ? phoneData[0].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/5G Language/zh_CN ABI/arm64'
  125. let deviceModel = (phoneData && phoneData.length > 0 && phoneData[0].deviceModel) ? phoneData[0].deviceModel : '2211133C'
  126. const ossData = { uid, token, school_id, student_id: account, random_id: path_id, run_end_time, userAgent }
  127. try {
  128. const zoneRes = await axios.post(zoneUrl, ossData)
  129. const { data } = zoneRes
  130. this.logger.info(`${account}更换跑区返回结果: ${JSON.stringify(data)}`)
  131. if (!data || data.status !== 1 || !data.data) {
  132. // 10.17更新,只有明确说明登录失效才会更新状态
  133. if (data && data.info && data.info.includes('请重新登录'))
  134. this.setStatusFail(account)
  135. throw new Error(data?.info || '系统繁忙,请联系客服或稍后再试')
  136. }
  137. } catch (error) {
  138. this.logger.error(`${account}更换跑区失败: ${error.stack || error.message}`)
  139. throw error
  140. }
  141. // 临时修复3.12~3.18期间未入库记录,后续可删除
  142. // await this.fixRecords(uuid, ossData)
  143. // 上传 OSS
  144. this.logger.info(`${account}开始上传OSS记录`)
  145. const ossUrl = this.runpy + '/upload_oss_file'
  146. let oss_path, point_data
  147. try {
  148. const ossRes = await axios.post(ossUrl, ossData, {
  149. proxy: false
  150. })
  151. const { data } = ossRes
  152. this.logger.info(`${account}上传OSS记录返回结果: ${JSON.stringify(data)}`)
  153. if (!data || data.code !== 200 || !data.oss_path || !data.point_data) {
  154. if (data.code == -200) {
  155. this.logger.info(`${account}分配打卡点数量不足,重新执行乐跑流程`)
  156. return this.beginLepao(uuid, account, token, uid, school_id, state)
  157. }
  158. throw new Error('系统繁忙,请联系客服或稍后再试')
  159. }
  160. oss_path = data.oss_path
  161. point_data = data.point_data
  162. this.logger.info(`${account}上传OSS记录成功!oss_path:${oss_path}`)
  163. } catch (error) {
  164. // this.setStatusFail(account)
  165. this.logger.error(`${account}上传OSS记录失败,请检查登录是否过期。${error.stack || error.message}`)
  166. throw new Error('系统繁忙,请联系客服或稍后再试')
  167. }
  168. // 扣除乐跑次数
  169. this.logger.info(`${account}开始扣减乐跑次数`)
  170. const useLepaoCountSql = 'UPDATE users SET lepao_count = lepao_count - 1 WHERE uuid = ?'
  171. await db.query(useLepaoCountSql, [uuid])
  172. this.logger.info(`${account}扣减乐跑次数完成`)
  173. const lepaoData = {
  174. uid,
  175. token,
  176. school_id,
  177. student_id: account,
  178. random_id: path_id,
  179. record_file: oss_path,
  180. run_end_time,
  181. point_data,
  182. userAgent,
  183. deviceModel
  184. }
  185. this.logger.info(`${account}乐跑请求参数构造完成:`)
  186. this.logger.info(JSON.stringify(lepaoData))
  187. // 绑定乐跑数据
  188. this.logger.info(`${account}开始绑定乐跑数据`)
  189. const lepaoUrl = this.runpy + '/bind_data'
  190. try {
  191. const lepaoRes = await axios.post(lepaoUrl, lepaoData)
  192. const { data } = lepaoRes
  193. this.logger.info(`${account}绑定乐跑数据返回结果: ${JSON.stringify(data)}`)
  194. if (!data || data.status !== 1 || !data.data) {
  195. // 10.17更新,只有明确说明登录失效才会更新状态
  196. if (data && data.info && data.info.includes('请重新登录'))
  197. this.setStatusFail(account)
  198. throw new Error(data?.info || '系统繁忙,请联系客服或稍后再试')
  199. }
  200. await this.addRecord(uuid, account, data.data, path_id, point_data)
  201. // 获取剩余跑步次数
  202. const recordData = await this.getRecord(uid, token, school_id, account, userAgent)
  203. this.logger.info(`${account}获取剩余跑步次数结果: ${JSON.stringify(recordData)}`)
  204. let term_num = recordData?.term_num || 0
  205. let total_num = recordData?.total_num || 30
  206. if (data.data.record_failed_reason === '自动确认有效' || data.data.record_failed_reason === '') {
  207. // 成功记录存入Redis
  208. await this.writeRedis(account)
  209. await this.sendSuccessEmail(account, data.data, term_num, total_num)
  210. } else {
  211. this.logger.warn(`${account}乐跑失败,原因: ${data.data.record_failed_reason}`)
  212. // 已存在记录也存redis
  213. if (data.data.record_failed_reason === '当天关联成绩次数已达到上限')
  214. await this.writeRedis(account)
  215. await this.sendFailEmail(account, data.data.record_failed_reason)
  216. await this.lepaoFail(uuid)
  217. }
  218. let recordSql = 'UPDATE lepao_account SET term_num = ?, total_num = ? WHERE student_num = ?'
  219. let recordRows = await db.query(recordSql, [term_num, total_num, account])
  220. if (!recordRows || recordRows.affectedRows !== 1)
  221. this.logger.warn(`${account}更新乐跑次数失败`)
  222. else
  223. this.logger.info(`${account}更新乐跑次数成功 term_num=${term_num}, total_num=${total_num}`)
  224. } catch (error) {
  225. this.logger.error(`${account}绑定乐跑数据失败: ${error.stack || error.message}`)
  226. await this.lepaoFail(uuid)
  227. throw error
  228. }
  229. } catch (error) {
  230. this.logger.error(`${account}乐跑流程异常: ${error.stack || error.message}`)
  231. await this.sendFailEmail(account, error.message || '系统繁忙,请联系客服或稍后再试')
  232. } finally {
  233. await Redis.del(`lepaoProgress:${account}`)
  234. }
  235. }
  236. async addRecord(uuid, account, result, path_id, point_data) {
  237. try {
  238. const time = Date.now()
  239. this.logger.info(`${account}添加乐跑记录,path_id=${path_id}`)
  240. const sql = 'INSERT INTO lepao_record (uuid, time, lepao_account, result, path_id, point_data) VALUES (?, ?, ?, ?, ?, ?)'
  241. await db.query(sql, [uuid, time, account, result, path_id, point_data])
  242. this.logger.info(`${account}添加乐跑记录成功`)
  243. } catch (error) {
  244. this.logger.error(`添加乐跑记录失败: ${error.stack || error.message}`)
  245. }
  246. }
  247. async sendSuccessEmail(account, lepaoData, term_num, total_num) {
  248. try {
  249. this.logger.info(`${account}发送乐跑成功邮件`)
  250. const emailSql = `
  251. SELECT
  252. a.name,
  253. a.email,
  254. a.target_count,
  255. a.notice_type,
  256. e.bot_umo
  257. FROM
  258. lepao_account a
  259. LEFT JOIN
  260. lepao_extra e
  261. ON
  262. a.student_num = e.student_num
  263. WHERE
  264. a.student_num = ?
  265. `
  266. const rows = await db.query(emailSql, [account])
  267. if (!rows || rows.length === 0) {
  268. this.logger.error(`${account}查找用户信息失败`)
  269. throw new Error('查找用户信息失败')
  270. }
  271. let data = {
  272. ...lepaoData,
  273. type: 'lepao_success',
  274. umo: rows[0].bot_umo,
  275. term_num: rows[0].target_count,
  276. total_num,
  277. name: rows[0].name,
  278. account
  279. }
  280. if (rows[0].notice_type === 'bot' && rows[0].bot_umo) {
  281. this.logger.info(`${account}发送乐跑成功Bot通知,UMO=${rows[0].bot_umo}`)
  282. const ch = await mq.getChannel(this.messageQueue)
  283. await ch.assertQueue(this.messageQueue, {
  284. durable: true
  285. })
  286. ch.sendToQueue(
  287. this.messageQueue,
  288. Buffer.from(JSON.stringify(data)),
  289. {
  290. persistent: true,
  291. contentType: 'application/json'
  292. }
  293. )
  294. this.logger.info(`${account}乐跑成功Bot通知发送完成`)
  295. } else if (rows[0].notice_type === 'email' && rows[0].email) {
  296. await EmailTemplate.lepaoSuccess(rows[0].email, data)
  297. this.logger.info(`${account}乐跑成功邮件发送完成`)
  298. }
  299. if (rows[0].target_count !== 0 && total_num >= rows[0].target_count) {
  300. this.logger.info(`${account}乐跑目标完成,发送乐跑结束通知并关闭自动乐跑`)
  301. if (rows[0].notice_type === 'bot' && rows[0].bot_umo) {
  302. this.logger.info(`${account}发送乐跑完成Bot通知,UMO=${rows[0].bot_umo}`)
  303. const ch = await mq.getChannel(this.messageQueue)
  304. await ch.assertQueue(this.messageQueue, {
  305. durable: true
  306. })
  307. data.type = 'lepao_over'
  308. ch.sendToQueue(
  309. this.messageQueue,
  310. Buffer.from(JSON.stringify(data)),
  311. {
  312. persistent: true,
  313. contentType: 'application/json'
  314. }
  315. )
  316. this.logger.info(`${account}乐跑完成Bot通知发送完成`)
  317. } else if (rows[0].notice_type === 'email' && rows[0].email) {
  318. await EmailTemplate.lepaoOver(rows[0].email, data)
  319. this.logger.info(`${account}乐跑完成邮件发送完成`)
  320. }
  321. let overSql = 'UPDATE lepao_account SET auto_run = 0 WHERE student_num = ?'
  322. let overRows = await db.query(overSql, [account])
  323. if (!overRows || overRows.affectedRows !== 1)
  324. this.logger.warn(`${account}乐跑结束后关闭自动乐跑失败`)
  325. else
  326. this.logger.info(`${account}自动乐跑关闭成功`)
  327. }
  328. } catch (error) {
  329. this.logger.error(`发送成功邮件失败: ${error.stack || error.message}`)
  330. }
  331. }
  332. async sendFailEmail(account, reason) {
  333. try {
  334. this.logger.info(`${account}发送乐跑失败通知,原因: ${reason}`)
  335. const emailSql = `
  336. SELECT
  337. a.name,
  338. a.email,
  339. a.target_count,
  340. a.notice_type,
  341. e.bot_umo
  342. FROM
  343. lepao_account a
  344. LEFT JOIN
  345. lepao_extra e
  346. ON
  347. a.student_num = e.student_num
  348. WHERE
  349. a.student_num = ?
  350. `
  351. const rows = await db.query(emailSql, [account])
  352. if (!rows || rows.length == 0) {
  353. this.logger.error(`${account}查找用户邮箱失败`)
  354. throw new Error('查找用户邮箱失败')
  355. }
  356. const data = {
  357. type: 'lepao_fail',
  358. umo: rows[0].bot_umo,
  359. name: rows[0].name,
  360. account,
  361. reason: reason === 'Request failed with status code 503' ? 'RunForge系统维护中,请稍后再试' : reason
  362. }
  363. if (rows[0].notice_type === 'bot' && rows[0].bot_umo) {
  364. this.logger.info(`${account}发送乐跑失败Bot通知,UMO=${rows[0].bot_umo}`)
  365. const ch = await mq.getChannel(this.messageQueue)
  366. await ch.assertQueue(this.messageQueue, {
  367. durable: true
  368. })
  369. ch.sendToQueue(
  370. this.messageQueue,
  371. Buffer.from(JSON.stringify(data)),
  372. {
  373. persistent: true,
  374. contentType: 'application/json'
  375. }
  376. )
  377. this.logger.info(`${account}Bot通知发送完成`)
  378. } else if (rows[0].notice_type === 'email' && rows[0].email) {
  379. await EmailTemplate.lepaoFail(rows[0].email, data)
  380. this.logger.info(`${account}乐跑失败邮件发送完成`)
  381. }
  382. } catch (error) {
  383. this.logger.error(`发送失败邮件失败: ${error.stack || error.message}`)
  384. }
  385. }
  386. async lepaoFail(uuid) {
  387. try {
  388. this.logger.info(`返还用户 ${uuid} 乐跑次数`)
  389. const sql = 'UPDATE users SET lepao_count = lepao_count + 1 WHERE uuid = ?'
  390. await db.query(sql, [uuid])
  391. this.logger.info(`返还用户 ${uuid} 乐跑次数成功`)
  392. } catch (error) {
  393. this.logger.error(`返还用户 ${uuid} 乐跑次数时出错: ${error.stack || error.message}`)
  394. }
  395. }
  396. async setStatusFail(account) {
  397. try {
  398. this.logger.info(`${account}设置账号为未启用`)
  399. const sql = 'UPDATE lepao_account SET state = 0 WHERE student_num = ?'
  400. await db.query(sql, [account])
  401. this.logger.info(`${account}账号状态设置为未启用成功`)
  402. } catch (error) {
  403. this.logger.error(`设置用户 ${account} state时出错: ${error.stack || error.message}`)
  404. }
  405. }
  406. // 修复3.12~3.18期间未入库记录
  407. async fixRecords(uuid, reqData) {
  408. try {
  409. //已开始乐跑,存入Redis
  410. const isFix = await Redis.get(`fixRecord:${reqData.student_id}`)
  411. if (isFix) {
  412. this.logger.info(`${reqData.student_id}已存在修复记录,跳过修复流程`)
  413. return
  414. }
  415. await Redis.set(`fixRecord:${reqData.student_id}`, reqData.student_id)
  416. const countUrl = this.runpy + '/get_term_record'
  417. const recordRes = await axios.post(countUrl, reqData)
  418. const { data } = recordRes
  419. if (!data || !data.counts) {
  420. this.logger.warn(`修复乐跑记录失败,接口返回异常`)
  421. return
  422. }
  423. const count = data.counts || 0
  424. let fixSql = 'UPDATE users SET lepao_count = lepao_count - ? WHERE uuid = ?'
  425. await db.query(fixSql, [count, uuid])
  426. this.logger.info(`修复乐跑记录成功,扣除用户 ${uuid} 乐跑次数 ${count} 次`)
  427. } catch (error) {
  428. this.logger.error(`修复乐跑记录失败: ${error.stack || error.message}`)
  429. }
  430. }
  431. }
  432. const lepao = new Lepao()
  433. module.exports.lepao = lepao