main.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. package main
  2. import (
  3. "log"
  4. "os"
  5. "path/filepath"
  6. "time"
  7. "github.com/2930134478/AI-CS/backend/controller"
  8. "github.com/2930134478/AI-CS/backend/infra"
  9. "github.com/2930134478/AI-CS/backend/middleware"
  10. "github.com/2930134478/AI-CS/backend/models"
  11. "github.com/2930134478/AI-CS/backend/repository"
  12. appRouter "github.com/2930134478/AI-CS/backend/router"
  13. "github.com/2930134478/AI-CS/backend/service"
  14. "github.com/2930134478/AI-CS/backend/websocket"
  15. "github.com/gin-gonic/gin"
  16. "github.com/joho/godotenv"
  17. "golang.org/x/crypto/bcrypt"
  18. )
  19. // 初始化默认管理员账号(如果不存在)
  20. // 默认账号:admin / admin123
  21. func initDefaultAdmin(userRepo *repository.UserRepository) {
  22. if _, err := userRepo.FindByUsername("admin"); err == nil {
  23. log.Println("✅ 管理员账号已存在")
  24. return
  25. }
  26. hash, err := bcrypt.GenerateFromPassword([]byte("admin123"), bcrypt.DefaultCost)
  27. if err != nil {
  28. log.Printf("⚠️ 创建默认管理员失败:密码加密错误 %v", err)
  29. return
  30. }
  31. admin := &models.User{
  32. Username: "admin",
  33. Password: string(hash),
  34. Role: "admin",
  35. }
  36. if err := userRepo.Create(admin); err != nil {
  37. log.Printf("⚠️ 创建默认管理员失败:%v", err)
  38. return
  39. }
  40. log.Println("✅ 默认管理员账号创建成功")
  41. log.Println(" 用户名: admin")
  42. log.Println(" 密码: admin123")
  43. log.Println(" ⚠️ 请首次登录后立即修改密码!")
  44. }
  45. func main() {
  46. // 加载 .env 文件
  47. // 获取当前工作目录
  48. wd, _ := os.Getwd()
  49. envPath := filepath.Join(wd, ".env")
  50. // 检查文件是否存在
  51. if _, err := os.Stat(envPath); os.IsNotExist(err) {
  52. log.Printf("⚠️ .env 文件不存在: %s", envPath)
  53. log.Println("当前工作目录:", wd)
  54. } else {
  55. log.Printf("✅ 找到 .env 文件: %s", envPath)
  56. }
  57. // 尝试加载 .env 文件
  58. // 注意:godotenv 不支持 UTF-8 BOM,如果文件有 BOM 会失败
  59. if err := godotenv.Load(envPath); err != nil {
  60. log.Printf("❌ 加载 .env 文件失败: %v", err)
  61. log.Println("⚠️ 提示:如果看到 'unexpected character' 错误,可能是文件编码问题(UTF-8 BOM)")
  62. log.Println(" 解决方法:用文本编辑器(如 VS Code)打开 .env,另存为 UTF-8 编码(不要 BOM)")
  63. log.Println("将使用系统环境变量")
  64. } else {
  65. log.Println("✅ .env 文件加载成功")
  66. }
  67. db, err := infra.NewDB()
  68. if err != nil {
  69. log.Fatalf("数据库连接失败:%v", err)
  70. }
  71. //根据结构体定义自动创建更新表
  72. if err := db.AutoMigrate(&models.User{}, &models.Conversation{}, &models.Message{}, &models.AIConfig{}, &models.FAQ{}); err != nil {
  73. log.Fatalf("自动创建表失败: %v", err)
  74. }
  75. userRepo := repository.NewUserRepository(db)
  76. conversationRepo := repository.NewConversationRepository(db)
  77. messageRepo := repository.NewMessageRepository(db)
  78. aiConfigRepo := repository.NewAIConfigRepository(db)
  79. faqRepo := repository.NewFAQRepository(db)
  80. // 初始化默认管理员账号(如果不存在)
  81. initDefaultAdmin(userRepo)
  82. //gin路由初始化
  83. r := gin.Default()
  84. //使用日志中间件
  85. r.Use(middleware.Logger())
  86. //跨域配置
  87. r.Use(middleware.CORS())
  88. // 初始化存储服务(本地存储)
  89. // 存储目录:backend/uploads(相对于工作目录)
  90. // 公共访问路径:/uploads(用于构建URL)
  91. // 复用之前获取的工作目录 wd(已在第 56 行声明)
  92. uploadDir := filepath.Join(wd, "uploads")
  93. publicPath := "/uploads"
  94. storageService := infra.NewLocalStorageService(uploadDir, publicPath)
  95. // 初始化服务层
  96. authService := service.NewAuthService(userRepo)
  97. conversationService := service.NewConversationService(conversationRepo, messageRepo, aiConfigRepo, userRepo)
  98. profileService := service.NewProfileService(userRepo, storageService)
  99. aiConfigService := service.NewAIConfigService(aiConfigRepo, userRepo)
  100. aiService := service.NewAIService(aiConfigRepo, messageRepo, conversationRepo)
  101. userService := service.NewUserService(userRepo) // 用户管理服务
  102. faqService := service.NewFAQService(faqRepo) // FAQ 管理服务
  103. // 声明 Hub 变量(用于在回调函数中访问)
  104. var wsHub *websocket.Hub
  105. // 创建 WebSocket Hub,设置回调函数来处理客户端连接/断开事件
  106. // 使用闭包来访问 conversationService、messageService、userRepo 和 wsHub
  107. onConnect := func(conversationID uint, isVisitor bool, visitorCount int, agentID uint) {
  108. if isVisitor {
  109. if err := conversationService.UpdateVisitorOnlineStatus(conversationID, true); err != nil {
  110. log.Printf("更新访客在线状态失败: %v", err)
  111. return
  112. }
  113. // 广播状态更新到所有客服端(不管连接到哪个对话)
  114. wsHub.BroadcastToAllAgents("visitor_status_update", map[string]interface{}{
  115. "conversation_id": conversationID,
  116. "is_online": true,
  117. "visitor_count": visitorCount,
  118. })
  119. } else if agentID > 0 {
  120. // 客服连接:创建系统消息 "{客服名}加入了会话"
  121. // 但需要检查是否已经存在该客服的加入消息,避免重复创建
  122. // 获取客服信息
  123. agent, err := userRepo.GetByID(agentID)
  124. if err != nil {
  125. log.Printf("获取客服信息失败: %v", err)
  126. return
  127. }
  128. // 确定显示名称:优先使用昵称,如果没有则使用用户名
  129. agentName := agent.Nickname
  130. if agentName == "" {
  131. agentName = agent.Username
  132. }
  133. // 检查是否已经存在该客服的加入消息
  134. hasJoinMessage, err := messageRepo.HasAgentJoinMessage(conversationID, agentID, agentName)
  135. if err != nil {
  136. log.Printf("检查客服加入消息失败: %v", err)
  137. return
  138. }
  139. // 如果已经存在加入消息,不再创建
  140. if hasJoinMessage {
  141. log.Printf("客服 %s 已经加入过对话 %d,跳过创建系统消息", agentName, conversationID)
  142. return
  143. }
  144. // 创建系统消息
  145. // 需要获取对话信息以确定当前模式
  146. conv, err := conversationRepo.GetByID(conversationID)
  147. if err != nil {
  148. log.Printf("获取对话信息失败: %v", err)
  149. return
  150. }
  151. now := time.Now()
  152. chatMode := conv.ChatMode
  153. if chatMode == "" {
  154. chatMode = "human" // 默认人工模式
  155. }
  156. systemMessage := &models.Message{
  157. ConversationID: conversationID,
  158. SenderID: agentID,
  159. SenderIsAgent: true,
  160. Content: agentName + "加入了会话",
  161. MessageType: "system_message",
  162. ChatMode: chatMode, // 记录系统消息发送时的对话模式
  163. IsRead: true, // 系统消息默认已读
  164. ReadAt: &now,
  165. }
  166. if err := messageRepo.Create(systemMessage); err != nil {
  167. log.Printf("创建客服加入系统消息失败: %v", err)
  168. return
  169. }
  170. // 延迟一小段时间后广播系统消息,确保客服的 WebSocket 连接已经完全建立
  171. // 这样可以确保系统消息能够被客服接收到
  172. go func() {
  173. time.Sleep(100 * time.Millisecond)
  174. wsHub.BroadcastMessage(conversationID, "new_message", systemMessage)
  175. log.Printf("✅ 客服加入系统消息已创建并广播: 对话ID=%d, 客服=%s", conversationID, agentName)
  176. }()
  177. }
  178. }
  179. onDisconnect := func(conversationID uint, isVisitor bool, visitorCount int) {
  180. if isVisitor {
  181. if visitorCount == 0 {
  182. if err := conversationService.UpdateVisitorOnlineStatus(conversationID, false); err != nil {
  183. log.Printf("更新访客离线状态失败: %v", err)
  184. return
  185. }
  186. // 广播状态更新到所有客服端(不管连接到哪个对话)
  187. wsHub.BroadcastToAllAgents("visitor_status_update", map[string]interface{}{
  188. "conversation_id": conversationID,
  189. "is_online": false,
  190. "visitor_count": 0,
  191. })
  192. } else {
  193. // 还有访客在线,只更新最后活跃时间
  194. if err := conversationService.UpdateLastSeenAt(conversationID); err != nil {
  195. log.Printf("更新最后活跃时间失败: %v", err)
  196. return
  197. }
  198. }
  199. }
  200. }
  201. // 创建 Hub(回调函数通过闭包访问 wsHub)
  202. wsHub = websocket.NewHub(onConnect, onDisconnect)
  203. go wsHub.Run() // 启动 Hub(在后台运行)
  204. messageService := service.NewMessageService(conversationRepo, messageRepo, wsHub, aiService)
  205. visitorService := service.NewVisitorService(userRepo, wsHub)
  206. // 初始化控制器
  207. authController := controller.NewAuthController(authService)
  208. conversationController := controller.NewConversationController(conversationService, aiConfigService)
  209. messageController := controller.NewMessageController(messageService, storageService)
  210. adminController := controller.NewAdminController(authService, userService)
  211. profileController := controller.NewProfileController(profileService)
  212. aiConfigController := controller.NewAIConfigController(aiConfigService)
  213. faqController := controller.NewFAQController(faqService)
  214. visitorController := controller.NewVisitorController(visitorService)
  215. appRouter.RegisterRoutes(
  216. r,
  217. appRouter.ControllerSet{
  218. Auth: authController,
  219. Conversation: conversationController,
  220. Message: messageController,
  221. Admin: adminController,
  222. Profile: profileController,
  223. AIConfig: aiConfigController,
  224. FAQ: faqController,
  225. Visitor: visitorController,
  226. },
  227. websocket.HandleWebSocket(wsHub),
  228. )
  229. // 配置静态文件服务(用于访问上传的头像等文件)
  230. // 静态文件路径:/uploads -> backend/uploads
  231. r.Static("/uploads", uploadDir)
  232. //启动服务器
  233. // 监听所有网络接口(0.0.0.0),允许外部设备访问
  234. // 如果只想本地访问,可以改为 "127.0.0.1:8080" 或 ":8080"
  235. host := os.Getenv("SERVER_HOST")
  236. if host == "" {
  237. host = "0.0.0.0" // 默认监听所有网络接口,允许外部访问
  238. }
  239. port := os.Getenv("SERVER_PORT")
  240. if port == "" {
  241. port = "8080"
  242. }
  243. addr := host + ":" + port
  244. log.Println("🚀 服务器启动成功,监听 " + addr)
  245. log.Println("📡 WebSocket 服务已启动,路径: /ws?conversation_id=<对话ID>")
  246. log.Println("💡 提示:如需限制为仅本地访问,请设置环境变量 SERVER_HOST=127.0.0.1")
  247. r.Run(addr)
  248. }