Lepao.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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.00
  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
  110. try {
  111. const ossRes = await axios.post(ossUrl, ossData)
  112. const { data } = ossRes
  113. this.logger.info(`${account}上传OSS记录返回结果: ${JSON.stringify(data)}`)
  114. if (!data || data.code !== 200 || !data.oss_path) {
  115. throw new Error('请检查登录是否过期,并尝试更新乐跑登录状态')
  116. }
  117. oss_path = data.oss_path
  118. this.logger.info(`${account}上传OSS记录成功!oss_path:${oss_path}`)
  119. } catch (error) {
  120. this.setStatusFail(account)
  121. this.logger.error(`${account}上传OSS记录失败,请检查登录是否过期。${error.stack || error.message}`)
  122. throw new Error('请检查登录是否过期')
  123. }
  124. // 扣除乐跑次数
  125. this.logger.info(`${account}开始扣减乐跑次数`)
  126. const useLepaoCountSql = 'UPDATE users SET lepao_count = lepao_count - 1 WHERE uuid = ?'
  127. await db.query(useLepaoCountSql, [uuid])
  128. this.logger.info(`${account}扣减乐跑次数完成`)
  129. const lepaoData = {
  130. uid,
  131. token,
  132. school_id,
  133. student_id: account,
  134. random_id: path_id,
  135. record_file: oss_path,
  136. run_end_time
  137. }
  138. this.logger.info(`${account}乐跑请求参数构造完成:`)
  139. this.logger.info(JSON.stringify(lepaoData))
  140. // 绑定乐跑数据
  141. this.logger.info(`${account}开始绑定乐跑数据`)
  142. const lepaoUrl = this.runpy + '/bind_data'
  143. try {
  144. const lepaoRes = await axios.post(lepaoUrl, lepaoData)
  145. const { data } = lepaoRes
  146. this.logger.info(`${account}绑定乐跑数据返回结果: ${JSON.stringify(data)}`)
  147. if (!data || data.status !== 1 || !data.data) {
  148. this.setStatusFail(account)
  149. throw new Error(data?.info || '未知错误,请尝试重新登录')
  150. }
  151. await this.addRecord(account, data.data, path_id)
  152. // 获取剩余跑步次数
  153. const recordData = await this.getRecord(uid, token, school_id, account)
  154. this.logger.info(`${account}获取剩余跑步次数结果: ${JSON.stringify(recordData)}`)
  155. let term_num = recordData?.term_num || 0
  156. let total_num = recordData?.total_num || 30
  157. if (data.data.record_failed_reason === '自动确认有效') {
  158. await this.sendSuccessEmail(account, data.data, term_num, total_num)
  159. } else {
  160. this.logger.warn(`${account}乐跑失败,原因: ${data.data.record_failed_reason}`)
  161. await this.sendFailEmail(account, data.data.record_failed_reason)
  162. await this.lepaoFail(uuid)
  163. }
  164. let recordSql = 'UPDATE lepao_account SET term_num = ?, total_num = ? WHERE student_num = ?'
  165. let recordRows = await db.query(recordSql, [term_num, total_num, account])
  166. if (!recordRows || recordRows.affectedRows !== 1)
  167. this.logger.warn(`${account}更新乐跑次数失败`)
  168. else
  169. this.logger.info(`${account}更新乐跑次数成功 term_num=${term_num}, total_num=${total_num}`)
  170. } catch (error) {
  171. this.logger.error(`${account}绑定乐跑数据失败: ${error.stack || error.message}`)
  172. await this.lepaoFail(uuid)
  173. throw error
  174. }
  175. } catch (error) {
  176. this.logger.error(`${account}乐跑流程异常: ${error.stack || error.message}`)
  177. await this.sendFailEmail(account, error.message || '未知错误,请尝试重新登录')
  178. }
  179. }
  180. async addRecord(account, result, path_id) {
  181. try {
  182. const time = Date.now()
  183. this.logger.info(`${account}添加乐跑记录,path_id=${path_id}`)
  184. const sql = 'INSERT INTO lepao_record (time, lepao_account, result, path_id) VALUES (?, ?, ?, ?)'
  185. await db.query(sql, [time, account, result, path_id])
  186. this.logger.info(`${account}添加乐跑记录成功`)
  187. } catch (error) {
  188. this.logger.error(`添加乐跑记录失败: ${error.stack || error.message}`)
  189. }
  190. }
  191. async sendSuccessEmail(account, lepaoData, term_num, total_num) {
  192. try {
  193. this.logger.info(`${account}发送乐跑成功邮件`)
  194. const emailSql = 'SELECT name, email FROM lepao_account WHERE student_num = ?'
  195. const rows = await db.query(emailSql, [account])
  196. if (!rows || rows.length === 0) {
  197. this.logger.error(`${account}查找用户邮箱失败`)
  198. throw new Error('查找用户邮箱失败')
  199. }
  200. const data = {
  201. ...lepaoData,
  202. term_num,
  203. total_num,
  204. name: rows[0].name,
  205. account
  206. }
  207. await EmailTemplate.lepaoSuccess(rows[0].email, data)
  208. this.logger.info(`${account}乐跑成功邮件发送完成`)
  209. if (total_num === term_num) {
  210. this.logger.info(`${account}乐跑目标完成,发送乐跑结束邮件并关闭自动乐跑`)
  211. await EmailTemplate.lepaoOver(rows[0].email, data)
  212. let overSql = 'UPDATE lepao_account SET auto_run = 0 WHERE student_num = ?'
  213. let overRows = await db.query(overSql, [account])
  214. if (!overRows || overRows.affectedRows !== 1)
  215. this.logger.warn(`${account}乐跑结束后关闭自动乐跑失败`)
  216. else
  217. this.logger.info(`${account}自动乐跑关闭成功`)
  218. }
  219. } catch (error) {
  220. this.logger.error(`发送成功邮件失败: ${error.stack || error.message}`)
  221. }
  222. }
  223. async sendFailEmail(account, reason) {
  224. try {
  225. this.logger.info(`${account}发送乐跑失败邮件,原因: ${reason}`)
  226. const emailSql = 'SELECT name, email FROM lepao_account WHERE student_num = ?'
  227. const rows = await db.query(emailSql, [account])
  228. if (!rows || rows.length == 0) {
  229. this.logger.error(`${account}查找用户邮箱失败`)
  230. throw new Error('查找用户邮箱失败')
  231. }
  232. const data = {
  233. name: rows[0].name,
  234. account,
  235. reason
  236. }
  237. await EmailTemplate.lepaoFail(rows[0].email, data)
  238. this.logger.info(`${account}乐跑失败邮件发送完成`)
  239. } catch (error) {
  240. this.logger.error(`发送失败邮件失败: ${error.stack || error.message}`)
  241. }
  242. }
  243. async lepaoFail(uuid) {
  244. try {
  245. this.logger.info(`返还用户 ${uuid} 乐跑次数`)
  246. const sql = 'UPDATE users SET lepao_count = lepao_count + 1 WHERE uuid = ?'
  247. await db.query(sql, [uuid])
  248. this.logger.info(`返还用户 ${uuid} 乐跑次数成功`)
  249. } catch (error) {
  250. this.logger.error(`返还用户 ${uuid} 乐跑次数时出错: ${error.stack || error.message}`)
  251. }
  252. }
  253. async setStatusFail(account) {
  254. try {
  255. this.logger.info(`${account}设置账号为未启用`)
  256. const sql = 'UPDATE lepao_account SET state = 0 WHERE student_num = ?'
  257. await db.query(sql, [account])
  258. this.logger.info(`${account}账号状态设置为未启用成功`)
  259. } catch (error) {
  260. this.logger.error(`设置用户 ${account} state时出错: ${error.stack || error.message}`)
  261. }
  262. }
  263. }
  264. const lepao = new Lepao()
  265. module.exports.lepao = lepao