Lepao.js 9.6 KB

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