Lepao.js 18 KB

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