Lepao.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. const accountSql = 'SELECT area, max_distance, min_distance, sex FROM lepao_account WHERE student_num = ?'
  14. const rows = await db.query(accountSql, [account])
  15. if (!rows || rows.length === 0) {
  16. throw new Error('无法获取账号数据')
  17. }
  18. const { area, max_distance, min_distance, sex } = rows[0]
  19. let max = Number(max_distance) || 4.00
  20. let min = Number(min_distance) || 2.00
  21. if (sex === 2) {
  22. max = Number(max_distance) || 4.00
  23. // min = Number(min_distance) || 1.60
  24. min = 1.60
  25. }
  26. // if (vip !== 1) {
  27. // if (area) throw new Error('指定乐跑跑区为 VIP 专用功能,请先开通 VIP')
  28. // if (max !== 4.00 || min !== 2.00 ) throw new Error('指定乐跑距离区间为 VIP 专用功能,请先开通 VIP')
  29. // }
  30. // 从远程获取路径 停用
  31. // const pathUrl = config.url4 + '/getPathData'
  32. // const pathRes = await axios.post(pathUrl, lepaoData)
  33. // const { data } = pathRes
  34. // if (!data || data.code !== 0 || !data.data) {
  35. // throw new Error(data?.msg || '获取跑步路径失败,请稍后再试')
  36. // }
  37. let pathSql = 'SELECT id FROM path_data WHERE distance < ? AND distance > ? '
  38. const pathParams = [max, min]
  39. if (area) {
  40. pathSql += ' AND run_zone_name = ?'
  41. pathParams.push(area)
  42. }
  43. pathSql += ' ORDER BY count LIMIT 1'
  44. const paths = await db.query(pathSql, pathParams)
  45. if (!paths || paths.length === 0) {
  46. throw new Error('未找到符合条件的路线,请改变路径选择条件')
  47. }
  48. // const randomPath = paths[Math.floor(Math.random() * paths.length)]
  49. const randomPath = paths[0]
  50. return randomPath.id
  51. }
  52. // 获取跑步次数
  53. async getRecord(uid, token, school_id, student_id) {
  54. try {
  55. const reqData = { uid, token, school_id, student_id }
  56. const recordUrl = this.runpy + '/get_record'
  57. let recordRes = await axios.post(recordUrl, reqData)
  58. const { data } = recordRes
  59. if (!data || data.status !== 1 || !data.data) {
  60. this.logger.info('获取剩余跑步次数失败!')
  61. console.log(data)
  62. return
  63. }
  64. return data.data
  65. } catch (error) {
  66. this.logger.error('获取跑步次数失败!')
  67. console.log(error.stack)
  68. return
  69. }
  70. }
  71. // 乐跑入口函数
  72. async beginLepao(uuid, account, token, uid, school_id, state) {
  73. try {
  74. const userPermissionSql = 'SELECT vip, lepao_count FROM users WHERE uuid = ?'
  75. const userPermissionData = await db.query(userPermissionSql, [uuid])
  76. if (!userPermissionData || userPermissionData.length !== 1)
  77. throw new Error('无法获取用户信息')
  78. if (userPermissionData[0].lepao_count < 1)
  79. throw new Error('用户乐跑次数不足,请购买乐跑套餐!')
  80. if (state !== 1) {
  81. return this.sendFailEmail(account, '登录已过期,请尝试使用登录器重新登录')
  82. }
  83. // 获取路径 ID
  84. const path_id = await this.getPath(account, userPermissionData[0].vip)
  85. // 更换跑区
  86. const zoneUrl = this.runpy + '/set_zone'
  87. const ossData = { uid, token, school_id, student_id: account, random_id: path_id }
  88. try {
  89. const zoneRes = await axios.post(zoneUrl, ossData)
  90. const { data } = zoneRes
  91. if (!data || data.status !== 1 || !data.data) {
  92. this.setStatusFail(account)
  93. throw new Error(data?.info || '未知错误,请尝试重新登录')
  94. }
  95. } catch (error) {
  96. throw error
  97. }
  98. // 上传 OSS
  99. const ossUrl = this.runpy + '/upload_oss_file'
  100. let oss_path
  101. try {
  102. const ossRes = await axios.post(ossUrl, ossData)
  103. const { data } = ossRes
  104. if (!data || data.code !== 200 || !data.oss_path) {
  105. throw new Error('请检查登录是否过期,并尝试更新乐跑登录状态')
  106. }
  107. oss_path = data.oss_path
  108. } catch (error) {
  109. this.setStatusFail(account)
  110. this.logger.error(`上传OSS记录失败,请检查登录是否过期。${error.stack || error.message}`)
  111. throw new Error('请检查登录是否过期')
  112. }
  113. // 扣除乐跑次数
  114. const useLepaoCountSql = 'UPDATE users SET lepao_count = lepao_count - 1 WHERE uuid = ?'
  115. await db.query(useLepaoCountSql, [uuid])
  116. // 晚上10点后提前
  117. let run_end_time = Math.floor(Date.now() / 1000)
  118. let hour = new Date().getHours()
  119. if (hour >= 22) run_end_time -= 18000
  120. const lepaoData = {
  121. uid,
  122. token,
  123. school_id,
  124. student_id: account,
  125. random_id: path_id,
  126. record_file: oss_path,
  127. run_end_time
  128. }
  129. this.logger.info(lepaoData)
  130. // 绑定乐跑数据
  131. const lepaoUrl = this.runpy + '/bind_data'
  132. try {
  133. const lepaoRes = await axios.post(lepaoUrl, lepaoData)
  134. const { data } = lepaoRes
  135. if (!data || data.status !== 1 || !data.data) {
  136. this.setStatusFail(account)
  137. throw new Error(data?.info || '未知错误,请尝试重新登录')
  138. }
  139. await this.addRecord(account, data.data)
  140. // 获取剩余跑步次数
  141. const recordData = await this.getRecord(uid, token, school_id, account)
  142. let term_num = recordData.term_num || 0
  143. let total_num = recordData.total_num || 30
  144. if (data.data.record_failed_reason === '') {
  145. await this.sendSuccessEmail(account, data.data, term_num, total_num)
  146. } else {
  147. await this.sendFailEmail(account, data.data.record_failed_reason)
  148. await this.lepaoFail(uuid)
  149. }
  150. let recordSql = 'UPDATE lepao_account SET term_num = ?, total_num = ? WHERE student_num = ?'
  151. let recordRows = await db.query(recordSql, [term_num, total_num, account])
  152. if (!recordRows || recordRows.affectedRows !== 1)
  153. this.logger.info('更新乐跑次数失败!')
  154. } catch (error) {
  155. await this.lepaoFail(uuid)
  156. throw error
  157. }
  158. } catch (error) {
  159. await this.sendFailEmail(account, error.message || '未知错误,请尝试重新登录')
  160. }
  161. }
  162. async addRecord(account, result) {
  163. try {
  164. const time = Date.now()
  165. const sql = 'INSERT INTO lepao_record (time, lepao_account, result) VALUES (?, ?, ?)'
  166. await db.query(sql, [time, account, result])
  167. } catch (error) {
  168. this.logger.error(error.stack || error.message)
  169. }
  170. }
  171. async sendSuccessEmail(account, lepaoData, term_num, total_num) {
  172. try {
  173. const emailSql = 'SELECT name, email FROM lepao_account WHERE student_num = ?'
  174. const rows = await db.query(emailSql, [account])
  175. if (!rows || rows.length === 0) {
  176. throw new Error('查找用户邮箱失败')
  177. }
  178. const data = {
  179. ...lepaoData,
  180. term_num,
  181. total_num,
  182. name: rows[0].name,
  183. account
  184. }
  185. await EmailTemplate.lepaoSuccess(rows[0].email, data)
  186. // 乐跑目标完成后
  187. if (total_num === term_num) {
  188. await EmailTemplate.lepaoOver(rows[0].email, data)
  189. let overSql = 'UPDATE lepao_account SET auto_run = 0 WHERE student_num = ?'
  190. let overRows = await db.query(overSql, [account])
  191. if (!overRows || overRows.affectedRows !== 1)
  192. this.logger.info(`乐跑结束后关闭自动乐跑失败!`)
  193. }
  194. } catch (error) {
  195. this.logger.error(error.stack || error.message)
  196. }
  197. }
  198. async sendFailEmail(account, reason) {
  199. try {
  200. const emailSql = 'SELECT name, email FROM lepao_account WHERE student_num = ?'
  201. const rows = await db.query(emailSql, [account])
  202. if (!rows || rows.length == 0) {
  203. throw new Error('查找用户邮箱失败')
  204. }
  205. const data = {
  206. name: rows[0].name,
  207. account,
  208. reason
  209. }
  210. await EmailTemplate.lepaoFail(rows[0].email, data)
  211. } catch (error) {
  212. this.logger.error(error.stack || error.message)
  213. }
  214. }
  215. async lepaoFail(uuid) {
  216. try {
  217. const sql = 'UPDATE users SET lepao_count = lepao_count + 1 WHERE uuid = ?'
  218. await db.query(sql, [uuid])
  219. } catch (error) {
  220. this.logger.error(`返还用户 ${uuid} 乐跑次数时出错: ${error.stack || error.message}`)
  221. }
  222. }
  223. async setStatusFail(account) {
  224. try {
  225. const sql = 'UPDATE lepao_account SET state = 0 WHERE student_num = ?'
  226. await db.query(sql, [account])
  227. } catch (error) {
  228. this.logger.error(`设置用户 ${account} state时出错: ${error.stack || error.message}`)
  229. }
  230. }
  231. }
  232. const lepao = new Lepao()
  233. module.exports.lepao = lepao