Lepao.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. const axios = require('axios')
  2. const db = require('../../plugin/DataBase/db')
  3. const Logger = require('../Logger')
  4. const path = require('path')
  5. const EmailTemplate = require('../../plugin/Email/emailTemplate')
  6. const config = require('../../config.json')
  7. class Lepao {
  8. constructor() {
  9. this.logger = new Logger(path.join(__dirname, '../logs/Lepao.log'), 'INFO')
  10. this.runpy = config.runpy
  11. }
  12. async getPath(account, vip) {
  13. this.logger.info(`${account}开始获取路径`)
  14. const accountSql = 'SELECT area, max_distance, min_distance, sex FROM lepao_account WHERE student_num = ?'
  15. const rows = await db.query(accountSql, [account])
  16. if (!rows || rows.length === 0) {
  17. this.logger.error(`${account}无法获取账号数据`)
  18. throw new Error('无法获取账号数据')
  19. }
  20. const { area, max_distance, min_distance, sex } = rows[0]
  21. let max = Number(max_distance) || 4.00
  22. let min = Number(min_distance) || 2.00
  23. if (sex === 2) {
  24. max = Number(max_distance) || 2.50
  25. min = 1.60
  26. }
  27. this.logger.info(`${account}路径参数: area=${area ?? '随机'}, max_distance=${max}, min_distance=${min}`)
  28. let pathSql = 'SELECT id FROM path_data WHERE state = 1 AND distance < ? AND distance > ? '
  29. const pathParams = [max, min]
  30. if (area) {
  31. pathSql += ' AND run_zone_name = ?'
  32. pathParams.push(area)
  33. }
  34. pathSql += ' ORDER BY count ASC LIMIT 1'
  35. const paths = await db.query(pathSql, pathParams)
  36. if (!paths || paths.length === 0) {
  37. this.logger.error(`${account}未找到符合条件的路线`)
  38. throw new Error('未找到符合条件的路线,请改变路径选择条件')
  39. }
  40. const randomPath = paths[0]
  41. const updateSql = 'UPDATE path_data SET count = count + 1 WHERE id = ?'
  42. await db.query(updateSql, [randomPath.id])
  43. this.logger.info(`${account}路径选中id=${randomPath.id},计数加1成功`)
  44. return randomPath.id
  45. }
  46. async getRecord(uid, token, school_id, student_id) {
  47. try {
  48. const reqData = { uid, token, school_id, student_id }
  49. this.logger.info(`开始请求获取跑步次数 uid=${uid} student_id=${student_id}`)
  50. const recordUrl = this.runpy + '/get_record'
  51. let recordRes = await axios.post(recordUrl, reqData)
  52. const { data } = recordRes
  53. this.logger.info(`获取跑步次数返回结果: ${JSON.stringify(data)}`)
  54. if (!data || data.status !== 1 || !data.data) {
  55. this.logger.warn('获取剩余跑步次数失败,接口返回异常')
  56. return
  57. }
  58. return data.data
  59. } catch (error) {
  60. this.logger.error(`获取跑步次数失败: ${error.stack || error.message}`)
  61. return
  62. }
  63. }
  64. async beginLepao(uuid, account, token, uid, school_id, state) {
  65. try {
  66. this.logger.info(`${account}开始执行乐跑流程`)
  67. const userPermissionSql = 'SELECT vip, lepao_count FROM users WHERE uuid = ?'
  68. const userPermissionData = await db.query(userPermissionSql, [uuid])
  69. if (!userPermissionData || userPermissionData.length !== 1) {
  70. this.logger.error(`${account}无法获取用户信息`)
  71. throw new Error('无法获取用户信息,请重试或联系RunForge客服')
  72. }
  73. if (userPermissionData[0].lepao_count < 1) {
  74. this.logger.warn(`${account}乐跑次数不足`)
  75. throw new Error('用户乐跑次数不足,请购买乐跑套餐!')
  76. }
  77. if (state !== 1) {
  78. this.logger.warn(`${account}登录状态异常 state=${state}`)
  79. return this.sendFailEmail(account, '登录已过期,请尝试使用登录器重新登录')
  80. }
  81. // 获取路径 ID
  82. const path_id = await this.getPath(account, userPermissionData[0].vip)
  83. // 更换跑区
  84. this.logger.info(`${account}开始更换跑区,path_id=${path_id}`)
  85. const zoneUrl = this.runpy + '/set_zone'
  86. // 晚上10点后提前
  87. let run_end_time = Math.floor(Date.now() / 1000) - 300 // 提前5分钟
  88. let hour = new Date().getHours()
  89. if (hour >= 22) {
  90. this.logger.info(`${account}当前时间为${hour}点,调整run_end_time提前5小时`)
  91. run_end_time -= 18000
  92. }
  93. const ossData = { uid, token, school_id, student_id: account, random_id: path_id, run_end_time }
  94. try {
  95. const zoneRes = await axios.post(zoneUrl, ossData)
  96. const { data } = zoneRes
  97. this.logger.info(`${account}更换跑区返回结果: ${JSON.stringify(data)}`)
  98. if (!data || data.status !== 1 || !data.data) {
  99. this.setStatusFail(account)
  100. throw new Error(data?.info || '未知错误,请尝试重新登录')
  101. }
  102. } catch (error) {
  103. this.logger.error(`${account}更换跑区失败: ${error.stack || error.message}`)
  104. throw error
  105. }
  106. // 上传 OSS
  107. this.logger.info(`${account}开始上传OSS记录`)
  108. const ossUrl = this.runpy + '/upload_oss_file'
  109. let oss_path, point_data
  110. try {
  111. const ossRes = await axios.post(ossUrl, ossData, {
  112. proxy: false
  113. })
  114. const { data } = ossRes
  115. this.logger.info(`${account}上传OSS记录返回结果: ${JSON.stringify(data)}`)
  116. if (!data || data.code !== 200 || !data.oss_path || !data.point_data) {
  117. throw new Error('请检查登录是否过期,并尝试更新乐跑登录状态')
  118. }
  119. oss_path = data.oss_path
  120. point_data = data.point_data
  121. this.logger.info(`${account}上传OSS记录成功!oss_path:${oss_path}`)
  122. } catch (error) {
  123. this.setStatusFail(account)
  124. this.logger.error(`${account}上传OSS记录失败,请检查登录是否过期。${error.stack || error.message}`)
  125. throw new Error('请检查登录是否过期')
  126. }
  127. // 扣除乐跑次数
  128. this.logger.info(`${account}开始扣减乐跑次数`)
  129. const useLepaoCountSql = 'UPDATE users SET lepao_count = lepao_count - 1 WHERE uuid = ?'
  130. await db.query(useLepaoCountSql, [uuid])
  131. this.logger.info(`${account}扣减乐跑次数完成`)
  132. const lepaoData = {
  133. uid,
  134. token,
  135. school_id,
  136. student_id: account,
  137. random_id: path_id,
  138. record_file: oss_path,
  139. run_end_time,
  140. point_data
  141. }
  142. this.logger.info(`${account}乐跑请求参数构造完成:`)
  143. this.logger.info(JSON.stringify(lepaoData))
  144. // 绑定乐跑数据
  145. this.logger.info(`${account}开始绑定乐跑数据`)
  146. const lepaoUrl = this.runpy + '/bind_data'
  147. try {
  148. const lepaoRes = await axios.post(lepaoUrl, lepaoData)
  149. const { data } = lepaoRes
  150. this.logger.info(`${account}绑定乐跑数据返回结果: ${JSON.stringify(data)}`)
  151. if (!data || data.status !== 1 || !data.data) {
  152. this.setStatusFail(account)
  153. throw new Error(data?.info || '未知错误,请尝试重新登录')
  154. }
  155. await this.addRecord(uuid, account, data.data, path_id)
  156. // 获取剩余跑步次数
  157. const recordData = await this.getRecord(uid, token, school_id, account)
  158. this.logger.info(`${account}获取剩余跑步次数结果: ${JSON.stringify(recordData)}`)
  159. let term_num = recordData?.term_num || 0
  160. let total_num = recordData?.total_num || 30
  161. if (data.data.record_failed_reason === '自动确认有效') {
  162. await this.sendSuccessEmail(account, data.data, term_num, total_num)
  163. } else {
  164. this.logger.warn(`${account}乐跑失败,原因: ${data.data.record_failed_reason}`)
  165. await this.sendFailEmail(account, data.data.record_failed_reason)
  166. await this.lepaoFail(uuid)
  167. }
  168. let recordSql = 'UPDATE lepao_account SET term_num = ?, total_num = ? WHERE student_num = ?'
  169. let recordRows = await db.query(recordSql, [term_num, total_num, account])
  170. if (!recordRows || recordRows.affectedRows !== 1)
  171. this.logger.warn(`${account}更新乐跑次数失败`)
  172. else
  173. this.logger.info(`${account}更新乐跑次数成功 term_num=${term_num}, total_num=${total_num}`)
  174. } catch (error) {
  175. this.logger.error(`${account}绑定乐跑数据失败: ${error.stack || error.message}`)
  176. await this.lepaoFail(uuid)
  177. throw error
  178. }
  179. } catch (error) {
  180. this.logger.error(`${account}乐跑流程异常: ${error.stack || error.message}`)
  181. await this.sendFailEmail(account, error.message || '未知错误,请尝试重新登录')
  182. }
  183. }
  184. async addRecord(uuid, account, result, path_id) {
  185. try {
  186. const time = Date.now()
  187. this.logger.info(`${account}添加乐跑记录,path_id=${path_id}`)
  188. const sql = 'INSERT INTO lepao_record (uuid, time, lepao_account, result, path_id) VALUES (?, ?, ?, ?, ?)'
  189. await db.query(sql, [uuid, time, account, result, path_id])
  190. this.logger.info(`${account}添加乐跑记录成功`)
  191. } catch (error) {
  192. this.logger.error(`添加乐跑记录失败: ${error.stack || error.message}`)
  193. }
  194. }
  195. async sendSuccessEmail(account, lepaoData, term_num, total_num) {
  196. try {
  197. this.logger.info(`${account}发送乐跑成功邮件`)
  198. const emailSql = 'SELECT name, email FROM lepao_account WHERE student_num = ?'
  199. const rows = await db.query(emailSql, [account])
  200. if (!rows || rows.length === 0) {
  201. this.logger.error(`${account}查找用户邮箱失败`)
  202. throw new Error('查找用户邮箱失败')
  203. }
  204. const data = {
  205. ...lepaoData,
  206. term_num,
  207. total_num,
  208. name: rows[0].name,
  209. account
  210. }
  211. await EmailTemplate.lepaoSuccess(rows[0].email, data)
  212. this.logger.info(`${account}乐跑成功邮件发送完成`)
  213. if (total_num === term_num) {
  214. this.logger.info(`${account}乐跑目标完成,发送乐跑结束邮件并关闭自动乐跑`)
  215. await EmailTemplate.lepaoOver(rows[0].email, data)
  216. let overSql = 'UPDATE lepao_account SET auto_run = 0 WHERE student_num = ?'
  217. let overRows = await db.query(overSql, [account])
  218. if (!overRows || overRows.affectedRows !== 1)
  219. this.logger.warn(`${account}乐跑结束后关闭自动乐跑失败`)
  220. else
  221. this.logger.info(`${account}自动乐跑关闭成功`)
  222. }
  223. } catch (error) {
  224. this.logger.error(`发送成功邮件失败: ${error.stack || error.message}`)
  225. }
  226. }
  227. async sendFailEmail(account, reason) {
  228. try {
  229. this.logger.info(`${account}发送乐跑失败邮件,原因: ${reason}`)
  230. const emailSql = 'SELECT name, email FROM lepao_account WHERE student_num = ?'
  231. const rows = await db.query(emailSql, [account])
  232. if (!rows || rows.length == 0) {
  233. this.logger.error(`${account}查找用户邮箱失败`)
  234. throw new Error('查找用户邮箱失败')
  235. }
  236. const data = {
  237. name: rows[0].name,
  238. account,
  239. reason: reason === 'Request failed with status code 503' ? 'RunForge系统维护中,请稍后再试' : reason
  240. }
  241. await EmailTemplate.lepaoFail(rows[0].email, data)
  242. this.logger.info(`${account}乐跑失败邮件发送完成`)
  243. } catch (error) {
  244. this.logger.error(`发送失败邮件失败: ${error.stack || error.message}`)
  245. }
  246. }
  247. async lepaoFail(uuid) {
  248. try {
  249. this.logger.info(`返还用户 ${uuid} 乐跑次数`)
  250. const sql = 'UPDATE users SET lepao_count = lepao_count + 1 WHERE uuid = ?'
  251. await db.query(sql, [uuid])
  252. this.logger.info(`返还用户 ${uuid} 乐跑次数成功`)
  253. } catch (error) {
  254. this.logger.error(`返还用户 ${uuid} 乐跑次数时出错: ${error.stack || error.message}`)
  255. }
  256. }
  257. async setStatusFail(account) {
  258. try {
  259. this.logger.info(`${account}设置账号为未启用`)
  260. const sql = 'UPDATE lepao_account SET state = 0 WHERE student_num = ?'
  261. await db.query(sql, [account])
  262. this.logger.info(`${account}账号状态设置为未启用成功`)
  263. } catch (error) {
  264. this.logger.error(`设置用户 ${account} state时出错: ${error.stack || error.message}`)
  265. }
  266. }
  267. }
  268. const lepao = new Lepao()
  269. module.exports.lepao = lepao