Files
lv8girl/internal/services/message.go
nannanwu ddec422813 feat(core): 优化路径处理和配置端口并添加项目规范文档
- 将所有文件路径转换为 URL 友好格式,统一使用正斜杠,确保跨平台兼容
- 修改默认服务器监听端口为 :8989,提升默认配置适用性
- 数据库初始化时创建数据库文件夹,避免路径不存在导致错误
- 新增 AGENTS.md 文档,详细规范项目开发流程、代码风格、架构设计和安全性能指导
- 修正头像路径显示逻辑,确保头像 URL 正确展示
- 增加应用启动和开发的标准操作指南,提升团队协作效率
2026-02-24 20:44:05 +08:00

102 lines
2.6 KiB
Go

package services
import (
"path/filepath"
"lv8girl/internal/models"
"lv8girl/internal/repositories"
)
type MessageService struct {
messageRepo *repositories.MessageRepository
userRepo *repositories.UserRepository
}
func NewMessageService() *MessageService {
return &MessageService{
messageRepo: repositories.NewMessageRepository(),
userRepo: repositories.NewUserRepository(),
}
}
func (s *MessageService) SendMessage(fromUserID, toUserID uint, content string) error {
message := &models.PrivateMessage{
FromUserID: fromUserID,
ToUserID: toUserID,
Content: content,
IsRead: false,
}
return s.messageRepo.Create(message)
}
func (s *MessageService) GetUnreadCount(userID uint) (int64, error) {
return s.messageRepo.CountUnread(userID)
}
type ConversationView struct {
UserID uint
Username string
Avatar string
LastMsg string
Time string
Unread int64
}
func (s *MessageService) GetConversations(userID uint) ([]ConversationView, error) {
messages, err := s.messageRepo.FindConversations(userID)
if err != nil {
return nil, err
}
userMap := make(map[uint]bool)
for _, msg := range messages {
if msg.FromUserID != userID {
userMap[msg.FromUserID] = true
}
if msg.ToUserID != userID {
userMap[msg.ToUserID] = true
}
}
var conversations []ConversationView
for otherID := range userMap {
otherUser, err := s.userRepo.FindByID(otherID)
if err != nil {
continue
}
lastMsg, _ := s.messageRepo.FindLastMessage(userID, otherID)
unread, _ := s.messageRepo.CountUnreadFromUser(otherID, userID)
avatar := ""
if otherUser.Avatar != "" {
// 确保路径使用正斜杠,并添加前导斜杠
avatarPath := filepath.ToSlash(otherUser.Avatar)
avatar = "/" + avatarPath
}
conversations = append(conversations, ConversationView{
UserID: otherUser.ID,
Username: otherUser.Username,
Avatar: avatar,
LastMsg: lastMsg.Content,
Time: lastMsg.CreatedAt.Format("2006-01-02 15:04"),
Unread: unread,
})
}
return conversations, nil
}
func (s *MessageService) NotifyUserApproved(adminID, userID uint) error {
return s.SendMessage(adminID, userID, "恭喜!您的账号已通过管理员审核,现在可以正常登录使用了。")
}
func (s *MessageService) NotifyUserRejected(adminID, userID uint) error {
return s.SendMessage(adminID, userID, "您的账号审核未通过。如有疑问,请联系管理员。")
}
func (s *MessageService) NotifyUserBanned(adminID, userID uint) error {
return s.SendMessage(adminID, userID, "您的账号已被管理员封禁。如有疑问,请联系管理员。")
}