router.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. var username = req.body.username
  49. var password = req.body.password
  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. const tokenStr = jsonwebtoken.sign({ username: username }, secretKey, { expiresIn: '24h' })
  62. res.send({ status: 200, msg: "登录成功", token: "Bearer " + tokenStr })
  63. }
  64. }
  65. }
  66. })
  67. })
  68. //更改账户信息
  69. function findusername(req, res, next) {
  70. // 从请求头中获取 Token
  71. const token = req.headers['authorization']
  72. jsonwebtoken.verify(token.split(' ')[1], secretKey, (err, decoded) => {
  73. if (err) {
  74. return res.send({ status: 401, msg: 'Token无效' })
  75. } else {
  76. req.username = decoded.username
  77. next()
  78. }
  79. })
  80. }
  81. router.post('/getusername', findusername,(req,res) => {
  82. const username = req.username
  83. res.send({status: 200,msg:username})
  84. })
  85. router.post('/changeaccount', findusername, (req, res) => {
  86. const username = req.username
  87. const oldpassword = req.body.oldpassword
  88. const newusername = req.body.newusername
  89. const newpassword = req.body.newpassword
  90. // 查询用户是否存在以及旧密码是否正确
  91. db.get('SELECT * FROM user WHERE username=? AND password=?', [username, oldpassword], (err, row) => {
  92. if (err) {
  93. res.send({ status: 500, msg: "数据库查询失败" })
  94. } else {
  95. if (!row) {
  96. res.send({ status: 500, msg: "用户名或密码错误" })
  97. } else {
  98. if (newusername.length<5){
  99. res.send({ status: 500, msg: "用户名不能小于5位" })
  100. } else {
  101. if (newpassword.length<6){
  102. res.send({ status: 500, msg: "密码不能小于6位" })
  103. } else {
  104. // 更新用户名和密码
  105. db.run('UPDATE user SET username=?, password=? WHERE username=?', [newusername, newpassword, username], (err) => {
  106. if (err) {
  107. res.send({ status: 500, msg: "更新账户信息失败" })
  108. } else {
  109. res.send({ status: 200, msg: "账户信息更新成功" })
  110. }
  111. })
  112. }
  113. }
  114. }
  115. }
  116. })
  117. })
  118. //获取二维码 启动bot
  119. router.get('/getqrcode',async(req,res) => {
  120. wxlogin()
  121. .then(qrcodeUrl =>{
  122. res.send({ qrcode: qrcodeUrl })
  123. })
  124. })
  125. // 发送头像图片文件
  126. router.get('/getavatar',async(req,res) => {
  127. try {
  128. const avatarFilePath = path.join(__dirname,'./wechat/avatar/avatar.jpg')
  129. res.sendFile(avatarFilePath)
  130. } catch(error) {
  131. res.send({status:500,msg:'获取头像失败!' + error.message})
  132. }
  133. })
  134. router.get('/getwxname', async (req, res) => {
  135. res.send({ wxname: User.name })
  136. })
  137. //获取二维码状态
  138. router.get('/getstatus',async(req,res) => {
  139. res.send({status:Status.status})
  140. })
  141. router.post('/chat',async(req,res) => {
  142. try{
  143. console.log('收到:',req.body)
  144. const response = await sendMessageToAPI(req.body.msg)
  145. res.send({status:200,msg:response})
  146. } catch(err) {
  147. res.send({status:500,msg:'获取消息失败!'+ err.message})
  148. }
  149. })
  150. // 停止机器人
  151. router.get('/stop', async (req, res) => {
  152. try {
  153. stopWx()
  154. res.send({ Status: 200, msg: '停止机器人成功' })
  155. } catch (error) {
  156. res.send({ Status: 500, msg: '停止机器人失败' + error })
  157. }
  158. })
  159. router.post('/getgptconfig', async (req, res) => {
  160. db.all('SELECT * FROM gptconfig', [], (err, rows) => {
  161. if (err) {
  162. res.send({ status: 500, msg: '查询失败!' })
  163. return
  164. }
  165. res.send({ status: 200, msg: rows })
  166. })
  167. })
  168. router.post('/getxfconfig', async (req, res) => {
  169. db.all('SELECT * FROM xfconfig', [], (err, rows) => {
  170. if (err) {
  171. res.send({ status: 500, msg: '查询失败!' })
  172. return
  173. }
  174. res.send({ status: 200, msg: rows })
  175. })
  176. })
  177. router.post('/gptconfig',async(req,res) => {
  178. const { apiKey,apiUrl,app_code,model } = req.body
  179. try {
  180. updateGPTConfig("apiKey", apiKey)
  181. updateGPTConfig("apiUrl", apiUrl)
  182. updateGPTConfig("app_code", app_code)
  183. updateGPTConfig("model",model)
  184. res.send({status: 200,msg: '设置成功!'})
  185. } catch (error) {
  186. res.send({status: 500, msg: '设置失败!'})
  187. }
  188. })
  189. router.post('/xfconfig', async (req, res) => {
  190. const { temperature, max_tokens, app_id, APIKey, APISecret, APIUrl, domain } = req.body
  191. try {
  192. updateXunfeiConfig("temperature", temperature)
  193. updateXunfeiConfig("max_tokens", max_tokens)
  194. updateXunfeiConfig("app_id", app_id)
  195. updateXunfeiConfig("APIKey", APIKey)
  196. updateXunfeiConfig("APISecret", APISecret)
  197. updateXunfeiConfig("APIUrl", APIUrl)
  198. updateXunfeiConfig("domain", domain)
  199. res.send({ status: 200, msg: '设置成功!' })
  200. } catch (error) {
  201. res.send({ status: 500, msg: '设置失败!' })
  202. }
  203. })
  204. //获取机器人设置
  205. router.post('/getwxconfig', async (req, res) => {
  206. db.all('SELECT * FROM wxconfig', [], (err, rows) => {
  207. if (err) {
  208. res.send({ status: 500, msg: '查询失败!' })
  209. return
  210. }
  211. res.send({ status: 200, msg: rows })
  212. })
  213. })
  214. //设置微信机器人
  215. router.post('/wxconfig', async (req, res) => {
  216. const { autoReplySingle, suffix, prefix, atReply, keyWords, blackName, whiteRoom ,usemodel} = req.body
  217. try {
  218. setWx('autoReplySingle', autoReplySingle)
  219. setWx('suffix', suffix)
  220. setWx('prefix', prefix)
  221. setWx('whiteRoom', whiteRoom)
  222. setWx('atReply', atReply)
  223. setWx('keyWords', keyWords)
  224. setWx('blackName', blackName)
  225. setWx('usemodel', usemodel)
  226. loadConfigValues()
  227. res.send({ status: 200, msg: '设置成功!' })
  228. } catch (error) {
  229. res.send({ status: 500, msg: '设置失败!' })
  230. }
  231. })
  232. //获取消息发送记录
  233. router.post('/messagehistory',async (req,res)=>{
  234. db.all('SELECT * FROM message', [], (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('/clearmessage',async(req,res) => {
  244. db.run('DELETE FROM message', (err) => {
  245. if (err) {
  246. res.send({ status: 500, msg: '删除失败!' })
  247. } else {
  248. res.send({ status: 200, msg: '删除成功!' })
  249. }
  250. })
  251. })
  252. module.exports = router