SummaryFile.js 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. const API = require("../../lib/API")
  2. const AccessControl = require("../../lib/AccessControl")
  3. const { BaseStdResponse } = require("../../BaseStdResponse")
  4. const db = require("../../plugin/DataBase/db")
  5. const axios = require('axios')
  6. const { core_url } = require('../../config.json')
  7. const path = require('path')
  8. const { isBinaryFileSync } = require('isbinaryfile')
  9. class SummaryFile extends API {
  10. constructor() {
  11. super()
  12. this.setMethod("GET")
  13. this.setPath("/AI/SummaryFile")
  14. }
  15. isBinaryFile(filePath) {
  16. try {
  17. return isBinaryFileSync(filePath)
  18. } catch (err) {
  19. return false
  20. }
  21. }
  22. async onRequest(req, res) {
  23. let { uuid, session, id, hash, filePath } = req.query
  24. if ([uuid, session, id, hash, filePath].some(value => value === '' || value === null || value === undefined))
  25. return res.json({
  26. ...BaseStdResponse.MISSING_PARAMETER
  27. })
  28. // 检查 session
  29. if (!await AccessControl.checkSession(uuid, session))
  30. return res.status(401).json({
  31. ...BaseStdResponse.ACCESS_DENIED
  32. })
  33. let sql = 'SELECT state, path, url FROM repos WHERE create_user = ? AND id = ?'
  34. let rows = await db.query(sql, [uuid, id])
  35. if (!rows || rows.length === 0)
  36. return res.json({
  37. ...BaseStdResponse.ERR,
  38. msg: '未找到仓库'
  39. })
  40. if (rows[0].state !== 1 || !rows[0].path)
  41. return res.json({
  42. ...BaseStdResponse.ERR,
  43. msg: '仓库未成功克隆!'
  44. })
  45. try {
  46. filePath = path.join(rows[0].path, filePath)
  47. if(this.isBinaryFile(filePath))
  48. return res.json({
  49. ...BaseStdResponse.ERR,
  50. msg: '该文件类型不支持AI总结!'
  51. })
  52. const time = new Date().getTime()
  53. sql = 'INSERT INTO file_summary_tasks (repo_id, create_time, create_user, repo_hash, filepath) VALUES (?, ?, ?, ?, ?)'
  54. let r = await db.query(sql, [id, time, uuid, hash, filePath, 'hand'])
  55. if (!r || r.affectedRows !== 1)
  56. return res.json({
  57. ...BaseStdResponse.ERR,
  58. msg: '扫描任务添加失败!'
  59. })
  60. res.json({
  61. ...BaseStdResponse.OK
  62. })
  63. let endpoint = core_url + '/ai/summaryFile'
  64. await axios.post(endpoint, { uuid, repo_url: rows[0].url, task_id: String(r.insertId), file_path: filePath })
  65. } catch (error) {
  66. this.logger.error('添加AI分析任务失败!' + error.stack)
  67. return res.json({
  68. ...BaseStdResponse.ERR,
  69. msg: '添加AI分析任务失败!'
  70. })
  71. }
  72. }
  73. }
  74. module.exports.SummaryFile = SummaryFile