router.js 9.0 KB

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