router.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. const express = require('express')
  2. const { updateGPTConfig } = require('./API/ChatGPT')
  3. const { updateXunfeiConfig } = require('./API/xunfei')
  4. const { updateTYConfig } = require('./API/tongyi')
  5. const { sendMessageToAPI } = require('./wechat/main')
  6. const sqlite3 = require('sqlite3')
  7. const jsonwebtoken = require('jsonwebtoken')
  8. const path = require('path')
  9. const secretKey = 'co666'
  10. const {
  11. wxlogin,
  12. Status,
  13. User,
  14. setWx,
  15. stopWx,
  16. loadConfigValues
  17. } = require('./wechat/main')
  18. //打开数据库
  19. var db = new sqlite3.Database("./db/data.db")
  20. const router = express.Router()
  21. router.use(express.static('./public'))
  22. // 定义中间件.unless指定哪些接口不需要进行token身份认证
  23. const { expressjwt: jwt } = require("express-jwt")
  24. const checkTokenMiddleware = jwt({ secret: secretKey, algorithms: ["HS256"] }).unless({
  25. path: [/^\/userlogin/, /^\/register/, /^\/getavatar/],
  26. })
  27. // 验证token
  28. const errorcheckToken = (err, req, res, next) => {
  29. if (err.name === 'UnauthorizedError') {
  30. return res.send({ status: 401, msg: '请先登录' })
  31. }
  32. res.send({ status: 500, msg: '未知错误' })
  33. }
  34. // 封装验证Token和错误处理的函数
  35. const checkToken = (req, res, next) => {
  36. checkTokenMiddleware(req, res, (err) => {
  37. if (err) {
  38. errorcheckToken(err, req, res, next)
  39. } else {
  40. next()
  41. }
  42. })
  43. }
  44. router.use(checkToken)
  45. //用户登录
  46. router.post('/userlogin', (req, res) => {
  47. const username = req.body.username
  48. const password = req.body.password
  49. const remember = req.body.remember
  50. // 匹配密码
  51. db.all('select * from user where username=?', username, function (err, row) {
  52. if (err) res.send({ status: 500, msg: "数据库查询失败" })
  53. else {
  54. if (row == "") {
  55. res.send({ status: 500, msg: "此用户不存在" })
  56. } else {
  57. if (row[0].password != password) {
  58. res.send({ status: 500, msg: "密码错误" })
  59. } else {
  60. // 如果用户名存在且密码匹配,则登录成功。
  61. if(remember) {
  62. const tokenStr = jsonwebtoken.sign({ username: username }, secretKey)
  63. res.send({ status: 200, msg: "登录成功", token: "Bearer " + tokenStr })
  64. } else{
  65. const tokenStr = jsonwebtoken.sign({ username: username }, secretKey, { expiresIn: '24h' })
  66. res.send({ status: 200, msg: "登录成功", token: "Bearer " + tokenStr })
  67. }
  68. }
  69. }
  70. }
  71. })
  72. })
  73. //更改账户信息
  74. function findusername(req, res, next) {
  75. // 从请求头中获取 Token
  76. const token = req.headers['authorization']
  77. jsonwebtoken.verify(token.split(' ')[1], secretKey, (err, decoded) => {
  78. if (err) {
  79. return res.send({ status: 401, msg: 'Token无效' })
  80. } else {
  81. req.username = decoded.username
  82. next()
  83. }
  84. })
  85. }
  86. router.post('/getusername', findusername,(req,res) => {
  87. const username = req.username
  88. res.send({status: 200,msg:username})
  89. })
  90. router.post('/changeaccount', findusername, (req, res) => {
  91. const username = req.username
  92. const oldpassword = req.body.oldpassword
  93. const newusername = req.body.newusername
  94. const newpassword = req.body.newpassword
  95. // 查询用户是否存在以及旧密码是否正确
  96. db.get('SELECT * FROM user WHERE username=? AND password=?', [username, oldpassword], (err, row) => {
  97. if (err) {
  98. res.send({ status: 500, msg: "数据库查询失败" })
  99. } else {
  100. if (!row) {
  101. res.send({ status: 500, msg: "用户名或密码错误" })
  102. } else {
  103. if (newusername.length<5){
  104. res.send({ status: 500, msg: "用户名不能小于5位" })
  105. } else {
  106. if (newpassword.length<6){
  107. res.send({ status: 500, msg: "密码不能小于6位" })
  108. } else {
  109. // 更新用户名和密码
  110. db.run('UPDATE user SET username=?, password=? WHERE username=?', [newusername, newpassword, username], (err) => {
  111. if (err) {
  112. res.send({ status: 500, msg: "更新账户信息失败" })
  113. } else {
  114. res.send({ status: 200, msg: "账户信息更新成功" })
  115. }
  116. })
  117. }
  118. }
  119. }
  120. }
  121. })
  122. })
  123. //获取二维码 启动bot
  124. router.get('/getqrcode',async(req,res) => {
  125. wxlogin()
  126. .then(qrcodeUrl =>{
  127. res.send({ qrcode: qrcodeUrl })
  128. })
  129. })
  130. // 发送头像图片文件
  131. router.get('/getavatar',async(req,res) => {
  132. try {
  133. const avatarFilePath = path.join(__dirname,'./wechat/avatar/avatar.jpg')
  134. res.sendFile(avatarFilePath)
  135. } catch(error) {
  136. res.send({status:500,msg:'获取头像失败!' + error.message})
  137. }
  138. })
  139. router.get('/getwxname', async (req, res) => {
  140. res.send({ wxname: User.name })
  141. })
  142. //获取二维码状态
  143. router.get('/getstatus',async(req,res) => {
  144. res.send({status:Status.status})
  145. })
  146. router.post('/chat',async(req,res) => {
  147. try{
  148. const response = await sendMessageToAPI(req.body.msg)
  149. res.send({status:200,msg:response})
  150. } catch(err) {
  151. res.send({status:500,msg:'获取消息失败!'+ err.message})
  152. }
  153. })
  154. // 停止机器人
  155. router.get('/stop', async (req, res) => {
  156. try {
  157. stopWx()
  158. res.send({ Status: 200, msg: '停止机器人成功' })
  159. } catch (error) {
  160. res.send({ Status: 500, msg: '停止机器人失败' + error })
  161. }
  162. })
  163. router.post('/getgptconfig', async (req, res) => {
  164. db.all('SELECT * FROM gptconfig', [], (err, rows) => {
  165. if (err) {
  166. res.send({ status: 500, msg: '查询失败!' })
  167. return
  168. }
  169. res.send({ status: 200, msg: rows })
  170. })
  171. })
  172. router.post('/getxfconfig', async (req, res) => {
  173. db.all('SELECT * FROM xfconfig', [], (err, rows) => {
  174. if (err) {
  175. res.send({ status: 500, msg: '查询失败!' })
  176. return
  177. }
  178. res.send({ status: 200, msg: rows })
  179. })
  180. })
  181. router.post('/gettyconfig', async (req, res) => {
  182. db.all('SELECT * FROM tongyiconfig', [], (err, rows) => {
  183. if (err) {
  184. res.send({ status: 500, msg: '查询失败!' })
  185. return
  186. }
  187. res.send({ status: 200, msg: rows })
  188. })
  189. })
  190. router.post('/gptconfig',async(req,res) => {
  191. const { apiKey,apiUrl,app_code,model,presets } = req.body
  192. try {
  193. updateGPTConfig("apiKey", apiKey)
  194. updateGPTConfig("apiUrl", apiUrl)
  195. updateGPTConfig("app_code", app_code)
  196. updateGPTConfig("model",model)
  197. updateGPTConfig("presets",presets)
  198. res.send({status: 200,msg: '设置成功!'})
  199. } catch (error) {
  200. res.send({status: 500, msg: '设置失败!'})
  201. }
  202. })
  203. router.post('/xfconfig', async (req, res) => {
  204. const { temperature, max_tokens, app_id, APIKey, APISecret, APIUrl, domain } = req.body
  205. try {
  206. updateXunfeiConfig("temperature", temperature)
  207. updateXunfeiConfig("max_tokens", max_tokens)
  208. updateXunfeiConfig("app_id", app_id)
  209. updateXunfeiConfig("APIKey", APIKey)
  210. updateXunfeiConfig("APISecret", APISecret)
  211. updateXunfeiConfig("APIUrl", APIUrl)
  212. updateXunfeiConfig("domain", domain)
  213. res.send({ status: 200, msg: '设置成功!' })
  214. } catch (error) {
  215. res.send({ status: 500, msg: '设置失败!' })
  216. }
  217. })
  218. router.post('/tyconfig', async (req, res) => {
  219. const { temperature, max_tokens, model, apiKey, presets, apiUrl } = req.body
  220. try {
  221. updateTYConfig("temperature", temperature)
  222. updateTYConfig("max_tokens", max_tokens)
  223. updateTYConfig("presets", presets)
  224. updateTYConfig("apiKey", apiKey)
  225. updateTYConfig("model", model)
  226. updateTYConfig("apiUrl", apiUrl)
  227. res.send({ status: 200, msg: '设置成功!' })
  228. } catch (error) {
  229. res.send({ status: 500, msg: '设置失败!' })
  230. }
  231. })
  232. //获取机器人设置
  233. router.post('/getwxconfig', async (req, res) => {
  234. db.all('SELECT * FROM wxconfig', [], (err, rows) => {
  235. if (err) {
  236. res.send({ status: 500, msg: '查询失败!' })
  237. return
  238. }
  239. res.send({ status: 200, msg: rows })
  240. })
  241. })
  242. //设置微信机器人
  243. router.post('/wxconfig', async (req, res) => {
  244. const { autoReplySingle, suffix, prefix, atReply, keyWords, blackName, whiteRoom ,usemodel} = req.body
  245. try {
  246. setWx('autoReplySingle', autoReplySingle)
  247. setWx('suffix', suffix)
  248. setWx('prefix', prefix)
  249. setWx('whiteRoom', whiteRoom)
  250. setWx('atReply', atReply)
  251. setWx('keyWords', keyWords)
  252. setWx('blackName', blackName)
  253. setWx('usemodel', usemodel)
  254. loadConfigValues()
  255. res.send({ status: 200, msg: '设置成功!' })
  256. } catch (error) {
  257. res.send({ status: 500, msg: '设置失败!' })
  258. }
  259. })
  260. //获取消息发送记录
  261. router.post('/messagehistory',async (req,res)=>{
  262. db.all('SELECT * FROM message', [], (err, rows) => {
  263. if (err) {
  264. res.send({ status: 500, msg: '查询失败!' })
  265. return
  266. }
  267. res.send({ status: 200, msg: rows })
  268. })
  269. })
  270. //清空消息发送记录
  271. router.post('/clearmessage',async(req,res) => {
  272. db.run('DELETE FROM message', (err) => {
  273. if (err) {
  274. res.send({ status: 500, msg: '删除失败!' })
  275. } else {
  276. res.send({ status: 200, msg: '删除成功!' })
  277. }
  278. })
  279. })
  280. module.exports = router