Lepao.js 9.5 KB

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