Lepao.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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, max_distance, min_distance, 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, max_distance, min_distance, sex } = rows[0]
  22. let max = Number(max_distance) || 4.00
  23. let min = Number(min_distance) || 2.00
  24. if (sex === 2) {
  25. max = Number(max_distance) || 2.50
  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) {
  48. try {
  49. const reqData = { uid, token, school_id, student_id }
  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. return res.json({
  85. ...BaseStdResponse.ERR,
  86. msg: '该账号当天已存在成功乐跑记录'
  87. })
  88. const userPermissionSql = 'SELECT vip, lepao_count FROM users WHERE uuid = ?'
  89. const userPermissionData = await db.query(userPermissionSql, [uuid])
  90. if (!userPermissionData || userPermissionData.length !== 1) {
  91. this.logger.error(`${account}无法获取用户信息`)
  92. throw new Error('无法获取用户信息,请重试或联系RunForge客服')
  93. }
  94. if (userPermissionData[0].lepao_count < 1) {
  95. this.logger.warn(`${account}乐跑次数不足`)
  96. throw new Error('用户乐跑次数不足,请购买乐跑套餐!')
  97. }
  98. if (state !== 1) {
  99. this.logger.warn(`${account}登录状态异常 state=${state}`)
  100. return this.sendFailEmail(account, '登录已过期,请尝试使用登录器重新登录')
  101. }
  102. // 获取路径 ID
  103. const path_id = await this.getPath(account, userPermissionData[0].vip)
  104. // 更换跑区
  105. this.logger.info(`${account}开始更换跑区,path_id=${path_id}`)
  106. const zoneUrl = this.runpy + '/set_zone'
  107. // 晚上10点后提前
  108. let run_end_time = Math.floor(Date.now() / 1000) - 300 // 提前5分钟
  109. let hour = new Date().getHours()
  110. if (hour >= 22) {
  111. this.logger.info(`${account}当前时间为${hour}点,调整run_end_time提前5小时`)
  112. run_end_time -= 18000
  113. }
  114. const ossData = { uid, token, school_id, student_id: account, random_id: path_id, run_end_time }
  115. try {
  116. const zoneRes = await axios.post(zoneUrl, ossData)
  117. const { data } = zoneRes
  118. this.logger.info(`${account}更换跑区返回结果: ${JSON.stringify(data)}`)
  119. if (!data || data.status !== 1 || !data.data) {
  120. this.setStatusFail(account)
  121. throw new Error(data?.info || '未知错误,请尝试重新登录')
  122. }
  123. } catch (error) {
  124. this.logger.error(`${account}更换跑区失败: ${error.stack || error.message}`)
  125. throw error
  126. }
  127. // 上传 OSS
  128. this.logger.info(`${account}开始上传OSS记录`)
  129. const ossUrl = this.runpy + '/upload_oss_file'
  130. let oss_path, point_data
  131. try {
  132. const ossRes = await axios.post(ossUrl, ossData, {
  133. proxy: false
  134. })
  135. const { data } = ossRes
  136. this.logger.info(`${account}上传OSS记录返回结果: ${JSON.stringify(data)}`)
  137. if (!data || data.code !== 200 || !data.oss_path || !data.point_data) {
  138. throw new Error('请检查登录是否过期,并尝试更新乐跑登录状态')
  139. }
  140. oss_path = data.oss_path
  141. point_data = data.point_data
  142. this.logger.info(`${account}上传OSS记录成功!oss_path:${oss_path}`)
  143. } catch (error) {
  144. this.setStatusFail(account)
  145. this.logger.error(`${account}上传OSS记录失败,请检查登录是否过期。${error.stack || error.message}`)
  146. throw new Error('请检查登录是否过期')
  147. }
  148. // 扣除乐跑次数
  149. this.logger.info(`${account}开始扣减乐跑次数`)
  150. const useLepaoCountSql = 'UPDATE users SET lepao_count = lepao_count - 1 WHERE uuid = ?'
  151. await db.query(useLepaoCountSql, [uuid])
  152. this.logger.info(`${account}扣减乐跑次数完成`)
  153. const lepaoData = {
  154. uid,
  155. token,
  156. school_id,
  157. student_id: account,
  158. random_id: path_id,
  159. record_file: oss_path,
  160. run_end_time,
  161. point_data
  162. }
  163. this.logger.info(`${account}乐跑请求参数构造完成:`)
  164. this.logger.info(JSON.stringify(lepaoData))
  165. // 绑定乐跑数据
  166. this.logger.info(`${account}开始绑定乐跑数据`)
  167. const lepaoUrl = this.runpy + '/bind_data'
  168. try {
  169. const lepaoRes = await axios.post(lepaoUrl, lepaoData)
  170. const { data } = lepaoRes
  171. this.logger.info(`${account}绑定乐跑数据返回结果: ${JSON.stringify(data)}`)
  172. if (!data || data.status !== 1 || !data.data) {
  173. this.setStatusFail(account)
  174. throw new Error(data?.info || '未知错误,请尝试重新登录')
  175. }
  176. await this.addRecord(uuid, account, data.data, path_id)
  177. // 获取剩余跑步次数
  178. const recordData = await this.getRecord(uid, token, school_id, account)
  179. this.logger.info(`${account}获取剩余跑步次数结果: ${JSON.stringify(recordData)}`)
  180. let term_num = recordData?.term_num || 0
  181. let total_num = recordData?.total_num || 30
  182. if (data.data.record_failed_reason === '自动确认有效') {
  183. // 成功记录存入Redis
  184. await this.writeRedis(account)
  185. await this.sendSuccessEmail(account, data.data, term_num, total_num)
  186. } else {
  187. this.logger.warn(`${account}乐跑失败,原因: ${data.data.record_failed_reason}`)
  188. // 已存在记录也存redis
  189. if(data.data.record_failed_reason === '当天关联成绩次数已达到上限')
  190. await this.writeRedis(account)
  191. await this.sendFailEmail(account, data.data.record_failed_reason)
  192. await this.lepaoFail(uuid)
  193. }
  194. let recordSql = 'UPDATE lepao_account SET term_num = ?, total_num = ? WHERE student_num = ?'
  195. let recordRows = await db.query(recordSql, [term_num, total_num, account])
  196. if (!recordRows || recordRows.affectedRows !== 1)
  197. this.logger.warn(`${account}更新乐跑次数失败`)
  198. else
  199. this.logger.info(`${account}更新乐跑次数成功 term_num=${term_num}, total_num=${total_num}`)
  200. } catch (error) {
  201. this.logger.error(`${account}绑定乐跑数据失败: ${error.stack || error.message}`)
  202. await this.lepaoFail(uuid)
  203. throw error
  204. }
  205. } catch (error) {
  206. this.logger.error(`${account}乐跑流程异常: ${error.stack || error.message}`)
  207. await this.sendFailEmail(account, error.message || '未知错误,请尝试重新登录')
  208. }
  209. }
  210. async addRecord(uuid, account, result, path_id) {
  211. try {
  212. const time = Date.now()
  213. this.logger.info(`${account}添加乐跑记录,path_id=${path_id}`)
  214. const sql = 'INSERT INTO lepao_record (uuid, time, lepao_account, result, path_id) VALUES (?, ?, ?, ?, ?)'
  215. await db.query(sql, [uuid, time, account, result, path_id])
  216. this.logger.info(`${account}添加乐跑记录成功`)
  217. } catch (error) {
  218. this.logger.error(`添加乐跑记录失败: ${error.stack || error.message}`)
  219. }
  220. }
  221. async sendSuccessEmail(account, lepaoData, term_num, total_num) {
  222. try {
  223. this.logger.info(`${account}发送乐跑成功邮件`)
  224. const emailSql = 'SELECT name, email FROM lepao_account WHERE student_num = ?'
  225. const rows = await db.query(emailSql, [account])
  226. if (!rows || rows.length === 0) {
  227. this.logger.error(`${account}查找用户邮箱失败`)
  228. throw new Error('查找用户邮箱失败')
  229. }
  230. const data = {
  231. ...lepaoData,
  232. term_num,
  233. total_num,
  234. name: rows[0].name,
  235. account
  236. }
  237. await EmailTemplate.lepaoSuccess(rows[0].email, data)
  238. this.logger.info(`${account}乐跑成功邮件发送完成`)
  239. if (total_num === term_num) {
  240. this.logger.info(`${account}乐跑目标完成,发送乐跑结束邮件并关闭自动乐跑`)
  241. await EmailTemplate.lepaoOver(rows[0].email, data)
  242. let overSql = 'UPDATE lepao_account SET auto_run = 0 WHERE student_num = ?'
  243. let overRows = await db.query(overSql, [account])
  244. if (!overRows || overRows.affectedRows !== 1)
  245. this.logger.warn(`${account}乐跑结束后关闭自动乐跑失败`)
  246. else
  247. this.logger.info(`${account}自动乐跑关闭成功`)
  248. }
  249. } catch (error) {
  250. this.logger.error(`发送成功邮件失败: ${error.stack || error.message}`)
  251. }
  252. }
  253. async sendFailEmail(account, reason) {
  254. try {
  255. this.logger.info(`${account}发送乐跑失败邮件,原因: ${reason}`)
  256. const emailSql = 'SELECT name, email FROM lepao_account WHERE student_num = ?'
  257. const rows = await db.query(emailSql, [account])
  258. if (!rows || rows.length == 0) {
  259. this.logger.error(`${account}查找用户邮箱失败`)
  260. throw new Error('查找用户邮箱失败')
  261. }
  262. const data = {
  263. name: rows[0].name,
  264. account,
  265. reason: reason === 'Request failed with status code 503' ? 'RunForge系统维护中,请稍后再试' : reason
  266. }
  267. await EmailTemplate.lepaoFail(rows[0].email, data)
  268. this.logger.info(`${account}乐跑失败邮件发送完成`)
  269. } catch (error) {
  270. this.logger.error(`发送失败邮件失败: ${error.stack || error.message}`)
  271. }
  272. }
  273. async lepaoFail(uuid) {
  274. try {
  275. this.logger.info(`返还用户 ${uuid} 乐跑次数`)
  276. const sql = 'UPDATE users SET lepao_count = lepao_count + 1 WHERE uuid = ?'
  277. await db.query(sql, [uuid])
  278. this.logger.info(`返还用户 ${uuid} 乐跑次数成功`)
  279. } catch (error) {
  280. this.logger.error(`返还用户 ${uuid} 乐跑次数时出错: ${error.stack || error.message}`)
  281. }
  282. }
  283. async setStatusFail(account) {
  284. try {
  285. this.logger.info(`${account}设置账号为未启用`)
  286. const sql = 'UPDATE lepao_account SET state = 0 WHERE student_num = ?'
  287. await db.query(sql, [account])
  288. this.logger.info(`${account}账号状态设置为未启用成功`)
  289. } catch (error) {
  290. this.logger.error(`设置用户 ${account} state时出错: ${error.stack || error.message}`)
  291. }
  292. }
  293. }
  294. const lepao = new Lepao()
  295. module.exports.lepao = lepao