Files
mce/internal/controller/settings_api_notify.go

80 lines
1.9 KiB
Go

package controller
import (
"net/http"
"metazone.cc/mce/internal/common"
"metazone.cc/mce/internal/model"
"github.com/gin-gonic/gin"
)
// SetNotifyPrefReader 注入通知偏好读写器
func (sc *SettingsController) SetNotifyPrefReader(reader notifyPrefReader) {
sc.notifyPrefReader = reader
}
// GetNotifyPrefs 获取通知偏好 GET /api/settings/notify-prefs
func (sc *SettingsController) GetNotifyPrefs(c *gin.Context) {
uid, exists := c.Get("uid")
if !exists {
common.Error(c, http.StatusUnauthorized, "请先登录")
return
}
if sc.notifyPrefReader == nil {
common.Error(c, http.StatusInternalServerError, "服务不可用")
return
}
prefs, err := sc.notifyPrefReader.GetNotifyPrefs(uid.(uint))
if err != nil {
common.Error(c, http.StatusInternalServerError, "获取失败")
return
}
common.Ok(c, prefs)
}
// UpdateNotifyPref 更新通知偏好 PUT /api/settings/notify-prefs
func (sc *SettingsController) UpdateNotifyPref(c *gin.Context) {
uid, exists := c.Get("uid")
if !exists {
common.Error(c, http.StatusUnauthorized, "请先登录")
return
}
if sc.notifyPrefReader == nil {
common.Error(c, http.StatusInternalServerError, "服务不可用")
return
}
var req struct {
Key string `json:"key"`
Enabled bool `json:"enabled"`
}
if err := c.ShouldBindJSON(&req); err != nil {
common.Error(c, http.StatusBadRequest, "参数错误")
return
}
// 验证 key 是否合法
allowedKeys := map[string]bool{
model.NotifyComment: true,
model.NotifyCommentReply: true,
model.NotifyLikeAggregated: true,
model.NotifyFollow: true,
}
if !allowedKeys[req.Key] {
common.Error(c, http.StatusBadRequest, "无效的通知类型")
return
}
if err := sc.notifyPrefReader.UpdateNotifyPref(uid.(uint), req.Key, req.Enabled); err != nil {
common.Error(c, http.StatusInternalServerError, "更新失败")
return
}
common.OkMessage(c, "通知偏好已更新")
}