main.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "os"
  6. "path/filepath"
  7. "time"
  8. "github.com/2930134478/AI-CS/backend/controller"
  9. "github.com/2930134478/AI-CS/backend/infra"
  10. "github.com/2930134478/AI-CS/backend/middleware"
  11. "github.com/2930134478/AI-CS/backend/models"
  12. "github.com/2930134478/AI-CS/backend/repository"
  13. appRouter "github.com/2930134478/AI-CS/backend/router"
  14. "github.com/2930134478/AI-CS/backend/service"
  15. "github.com/2930134478/AI-CS/backend/service/embedding"
  16. "github.com/2930134478/AI-CS/backend/service/rag"
  17. "github.com/2930134478/AI-CS/backend/websocket"
  18. "github.com/gin-gonic/gin"
  19. "github.com/joho/godotenv"
  20. "golang.org/x/crypto/bcrypt"
  21. )
  22. // 初始化默认管理员账号(如果不存在)
  23. // 用户名从环境变量 ADMIN_USERNAME 读取(默认:admin)
  24. // 密码从环境变量 ADMIN_PASSWORD 读取(必须设置)
  25. func initDefaultAdmin(userRepo *repository.UserRepository) {
  26. // 从环境变量读取管理员用户名和密码
  27. adminUsername := os.Getenv("ADMIN_USERNAME")
  28. if adminUsername == "" {
  29. adminUsername = "admin" // 默认用户名
  30. }
  31. adminPassword := os.Getenv("ADMIN_PASSWORD")
  32. if adminPassword == "" {
  33. log.Println("⚠️ 警告:未设置 ADMIN_PASSWORD 环境变量,跳过创建默认管理员账号")
  34. log.Println(" 请在 .env 文件中设置 ADMIN_PASSWORD 后重启服务")
  35. return
  36. }
  37. // 检查管理员账号是否已存在
  38. if _, err := userRepo.FindByUsername(adminUsername); err == nil {
  39. log.Printf("✅ 管理员账号 '%s' 已存在", adminUsername)
  40. return
  41. }
  42. // 加密密码
  43. hash, err := bcrypt.GenerateFromPassword([]byte(adminPassword), bcrypt.DefaultCost)
  44. if err != nil {
  45. log.Printf("⚠️ 创建默认管理员失败:密码加密错误 %v", err)
  46. return
  47. }
  48. admin := &models.User{
  49. Username: adminUsername,
  50. Password: string(hash),
  51. Role: "admin",
  52. }
  53. if err := userRepo.Create(admin); err != nil {
  54. log.Printf("⚠️ 创建默认管理员失败:%v", err)
  55. return
  56. }
  57. log.Printf("✅ 默认管理员账号创建成功")
  58. log.Printf(" 用户名: %s", adminUsername)
  59. log.Println(" ⚠️ 请首次登录后立即修改密码!")
  60. }
  61. func main() {
  62. // 加载 .env 文件
  63. // 获取当前工作目录
  64. wd, _ := os.Getwd()
  65. envPath := filepath.Join(wd, ".env")
  66. // 检查文件是否存在
  67. if _, err := os.Stat(envPath); os.IsNotExist(err) {
  68. log.Printf("⚠️ .env 文件不存在: %s", envPath)
  69. log.Println("当前工作目录:", wd)
  70. } else {
  71. log.Printf("✅ 找到 .env 文件: %s", envPath)
  72. }
  73. // 尝试加载 .env 文件
  74. // 注意:godotenv 不支持 UTF-8 BOM,如果文件有 BOM 会失败
  75. if err := godotenv.Load(envPath); err != nil {
  76. log.Printf("❌ 加载 .env 文件失败: %v", err)
  77. log.Println("⚠️ 提示:如果看到 'unexpected character' 错误,可能是文件编码问题(UTF-8 BOM)")
  78. log.Println(" 解决方法:用文本编辑器(如 VS Code)打开 .env,另存为 UTF-8 编码(不要 BOM)")
  79. log.Println("将使用系统环境变量")
  80. } else {
  81. log.Println("✅ .env 文件加载成功")
  82. }
  83. db, err := infra.NewDB()
  84. if err != nil {
  85. log.Fatalf("数据库连接失败:%v", err)
  86. }
  87. //根据结构体定义自动创建更新表
  88. if err := db.AutoMigrate(&models.User{}, &models.Conversation{}, &models.Message{}, &models.AIConfig{}, &models.FAQ{}, &models.KnowledgeBase{}, &models.Document{}, &models.EmbeddingConfig{}); err != nil {
  89. log.Fatalf("自动创建表失败: %v", err)
  90. }
  91. userRepo := repository.NewUserRepository(db)
  92. conversationRepo := repository.NewConversationRepository(db)
  93. messageRepo := repository.NewMessageRepository(db)
  94. aiConfigRepo := repository.NewAIConfigRepository(db)
  95. faqRepo := repository.NewFAQRepository(db)
  96. kbRepo := repository.NewKnowledgeBaseRepository(db)
  97. docRepo := repository.NewDocumentRepository(db)
  98. embeddingConfigRepo := repository.NewEmbeddingConfigRepository(db)
  99. // 初始化默认管理员账号(如果不存在)
  100. initDefaultAdmin(userRepo)
  101. //gin路由初始化
  102. r := gin.Default()
  103. //使用日志中间件
  104. r.Use(middleware.Logger())
  105. //跨域配置
  106. r.Use(middleware.CORS())
  107. // 初始化存储服务(本地存储)
  108. // 存储目录:backend/uploads(相对于工作目录)
  109. // 公共访问路径:/uploads(用于构建URL)
  110. // 复用之前获取的工作目录 wd(已在第 56 行声明)
  111. uploadDir := filepath.Join(wd, "uploads")
  112. publicPath := "/uploads"
  113. storageService := infra.NewLocalStorageService(uploadDir, publicPath)
  114. // 初始化 Milvus 客户端(向量数据库)
  115. milvusClient, err := infra.NewMilvusClient()
  116. if err != nil {
  117. log.Fatalf("连接 Milvus 失败: %v", err)
  118. }
  119. defer milvusClient.Close()
  120. // 检查 Milvus 健康状态
  121. if err := infra.HealthCheck(milvusClient); err != nil {
  122. log.Fatalf("Milvus 健康检查失败: %v", err)
  123. }
  124. log.Println("✅ Milvus 连接成功")
  125. // 嵌入服务按需从 DB 配置获取(保存即生效,无需重启)
  126. embeddingConfigService := service.NewEmbeddingConfigService(embeddingConfigRepo, userRepo)
  127. embeddingFactory := embedding.NewEmbeddingFactory()
  128. embeddingProvider := service.NewConfigBackedEmbeddingProvider(embeddingConfigService, embeddingFactory)
  129. // 启动时获取一次维度用于创建/校验向量集合
  130. initCtx := context.Background()
  131. initSvc, _ := embeddingProvider.Get(initCtx)
  132. if initSvc != nil {
  133. log.Printf("✅ 嵌入服务按需从「知识库向量配置」加载,模型: %s (维度: %d),修改配置后立即生效", initSvc.GetModelName(), initSvc.GetDimension())
  134. } else {
  135. log.Printf("⚠️ 未配置嵌入服务;知识库/RAG 需在「设置 - 知识库向量模型」中配置 API 后再使用")
  136. }
  137. dimension := 1536
  138. if initSvc != nil {
  139. dimension = initSvc.GetDimension()
  140. }
  141. // 向量存储:迁移时通过 getEmbedding 从当前配置重新向量化
  142. getEmbedding := func(ctx context.Context) (infra.EmbeddingService, error) {
  143. svc, err := embeddingProvider.Get(ctx)
  144. if err != nil || svc == nil {
  145. return nil, err
  146. }
  147. return svc, nil
  148. }
  149. vectorStore, err := infra.NewVectorStore(milvusClient, "documents", dimension, getEmbedding)
  150. if err != nil {
  151. log.Fatalf("创建向量存储失败: %v", err)
  152. }
  153. vectorStoreService := rag.NewVectorStoreService(vectorStore)
  154. // 文档向量化 / RAG 检索 / 健康检查均使用 provider,配置保存即生效
  155. documentEmbeddingService := rag.NewDocumentEmbeddingService(vectorStoreService, embeddingProvider)
  156. retrievalService := rag.NewRetrievalService(vectorStoreService, embeddingProvider, docRepo, kbRepo)
  157. retrievalService.EnableCache(5 * time.Minute)
  158. healthChecker := rag.NewHealthChecker(embeddingProvider, vectorStoreService)
  159. // 初始化服务层
  160. authService := service.NewAuthService(userRepo)
  161. conversationService := service.NewConversationService(conversationRepo, messageRepo, aiConfigRepo, userRepo)
  162. profileService := service.NewProfileService(userRepo, storageService)
  163. aiConfigService := service.NewAIConfigService(aiConfigRepo, userRepo)
  164. aiService := service.NewAIService(aiConfigRepo, messageRepo, conversationRepo, retrievalService) // 添加 RAG 检索服务
  165. userService := service.NewUserService(userRepo) // 用户管理服务
  166. faqService := service.NewFAQService(faqRepo, retrievalService, documentEmbeddingService) // FAQ 管理服务
  167. documentService := service.NewDocumentService(docRepo, kbRepo, documentEmbeddingService, retrievalService) // 文档管理服务
  168. knowledgeBaseService := service.NewKnowledgeBaseService(kbRepo, docRepo) // 知识库管理服务
  169. importService := service.NewImportService(docRepo, kbRepo, documentService, documentEmbeddingService) // 导入服务
  170. // 声明 Hub 变量(用于在回调函数中访问)
  171. var wsHub *websocket.Hub
  172. // 创建 WebSocket Hub,设置回调函数来处理客户端连接/断开事件
  173. // 使用闭包来访问 conversationService、messageService、userRepo 和 wsHub
  174. onConnect := func(conversationID uint, isVisitor bool, visitorCount int, agentID uint) {
  175. if isVisitor {
  176. if err := conversationService.UpdateVisitorOnlineStatus(conversationID, true); err != nil {
  177. log.Printf("更新访客在线状态失败: %v", err)
  178. return
  179. }
  180. // 广播状态更新到所有客服端(不管连接到哪个对话)
  181. wsHub.BroadcastToAllAgents("visitor_status_update", map[string]interface{}{
  182. "conversation_id": conversationID,
  183. "is_online": true,
  184. "visitor_count": visitorCount,
  185. })
  186. } else if agentID > 0 {
  187. // 客服连接:创建系统消息 "{客服名}加入了会话"
  188. // 但需要检查是否已经存在该客服的加入消息,避免重复创建
  189. // 获取客服信息
  190. agent, err := userRepo.GetByID(agentID)
  191. if err != nil {
  192. log.Printf("获取客服信息失败: %v", err)
  193. return
  194. }
  195. // 确定显示名称:优先使用昵称,如果没有则使用用户名
  196. agentName := agent.Nickname
  197. if agentName == "" {
  198. agentName = agent.Username
  199. }
  200. // 检查是否已经存在该客服的加入消息
  201. hasJoinMessage, err := messageRepo.HasAgentJoinMessage(conversationID, agentID, agentName)
  202. if err != nil {
  203. log.Printf("检查客服加入消息失败: %v", err)
  204. return
  205. }
  206. // 如果已经存在加入消息,不再创建
  207. if hasJoinMessage {
  208. log.Printf("客服 %s 已经加入过对话 %d,跳过创建系统消息", agentName, conversationID)
  209. return
  210. }
  211. // 创建系统消息
  212. // 需要获取对话信息以确定当前模式
  213. conv, err := conversationRepo.GetByID(conversationID)
  214. if err != nil {
  215. log.Printf("获取对话信息失败: %v", err)
  216. return
  217. }
  218. now := time.Now()
  219. chatMode := conv.ChatMode
  220. if chatMode == "" {
  221. chatMode = "human" // 默认人工模式
  222. }
  223. systemMessage := &models.Message{
  224. ConversationID: conversationID,
  225. SenderID: agentID,
  226. SenderIsAgent: true,
  227. Content: agentName + "加入了会话",
  228. MessageType: "system_message",
  229. ChatMode: chatMode, // 记录系统消息发送时的对话模式
  230. IsRead: true, // 系统消息默认已读
  231. ReadAt: &now,
  232. }
  233. if err := messageRepo.Create(systemMessage); err != nil {
  234. log.Printf("创建客服加入系统消息失败: %v", err)
  235. return
  236. }
  237. // 延迟一小段时间后广播系统消息,确保客服的 WebSocket 连接已经完全建立
  238. // 这样可以确保系统消息能够被客服接收到
  239. go func() {
  240. time.Sleep(100 * time.Millisecond)
  241. wsHub.BroadcastMessage(conversationID, "new_message", systemMessage)
  242. log.Printf("✅ 客服加入系统消息已创建并广播: 对话ID=%d, 客服=%s", conversationID, agentName)
  243. }()
  244. }
  245. }
  246. onDisconnect := func(conversationID uint, isVisitor bool, visitorCount int) {
  247. if isVisitor {
  248. if visitorCount == 0 {
  249. if err := conversationService.UpdateVisitorOnlineStatus(conversationID, false); err != nil {
  250. log.Printf("更新访客离线状态失败: %v", err)
  251. return
  252. }
  253. // 广播状态更新到所有客服端(不管连接到哪个对话)
  254. wsHub.BroadcastToAllAgents("visitor_status_update", map[string]interface{}{
  255. "conversation_id": conversationID,
  256. "is_online": false,
  257. "visitor_count": 0,
  258. })
  259. } else {
  260. // 还有访客在线,只更新最后活跃时间
  261. if err := conversationService.UpdateLastSeenAt(conversationID); err != nil {
  262. log.Printf("更新最后活跃时间失败: %v", err)
  263. return
  264. }
  265. }
  266. }
  267. }
  268. // 创建 Hub(回调函数通过闭包访问 wsHub)
  269. wsHub = websocket.NewHub(onConnect, onDisconnect)
  270. go wsHub.Run() // 启动 Hub(在后台运行)
  271. messageService := service.NewMessageService(conversationRepo, messageRepo, wsHub, aiService)
  272. visitorService := service.NewVisitorService(userRepo, wsHub)
  273. // 初始化控制器
  274. authController := controller.NewAuthController(authService)
  275. conversationController := controller.NewConversationController(conversationService, aiConfigService)
  276. messageController := controller.NewMessageController(messageService, storageService)
  277. adminController := controller.NewAdminController(authService, userService)
  278. profileController := controller.NewProfileController(profileService)
  279. aiConfigController := controller.NewAIConfigController(aiConfigService)
  280. faqController := controller.NewFAQController(faqService)
  281. documentController := controller.NewDocumentController(documentService, embeddingConfigService)
  282. embeddingConfigController := controller.NewEmbeddingConfigController(embeddingConfigService)
  283. knowledgeBaseController := controller.NewKnowledgeBaseController(knowledgeBaseService, embeddingConfigService)
  284. importController := controller.NewImportController(importService, embeddingConfigService) // 导入控制器
  285. visitorController := controller.NewVisitorController(visitorService)
  286. healthController := controller.NewHealthController(healthChecker, retrievalService) // 健康检查控制器
  287. appRouter.RegisterRoutes(
  288. r,
  289. appRouter.ControllerSet{
  290. Auth: authController,
  291. Conversation: conversationController,
  292. Message: messageController,
  293. Admin: adminController,
  294. Profile: profileController,
  295. AIConfig: aiConfigController,
  296. EmbeddingConfig: embeddingConfigController,
  297. FAQ: faqController,
  298. Document: documentController,
  299. KnowledgeBase: knowledgeBaseController,
  300. Import: importController, // 导入控制器
  301. Visitor: visitorController,
  302. Health: healthController, // 健康检查控制器
  303. },
  304. websocket.HandleWebSocket(wsHub),
  305. )
  306. // 配置静态文件服务(用于访问上传的头像等文件)
  307. // 静态文件路径:/uploads -> backend/uploads
  308. r.Static("/uploads", uploadDir)
  309. //启动服务器
  310. // 监听所有网络接口(0.0.0.0),允许外部设备访问
  311. // 如果只想本地访问,可以改为 "127.0.0.1:8080" 或 ":8080"
  312. host := os.Getenv("SERVER_HOST")
  313. if host == "" {
  314. host = "0.0.0.0" // 默认监听所有网络接口,允许外部访问
  315. }
  316. port := os.Getenv("SERVER_PORT")
  317. if port == "" {
  318. port = "8080"
  319. }
  320. addr := host + ":" + port
  321. log.Println("🚀 服务器启动成功,监听 " + addr)
  322. log.Println("📡 WebSocket 服务已启动,路径: /ws?conversation_id=<对话ID>")
  323. log.Println("💡 提示:如需限制为仅本地访问,请设置环境变量 SERVER_HOST=127.0.0.1")
  324. r.Run(addr)
  325. }