router.js 9.8 KB

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