feat: 后台增加开放消息开关
关闭后前台隐藏私聊/群聊入口并由后端拦截;同步去掉公告页重复计数胶囊。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -279,7 +279,12 @@ func (h *Handlers) Me(c *gin.Context) {
|
|||||||
if n, err := h.Notification.UnreadCount(claims.ID); err == nil {
|
if n, err := h.Notification.UnreadCount(claims.ID); err == nil {
|
||||||
unread = n
|
unread = n
|
||||||
}
|
}
|
||||||
chatUnread := h.Chat.TotalUnread(claims.ID)
|
chatUnread := int64(0)
|
||||||
|
if h.Setting != nil && h.Chat != nil {
|
||||||
|
if allow, err := h.Setting.AllowMessages(); err == nil && allow {
|
||||||
|
chatUnread = h.Chat.TotalUnread(claims.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
// 板块管理员带出授权板块,供前端菜单/按钮按板块范围渲染
|
// 板块管理员带出授权板块,供前端菜单/按钮按板块范围渲染
|
||||||
var boardIDs []uint
|
var boardIDs []uint
|
||||||
if user.Role == model.RoleBoardAdmin {
|
if user.Role == model.RoleBoardAdmin {
|
||||||
|
|||||||
@@ -47,6 +47,24 @@ func (h *Handlers) chatOversee(userID uint) bool {
|
|||||||
return service.CanOverseeChat(actor.Role)
|
return service.CanOverseeChat(actor.Role)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RequireMessagesOpen 前台群聊/私聊闸门;关闭后一律 403。管理端 /api/admin/chat 不受影响。
|
||||||
|
func (h *Handlers) RequireMessagesOpen(c *gin.Context) {
|
||||||
|
if h.Setting == nil {
|
||||||
|
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "消息暂时不可用"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
allow, err := h.Setting.AllowMessages()
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "消息暂时不可用"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !allow {
|
||||||
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "本站不支持消息"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
|
||||||
// CreateChatRoom 建群(可公开/私密,私密可带初始成员)
|
// CreateChatRoom 建群(可公开/私密,私密可带初始成员)
|
||||||
func (h *Handlers) CreateChatRoom(c *gin.Context) {
|
func (h *Handlers) CreateChatRoom(c *gin.Context) {
|
||||||
claims := middleware.CurrentUser(c)
|
claims := middleware.CurrentUser(c)
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ type updateSettingsRequest struct {
|
|||||||
SiteDescription *string `json:"site_description"`
|
SiteDescription *string `json:"site_description"`
|
||||||
AllowRegister *bool `json:"allow_register"`
|
AllowRegister *bool `json:"allow_register"`
|
||||||
AllowComments *bool `json:"allow_comments"`
|
AllowComments *bool `json:"allow_comments"`
|
||||||
|
AllowMessages *bool `json:"allow_messages"`
|
||||||
PostCooldownHours *int `json:"post_cooldown_hours"`
|
PostCooldownHours *int `json:"post_cooldown_hours"`
|
||||||
CodeBlockAutoFold *bool `json:"code_block_auto_fold"`
|
CodeBlockAutoFold *bool `json:"code_block_auto_fold"`
|
||||||
CodeBlockFoldLines *int `json:"code_block_fold_lines"`
|
CodeBlockFoldLines *int `json:"code_block_fold_lines"`
|
||||||
@@ -45,6 +46,7 @@ func settingsPayload(saved service.PublicSiteSettings) gin.H {
|
|||||||
"site_description": saved.SiteDescription,
|
"site_description": saved.SiteDescription,
|
||||||
"allow_register": saved.AllowRegister,
|
"allow_register": saved.AllowRegister,
|
||||||
"allow_comments": saved.AllowComments,
|
"allow_comments": saved.AllowComments,
|
||||||
|
"allow_messages": saved.AllowMessages,
|
||||||
"post_cooldown_hours": saved.PostCooldownHours,
|
"post_cooldown_hours": saved.PostCooldownHours,
|
||||||
"code_block_auto_fold": saved.CodeBlockAutoFold,
|
"code_block_auto_fold": saved.CodeBlockAutoFold,
|
||||||
"code_block_fold_lines": saved.CodeBlockFoldLines,
|
"code_block_fold_lines": saved.CodeBlockFoldLines,
|
||||||
@@ -65,6 +67,7 @@ func (h *Handlers) UpdateSettings(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
if req.Accent == nil && req.TrustReviewedPublish == nil && req.SiteName == nil &&
|
if req.Accent == nil && req.TrustReviewedPublish == nil && req.SiteName == nil &&
|
||||||
req.SiteDescription == nil && req.AllowRegister == nil && req.AllowComments == nil &&
|
req.SiteDescription == nil && req.AllowRegister == nil && req.AllowComments == nil &&
|
||||||
|
req.AllowMessages == nil &&
|
||||||
req.PostCooldownHours == nil && req.CodeBlockAutoFold == nil && req.CodeBlockFoldLines == nil &&
|
req.PostCooldownHours == nil && req.CodeBlockAutoFold == nil && req.CodeBlockFoldLines == nil &&
|
||||||
req.UIAnimations == nil && req.AnimCodeFold == nil && req.AnimSmoothScroll == nil &&
|
req.UIAnimations == nil && req.AnimCodeFold == nil && req.AnimSmoothScroll == nil &&
|
||||||
req.AnimChrome == nil && req.PostLinkNewTab == nil {
|
req.AnimChrome == nil && req.PostLinkNewTab == nil {
|
||||||
@@ -120,6 +123,12 @@ func (h *Handlers) UpdateSettings(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if req.AllowMessages != nil {
|
||||||
|
if err := h.Setting.SetAllowMessages(*req.AllowMessages); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存站点设置失败"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
if req.PostCooldownHours != nil {
|
if req.PostCooldownHours != nil {
|
||||||
if err := h.Setting.SetPostCooldownHours(*req.PostCooldownHours); err != nil {
|
if err := h.Setting.SetPostCooldownHours(*req.PostCooldownHours); err != nil {
|
||||||
if errors.Is(err, service.ErrInvalidSiteSetting) {
|
if errors.Is(err, service.ErrInvalidSiteSetting) {
|
||||||
|
|||||||
@@ -179,25 +179,28 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
|||||||
api.GET("/my/media", h.MyMedia)
|
api.GET("/my/media", h.MyMedia)
|
||||||
api.DELETE("/my/attachments/:id", h.DeleteAttachment)
|
api.DELETE("/my/attachments/:id", h.DeleteAttachment)
|
||||||
|
|
||||||
// 群聊(二期):建群/成员/消息/未读
|
// 群聊(二期):建群/成员/消息/未读;全站关闭消息时前台一律 403
|
||||||
api.GET("/chat/rooms", h.ListChatRooms)
|
chatAPI := api.Group("/chat", h.RequireMessagesOpen)
|
||||||
api.POST("/chat/rooms", h.CreateChatRoom)
|
{
|
||||||
api.POST("/chat/direct", h.OpenDirectChat)
|
chatAPI.GET("/rooms", h.ListChatRooms)
|
||||||
api.GET("/chat/users", h.SearchChatUsers)
|
chatAPI.POST("/rooms", h.CreateChatRoom)
|
||||||
api.GET("/chat/rooms/:id", h.GetChatRoom)
|
chatAPI.POST("/direct", h.OpenDirectChat)
|
||||||
api.PUT("/chat/rooms/:id", h.UpdateChatRoom)
|
chatAPI.GET("/users", h.SearchChatUsers)
|
||||||
api.PUT("/chat/rooms/:id/pin", h.PinChatRoom)
|
chatAPI.GET("/rooms/:id", h.GetChatRoom)
|
||||||
api.DELETE("/chat/rooms/:id", h.DissolveChatRoom)
|
chatAPI.PUT("/rooms/:id", h.UpdateChatRoom)
|
||||||
api.POST("/chat/rooms/:id/join", h.JoinChatRoom)
|
chatAPI.PUT("/rooms/:id/pin", h.PinChatRoom)
|
||||||
api.POST("/chat/rooms/:id/leave", h.LeaveChatRoom)
|
chatAPI.DELETE("/rooms/:id", h.DissolveChatRoom)
|
||||||
api.GET("/chat/rooms/:id/members", h.ListChatMembers)
|
chatAPI.POST("/rooms/:id/join", h.JoinChatRoom)
|
||||||
api.POST("/chat/rooms/:id/members", h.InviteChatMembers)
|
chatAPI.POST("/rooms/:id/leave", h.LeaveChatRoom)
|
||||||
api.DELETE("/chat/rooms/:id/members/:uid", h.KickChatMember)
|
chatAPI.GET("/rooms/:id/members", h.ListChatMembers)
|
||||||
api.GET("/chat/rooms/:id/messages", h.ListChatMessages)
|
chatAPI.POST("/rooms/:id/members", h.InviteChatMembers)
|
||||||
api.POST("/chat/rooms/:id/messages", middleware.RateLimitMiddleware(limiter, service.RateChat), h.SendChatMessage)
|
chatAPI.DELETE("/rooms/:id/members/:uid", h.KickChatMember)
|
||||||
api.DELETE("/chat/rooms/:id/messages/:mid", h.RecallChatMessage)
|
chatAPI.GET("/rooms/:id/messages", h.ListChatMessages)
|
||||||
api.PUT("/chat/rooms/:id/read", h.MarkChatRead)
|
chatAPI.POST("/rooms/:id/messages", middleware.RateLimitMiddleware(limiter, service.RateChat), h.SendChatMessage)
|
||||||
api.GET("/chat/unread-summary", h.ChatUnreadSummary)
|
chatAPI.DELETE("/rooms/:id/messages/:mid", h.RecallChatMessage)
|
||||||
|
chatAPI.PUT("/rooms/:id/read", h.MarkChatRead)
|
||||||
|
chatAPI.GET("/unread-summary", h.ChatUnreadSummary)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 管理后台 API:RequireStaff 基础鉴权(板块管理员及以上,Actor 实时从 DB 现取),
|
// 管理后台 API:RequireStaff 基础鉴权(板块管理员及以上,Actor 实时从 DB 现取),
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ const (
|
|||||||
SettingKeyAllowRegister = "allow_register"
|
SettingKeyAllowRegister = "allow_register"
|
||||||
// SettingKeyAllowComments 全站开放评论;缺行视为开启(默认开)
|
// SettingKeyAllowComments 全站开放评论;缺行视为开启(默认开)
|
||||||
SettingKeyAllowComments = "allow_comments"
|
SettingKeyAllowComments = "allow_comments"
|
||||||
|
// SettingKeyAllowMessages 全站开放私聊/群聊;缺行视为开启(默认开)
|
||||||
|
SettingKeyAllowMessages = "allow_messages"
|
||||||
SettingKeyPostCooldownHours = "post_cooldown_hours"
|
SettingKeyPostCooldownHours = "post_cooldown_hours"
|
||||||
// SettingKeyCodeBlockAutoFold 代码块自动折叠;缺行视为开启
|
// SettingKeyCodeBlockAutoFold 代码块自动折叠;缺行视为开启
|
||||||
SettingKeyCodeBlockAutoFold = "code_block_auto_fold"
|
SettingKeyCodeBlockAutoFold = "code_block_auto_fold"
|
||||||
@@ -67,6 +69,7 @@ type PublicSiteSettings struct {
|
|||||||
SiteDescription string `json:"site_description"`
|
SiteDescription string `json:"site_description"`
|
||||||
AllowRegister bool `json:"allow_register"`
|
AllowRegister bool `json:"allow_register"`
|
||||||
AllowComments bool `json:"allow_comments"`
|
AllowComments bool `json:"allow_comments"`
|
||||||
|
AllowMessages bool `json:"allow_messages"`
|
||||||
PostCooldownHours int `json:"post_cooldown_hours"`
|
PostCooldownHours int `json:"post_cooldown_hours"`
|
||||||
CodeBlockAutoFold bool `json:"code_block_auto_fold"`
|
CodeBlockAutoFold bool `json:"code_block_auto_fold"`
|
||||||
CodeBlockFoldLines int `json:"code_block_fold_lines"`
|
CodeBlockFoldLines int `json:"code_block_fold_lines"`
|
||||||
@@ -135,6 +138,7 @@ func (s *SettingService) Public() (PublicSiteSettings, error) {
|
|||||||
TrustReviewedPublish: true,
|
TrustReviewedPublish: true,
|
||||||
AllowRegister: true,
|
AllowRegister: true,
|
||||||
AllowComments: true,
|
AllowComments: true,
|
||||||
|
AllowMessages: true,
|
||||||
PostCooldownHours: DefaultCooldownHours,
|
PostCooldownHours: DefaultCooldownHours,
|
||||||
CodeBlockAutoFold: true,
|
CodeBlockAutoFold: true,
|
||||||
CodeBlockFoldLines: DefaultCodeFoldLines,
|
CodeBlockFoldLines: DefaultCodeFoldLines,
|
||||||
@@ -187,6 +191,12 @@ func (s *SettingService) Public() (PublicSiteSettings, error) {
|
|||||||
}
|
}
|
||||||
out.AllowComments = comments
|
out.AllowComments = comments
|
||||||
|
|
||||||
|
messages, err := s.AllowMessages()
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
out.AllowMessages = messages
|
||||||
|
|
||||||
hours, err := s.PostCooldownHours()
|
hours, err := s.PostCooldownHours()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return out, err
|
return out, err
|
||||||
@@ -320,6 +330,20 @@ func (s *SettingService) SetAllowComments(on bool) error {
|
|||||||
return s.setBoolDefaultTrue(SettingKeyAllowComments, on)
|
return s.setBoolDefaultTrue(SettingKeyAllowComments, on)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AllowMessages 是否允许全站私聊/群聊。缺行视为开启。
|
||||||
|
func (s *SettingService) AllowMessages() (bool, error) {
|
||||||
|
v, found, err := s.getValue(SettingKeyAllowMessages)
|
||||||
|
if err != nil {
|
||||||
|
return true, err
|
||||||
|
}
|
||||||
|
return parseBoolDefaultTrue(v, found), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetAllowMessages 持久化消息开关;开启时删键保持「缺行=默认开」。
|
||||||
|
func (s *SettingService) SetAllowMessages(on bool) error {
|
||||||
|
return s.setBoolDefaultTrue(SettingKeyAllowMessages, on)
|
||||||
|
}
|
||||||
|
|
||||||
// PostCooldownHours 新用户发帖冷静期(小时)。缺行=24;0 表示关闭。
|
// PostCooldownHours 新用户发帖冷静期(小时)。缺行=24;0 表示关闭。
|
||||||
func (s *SettingService) PostCooldownHours() (int, error) {
|
func (s *SettingService) PostCooldownHours() (int, error) {
|
||||||
v, found, err := s.getValue(SettingKeyPostCooldownHours)
|
v, found, err := s.getValue(SettingKeyPostCooldownHours)
|
||||||
|
|||||||
@@ -334,28 +334,7 @@ export default function AnnouncementAdmin({
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* 计数条 */}
|
<div className="mb-4">
|
||||||
<div className="flex items-center gap-3 mb-4 flex-wrap">
|
|
||||||
<div
|
|
||||||
className="inline-flex items-center gap-4 rounded-lg px-3.5 py-2 text-[13px]"
|
|
||||||
style={{ background: "var(--panel-2)", color: "var(--ink-2)" }}
|
|
||||||
>
|
|
||||||
<span>
|
|
||||||
草稿{" "}
|
|
||||||
<strong className="tabular-nums" style={{ color: "var(--ink)" }}>
|
|
||||||
{draftCount}
|
|
||||||
</strong>
|
|
||||||
</span>
|
|
||||||
<span aria-hidden style={{ color: "var(--line)" }}>
|
|
||||||
|
|
|
||||||
</span>
|
|
||||||
<span>
|
|
||||||
已发布{" "}
|
|
||||||
<strong className="tabular-nums" style={{ color: "var(--ink)" }}>
|
|
||||||
{publishedCount}
|
|
||||||
</strong>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<AdminSegmented<StatusFilter>
|
<AdminSegmented<StatusFilter>
|
||||||
ariaLabel="公告状态筛选"
|
ariaLabel="公告状态筛选"
|
||||||
size="sm"
|
size="sm"
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
MessageSquare,
|
MessageSquare,
|
||||||
Save,
|
Save,
|
||||||
UserPlus,
|
UserPlus,
|
||||||
|
MessagesSquare,
|
||||||
ExternalLink,
|
ExternalLink,
|
||||||
Shield,
|
Shield,
|
||||||
Mail,
|
Mail,
|
||||||
@@ -107,12 +108,14 @@ export default function SettingsAdmin({ initial }: { initial: PublicSettings })
|
|||||||
const [siteDescription, setSiteDescription] = useState(initial.site_description);
|
const [siteDescription, setSiteDescription] = useState(initial.site_description);
|
||||||
const [allowRegister, setAllowRegister] = useState(initial.allow_register);
|
const [allowRegister, setAllowRegister] = useState(initial.allow_register);
|
||||||
const [allowComments, setAllowComments] = useState(initial.allow_comments !== false);
|
const [allowComments, setAllowComments] = useState(initial.allow_comments !== false);
|
||||||
|
const [allowMessages, setAllowMessages] = useState(initial.allow_messages !== false);
|
||||||
const [postLinkNewTab, setPostLinkNewTab] = useState(initial.post_link_new_tab !== false);
|
const [postLinkNewTab, setPostLinkNewTab] = useState(initial.post_link_new_tab !== false);
|
||||||
const [savedName, setSavedName] = useState(initial.site_name);
|
const [savedName, setSavedName] = useState(initial.site_name);
|
||||||
const [savedDesc, setSavedDesc] = useState(initial.site_description);
|
const [savedDesc, setSavedDesc] = useState(initial.site_description);
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [togglingReg, setTogglingReg] = useState(false);
|
const [togglingReg, setTogglingReg] = useState(false);
|
||||||
const [togglingComments, setTogglingComments] = useState(false);
|
const [togglingComments, setTogglingComments] = useState(false);
|
||||||
|
const [togglingMessages, setTogglingMessages] = useState(false);
|
||||||
const [togglingLink, setTogglingLink] = useState(false);
|
const [togglingLink, setTogglingLink] = useState(false);
|
||||||
const [active, setActive] = useState<SectionId>("basic");
|
const [active, setActive] = useState<SectionId>("basic");
|
||||||
|
|
||||||
@@ -199,6 +202,21 @@ export default function SettingsAdmin({ initial }: { initial: PublicSettings })
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const toggleMessages = async () => {
|
||||||
|
if (togglingMessages) return;
|
||||||
|
const next = !allowMessages;
|
||||||
|
setTogglingMessages(true);
|
||||||
|
try {
|
||||||
|
const res = await apiUpdateSiteSettings({ allow_messages: next });
|
||||||
|
setAllowMessages(res.allow_messages);
|
||||||
|
toast(res.allow_messages ? "已开放消息" : "已关闭消息", "ok");
|
||||||
|
} catch (e) {
|
||||||
|
toast(e instanceof Error ? e.message : "保存失败");
|
||||||
|
} finally {
|
||||||
|
setTogglingMessages(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const togglePostLinkNewTab = async () => {
|
const togglePostLinkNewTab = async () => {
|
||||||
if (togglingLink) return;
|
if (togglingLink) return;
|
||||||
const next = !postLinkNewTab;
|
const next = !postLinkNewTab;
|
||||||
@@ -293,7 +311,7 @@ export default function SettingsAdmin({ initial }: { initial: PublicSettings })
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="settings-content" className="scroll-mt-4">
|
<div id="settings-content" className="scroll-mt-4">
|
||||||
<AdminSection title="内容与互动" description="控制注册、评论与链接打开方式">
|
<AdminSection title="内容与互动" description="控制注册、评论、消息与链接打开方式">
|
||||||
<SwitchRow
|
<SwitchRow
|
||||||
bordered
|
bordered
|
||||||
title={
|
title={
|
||||||
@@ -328,6 +346,23 @@ export default function SettingsAdmin({ initial }: { initial: PublicSettings })
|
|||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
<SwitchRow
|
||||||
|
bordered
|
||||||
|
title={
|
||||||
|
<>
|
||||||
|
<MessagesSquare size={15} /> 开放消息
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
description="关闭后前台不展示私聊与群聊入口;已有会话由后台消息管理继续监管。"
|
||||||
|
control={
|
||||||
|
<AdminSwitch
|
||||||
|
checked={allowMessages}
|
||||||
|
disabled={togglingMessages}
|
||||||
|
onChange={() => void toggleMessages()}
|
||||||
|
label="开放消息"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
<SwitchRow
|
<SwitchRow
|
||||||
title={
|
title={
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -2,10 +2,11 @@ import type { Metadata } from "next";
|
|||||||
import { notFound, redirect } from "next/navigation";
|
import { notFound, redirect } from "next/navigation";
|
||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
import { authCookieHeader } from "@/lib/cookies";
|
import { authCookieHeader } from "@/lib/cookies";
|
||||||
import { getMeCached } from "@/lib/serverData";
|
import { getMeCached, getPublicSettingsCached } from "@/lib/serverData";
|
||||||
import { fetchChatRoom, fetchChatMessages, fetchChatRooms } from "@/lib/api";
|
import { fetchChatRoom, fetchChatMessages, fetchChatRooms } from "@/lib/api";
|
||||||
import ChatShell from "../ChatShell";
|
import ChatShell from "../ChatShell";
|
||||||
import ChatRoomClient from "./ChatRoomClient";
|
import ChatRoomClient from "./ChatRoomClient";
|
||||||
|
import MessagesUnsupported from "@/components/MessagesUnsupported";
|
||||||
|
|
||||||
interface PageProps {
|
interface PageProps {
|
||||||
params: Promise<{ id: string }>;
|
params: Promise<{ id: string }>;
|
||||||
@@ -13,6 +14,9 @@ interface PageProps {
|
|||||||
|
|
||||||
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
|
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
|
if ((await getPublicSettingsCached()).allow_messages === false) {
|
||||||
|
return { title: "本站不支持消息" };
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const { room } = await fetchChatRoom(id, authCookieHeader(await cookies()));
|
const { room } = await fetchChatRoom(id, authCookieHeader(await cookies()));
|
||||||
const title =
|
const title =
|
||||||
@@ -27,6 +31,9 @@ export async function generateMetadata({ params }: PageProps): Promise<Metadata>
|
|||||||
|
|
||||||
export default async function ChatRoomPage({ params }: PageProps) {
|
export default async function ChatRoomPage({ params }: PageProps) {
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
|
if ((await getPublicSettingsCached()).allow_messages === false) {
|
||||||
|
return <MessagesUnsupported />;
|
||||||
|
}
|
||||||
const cookie = authCookieHeader(await cookies());
|
const cookie = authCookieHeader(await cookies());
|
||||||
const me = await getMeCached(cookie || undefined);
|
const me = await getMeCached(cookie || undefined);
|
||||||
if (!me.user) {
|
if (!me.user) {
|
||||||
|
|||||||
@@ -2,9 +2,10 @@ import { redirect } from "next/navigation";
|
|||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import { authCookieHeader } from "@/lib/cookies";
|
import { authCookieHeader } from "@/lib/cookies";
|
||||||
import { getMeCached } from "@/lib/serverData";
|
import { getMeCached, getPublicSettingsCached } from "@/lib/serverData";
|
||||||
import { fetchChatRooms } from "@/lib/api";
|
import { fetchChatRooms } from "@/lib/api";
|
||||||
import ChatShell from "./ChatShell";
|
import ChatShell from "./ChatShell";
|
||||||
|
import MessagesUnsupported from "@/components/MessagesUnsupported";
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: "消息",
|
title: "消息",
|
||||||
@@ -12,6 +13,9 @@ export const metadata: Metadata = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default async function ChatListPage() {
|
export default async function ChatListPage() {
|
||||||
|
if ((await getPublicSettingsCached()).allow_messages === false) {
|
||||||
|
return <MessagesUnsupported />;
|
||||||
|
}
|
||||||
const cookie = authCookieHeader(await cookies());
|
const cookie = authCookieHeader(await cookies());
|
||||||
const me = await getMeCached(cookie || undefined);
|
const me = await getMeCached(cookie || undefined);
|
||||||
if (!me.user) {
|
if (!me.user) {
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import PostLinkProvider from "@/components/PostLinkProvider";
|
|||||||
import CodeFoldProvider from "@/components/markdown/CodeFoldProvider";
|
import CodeFoldProvider from "@/components/markdown/CodeFoldProvider";
|
||||||
import MotionProvider from "@/components/MotionProvider";
|
import MotionProvider from "@/components/MotionProvider";
|
||||||
import CommentsPolicyProvider from "@/components/CommentsPolicyProvider";
|
import CommentsPolicyProvider from "@/components/CommentsPolicyProvider";
|
||||||
|
import MessagesPolicyProvider from "@/components/MessagesPolicyProvider";
|
||||||
import type { User } from "@/lib/api";
|
import type { User } from "@/lib/api";
|
||||||
import { getMeCached, getPublicSettingsCached } from "@/lib/serverData";
|
import { getMeCached, getPublicSettingsCached } from "@/lib/serverData";
|
||||||
import { TOKEN_COOKIE, authCookieHeader } from "@/lib/cookies";
|
import { TOKEN_COOKIE, authCookieHeader } from "@/lib/cookies";
|
||||||
@@ -121,6 +122,7 @@ export default async function RootLayout({
|
|||||||
</a>
|
</a>
|
||||||
<MotionProvider initial={motionCfg}>
|
<MotionProvider initial={motionCfg}>
|
||||||
<CommentsPolicyProvider allowComments={settings.allow_comments !== false}>
|
<CommentsPolicyProvider allowComments={settings.allow_comments !== false}>
|
||||||
|
<MessagesPolicyProvider allowMessages={settings.allow_messages !== false}>
|
||||||
<PostLinkProvider openInNewTab={settings.post_link_new_tab !== false}>
|
<PostLinkProvider openInNewTab={settings.post_link_new_tab !== false}>
|
||||||
<CodeFoldProvider
|
<CodeFoldProvider
|
||||||
initialEnabled={settings.code_block_auto_fold}
|
initialEnabled={settings.code_block_auto_fold}
|
||||||
@@ -130,7 +132,7 @@ export default async function RootLayout({
|
|||||||
initialIsAdmin={isAdmin}
|
initialIsAdmin={isAdmin}
|
||||||
user={user}
|
user={user}
|
||||||
unread={unread}
|
unread={unread}
|
||||||
chatUnread={chatUnread}
|
chatUnread={settings.allow_messages !== false ? chatUnread : 0}
|
||||||
theme={theme}
|
theme={theme}
|
||||||
siteName={settings.site_name}
|
siteName={settings.site_name}
|
||||||
allowRegister={settings.allow_register}
|
allowRegister={settings.allow_register}
|
||||||
@@ -139,6 +141,7 @@ export default async function RootLayout({
|
|||||||
</SiteChrome>
|
</SiteChrome>
|
||||||
</CodeFoldProvider>
|
</CodeFoldProvider>
|
||||||
</PostLinkProvider>
|
</PostLinkProvider>
|
||||||
|
</MessagesPolicyProvider>
|
||||||
</CommentsPolicyProvider>
|
</CommentsPolicyProvider>
|
||||||
</MotionProvider>
|
</MotionProvider>
|
||||||
<Toaster />
|
<Toaster />
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { MessagesSquare } from "lucide-react";
|
|||||||
import { apiLogin, apiMe, apiGetSettings } from "@/lib/api";
|
import { apiLogin, apiMe, apiGetSettings } from "@/lib/api";
|
||||||
import { hasAuthCookieHint } from "@/lib/cookies";
|
import { hasAuthCookieHint } from "@/lib/cookies";
|
||||||
import { useAllowComments } from "@/components/CommentsPolicyProvider";
|
import { useAllowComments } from "@/components/CommentsPolicyProvider";
|
||||||
|
import { useAllowMessages } from "@/components/MessagesPolicyProvider";
|
||||||
|
|
||||||
// 仅允许同源相对路径跳转,拦截 //host、/\\host 与绝对 URL 形式的开放重定向
|
// 仅允许同源相对路径跳转,拦截 //host、/\\host 与绝对 URL 形式的开放重定向
|
||||||
function safeRedirect(to: string | null): string {
|
function safeRedirect(to: string | null): string {
|
||||||
@@ -42,6 +43,7 @@ export default function LoginPage() {
|
|||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const allowComments = useAllowComments();
|
const allowComments = useAllowComments();
|
||||||
|
const allowMessages = useAllowMessages();
|
||||||
const redirect = safeRedirect(searchParams.get("redirect"));
|
const redirect = safeRedirect(searchParams.get("redirect"));
|
||||||
const [username, setUsername] = useState("");
|
const [username, setUsername] = useState("");
|
||||||
const [password, setPassword] = useState("");
|
const [password, setPassword] = useState("");
|
||||||
@@ -93,7 +95,7 @@ export default function LoginPage() {
|
|||||||
欢迎回来
|
欢迎回来
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-sm mt-2" style={{ color: "var(--ink-2)" }}>
|
<p className="text-sm mt-2" style={{ color: "var(--ink-2)" }}>
|
||||||
登录后发帖{allowComments ? "、评论" : ""}与点赞
|
登录后发帖{allowComments ? "、评论" : ""}{allowMessages ? "、发消息" : ""}与点赞
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -5,12 +5,16 @@ import { useRouter } from "next/navigation";
|
|||||||
import { MessageSquare } from "lucide-react";
|
import { MessageSquare } from "lucide-react";
|
||||||
import { apiOpenDirectChat } from "@/lib/api";
|
import { apiOpenDirectChat } from "@/lib/api";
|
||||||
import { toast } from "@/lib/toast";
|
import { toast } from "@/lib/toast";
|
||||||
|
import { useAllowMessages } from "@/components/MessagesPolicyProvider";
|
||||||
|
|
||||||
/** 用户主页:发起私聊 */
|
/** 用户主页:发起私聊 */
|
||||||
export default function StartDMButton({ userId }: { userId: number }) {
|
export default function StartDMButton({ userId }: { userId: number }) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const allowMessages = useAllowMessages();
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
if (!allowMessages) return null;
|
||||||
|
|
||||||
const start = async () => {
|
const start = async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -56,7 +56,9 @@ export default async function UserPage({ params, searchParams }: UserPageProps)
|
|||||||
|
|
||||||
const cookie = authCookieHeader(await cookies());
|
const cookie = authCookieHeader(await cookies());
|
||||||
const me = await getMeCached(cookie || undefined);
|
const me = await getMeCached(cookie || undefined);
|
||||||
const allowComments = (await getPublicSettingsCached()).allow_comments !== false;
|
const settings = await getPublicSettingsCached();
|
||||||
|
const allowComments = settings.allow_comments !== false;
|
||||||
|
const allowMessages = settings.allow_messages !== false;
|
||||||
|
|
||||||
let data: UserProfile;
|
let data: UserProfile;
|
||||||
try {
|
try {
|
||||||
@@ -172,7 +174,7 @@ export default async function UserPage({ params, searchParams }: UserPageProps)
|
|||||||
banned: u.banned,
|
banned: u.banned,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<StartDMButton userId={data.user.id} />
|
{allowMessages ? <StartDMButton userId={data.user.id} /> : null}
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ import { onDocumentVisible } from "@/lib/visibilityReconcile";
|
|||||||
import NotificationBell from "./NotificationBell";
|
import NotificationBell from "./NotificationBell";
|
||||||
import ThemeToggle from "./ThemeToggle";
|
import ThemeToggle from "./ThemeToggle";
|
||||||
import Avatar from "./Avatar";
|
import Avatar from "./Avatar";
|
||||||
|
import { useAllowMessages } from "./MessagesPolicyProvider";
|
||||||
|
|
||||||
export default function Header({
|
export default function Header({
|
||||||
initialUser,
|
initialUser,
|
||||||
@@ -47,6 +48,7 @@ export default function Header({
|
|||||||
}) {
|
}) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
|
const allowMessages = useAllowMessages();
|
||||||
const [menuOpen, setMenuOpen] = useState(false);
|
const [menuOpen, setMenuOpen] = useState(false);
|
||||||
// 登录态以 SSR 直出为初始值,F5 无切换闪动;router.refresh() 后随 props 校正
|
// 登录态以 SSR 直出为初始值,F5 无切换闪动;router.refresh() 后随 props 校正
|
||||||
const [user, setUser] = useState<User | null>(initialUser);
|
const [user, setUser] = useState<User | null>(initialUser);
|
||||||
@@ -105,7 +107,7 @@ export default function Header({
|
|||||||
|
|
||||||
// 实时未读:chat:unread 推送给所有成员(含未打开会话页);在当前会话页则忽略
|
// 实时未读:chat:unread 推送给所有成员(含未打开会话页);在当前会话页则忽略
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!user) return;
|
if (!user || !allowMessages) return;
|
||||||
const off = realtime.on<RtChatUnreadData>(RT_CHAT_UNREAD, (data) => {
|
const off = realtime.on<RtChatUnreadData>(RT_CHAT_UNREAD, (data) => {
|
||||||
if (!data || typeof data.room_id !== "number") return;
|
if (!data || typeof data.room_id !== "number") return;
|
||||||
if (pathname === `/chat/${data.room_id}`) return;
|
if (pathname === `/chat/${data.room_id}`) return;
|
||||||
@@ -113,11 +115,11 @@ export default function Header({
|
|||||||
setChatUnread((c) => Math.max(0, c + delta));
|
setChatUnread((c) => Math.max(0, c + delta));
|
||||||
});
|
});
|
||||||
return off;
|
return off;
|
||||||
}, [user, pathname]);
|
}, [user, pathname, allowMessages]);
|
||||||
|
|
||||||
// 会话内已读 / 回前台:合并对账(短时间多次 markRead 只打一次 summary)
|
// 会话内已读 / 回前台:合并对账(短时间多次 markRead 只打一次 summary)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!user) return;
|
if (!user || !allowMessages) return;
|
||||||
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
|
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
const pullSummary = () => {
|
const pullSummary = () => {
|
||||||
apiChatUnreadSummary()
|
apiChatUnreadSummary()
|
||||||
@@ -135,7 +137,7 @@ export default function Header({
|
|||||||
window.removeEventListener("j13-chat-unread-sync", onSync);
|
window.removeEventListener("j13-chat-unread-sync", onSync);
|
||||||
offVisible();
|
offVisible();
|
||||||
};
|
};
|
||||||
}, [user]);
|
}, [user, allowMessages]);
|
||||||
|
|
||||||
const handleSearch = (e: React.FormEvent) => {
|
const handleSearch = (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -271,7 +273,7 @@ export default function Header({
|
|||||||
className={`${iconBtn} hidden lg:inline-flex`}
|
className={`${iconBtn} hidden lg:inline-flex`}
|
||||||
style={iconBtnStyle}
|
style={iconBtnStyle}
|
||||||
/>
|
/>
|
||||||
{user && (
|
{user && allowMessages && (
|
||||||
<Link
|
<Link
|
||||||
href="/chat"
|
href="/chat"
|
||||||
prefetch={false}
|
prefetch={false}
|
||||||
@@ -359,7 +361,7 @@ export default function Header({
|
|||||||
<div className="flex flex-col">
|
<div className="flex flex-col">
|
||||||
<MobileLink href="/" active={pathname === "/"}>首页</MobileLink>
|
<MobileLink href="/" active={pathname === "/"}>首页</MobileLink>
|
||||||
{user && <MobileLink href="/compose">发帖</MobileLink>}
|
{user && <MobileLink href="/compose">发帖</MobileLink>}
|
||||||
{user && (
|
{user && allowMessages && (
|
||||||
<MobileLink href="/chat" active={pathname?.startsWith("/chat") ?? false}>
|
<MobileLink href="/chat" active={pathname?.startsWith("/chat") ?? false}>
|
||||||
<span className="inline-flex items-center gap-2">
|
<span className="inline-flex items-center gap-2">
|
||||||
<MessageSquare size={15} /> 消息
|
<MessageSquare size={15} /> 消息
|
||||||
|
|||||||
52
frontend/components/MessagesPolicyProvider.tsx
Normal file
52
frontend/components/MessagesPolicyProvider.tsx
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
createContext,
|
||||||
|
useContext,
|
||||||
|
useEffect,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
type ReactNode,
|
||||||
|
} from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { realtime, RT_SETTINGS_CHANGED, type RtSettingsData } from "@/lib/realtime";
|
||||||
|
|
||||||
|
const AllowMessagesContext = createContext(true);
|
||||||
|
|
||||||
|
/** 前台是否开放私聊/群聊(SSR 初值 + 后台开关热更新) */
|
||||||
|
export function useAllowMessages(): boolean {
|
||||||
|
return useContext(AllowMessagesContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根布局注入:关闭消息后前台立即隐藏入口;开启则刷新以拉回会话。
|
||||||
|
*/
|
||||||
|
export default function MessagesPolicyProvider({
|
||||||
|
allowMessages,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
allowMessages: boolean;
|
||||||
|
children: ReactNode;
|
||||||
|
}) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [open, setOpen] = useState(allowMessages);
|
||||||
|
const openRef = useRef(open);
|
||||||
|
openRef.current = open;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setOpen(allowMessages);
|
||||||
|
}, [allowMessages]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return realtime.on<RtSettingsData>(RT_SETTINGS_CHANGED, (data) => {
|
||||||
|
if (typeof data?.allow_messages !== "boolean") return;
|
||||||
|
if (openRef.current === data.allow_messages) return;
|
||||||
|
setOpen(data.allow_messages);
|
||||||
|
router.refresh();
|
||||||
|
});
|
||||||
|
}, [router]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AllowMessagesContext.Provider value={open}>{children}</AllowMessagesContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
29
frontend/components/MessagesUnsupported.tsx
Normal file
29
frontend/components/MessagesUnsupported.tsx
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { MessageSquareOff } from "lucide-react";
|
||||||
|
|
||||||
|
/** 全站关闭消息时的前台说明:表达「不支持」而非暂时关闭。 */
|
||||||
|
export default function MessagesUnsupported() {
|
||||||
|
return (
|
||||||
|
<div className="max-w-md mx-auto text-center py-16 sm:py-24">
|
||||||
|
<span
|
||||||
|
className="mx-auto mb-3 flex h-11 w-11 items-center justify-center rounded-xl"
|
||||||
|
style={{
|
||||||
|
background: "color-mix(in srgb, var(--ink-3) 14%, transparent)",
|
||||||
|
color: "var(--ink-3)",
|
||||||
|
}}
|
||||||
|
aria-hidden
|
||||||
|
>
|
||||||
|
<MessageSquareOff size={22} />
|
||||||
|
</span>
|
||||||
|
<h1 className="text-[17px] font-semibold" style={{ color: "var(--ink)" }}>
|
||||||
|
本站不支持消息
|
||||||
|
</h1>
|
||||||
|
<p className="meta mt-1.5 text-[12.5px] leading-relaxed">
|
||||||
|
站点未提供私聊与群聊功能。
|
||||||
|
</p>
|
||||||
|
<Link href="/" className="btn btn-line btn-sm mt-5 inline-flex">
|
||||||
|
返回首页
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -596,6 +596,8 @@ export interface PublicSettings {
|
|||||||
allow_register: boolean;
|
allow_register: boolean;
|
||||||
/** 全站是否开放评论;关闭后前台不展示评论能力 */
|
/** 全站是否开放评论;关闭后前台不展示评论能力 */
|
||||||
allow_comments: boolean;
|
allow_comments: boolean;
|
||||||
|
/** 全站是否开放私聊/群聊;关闭后前台不展示消息入口 */
|
||||||
|
allow_messages: boolean;
|
||||||
post_cooldown_hours: number;
|
post_cooldown_hours: number;
|
||||||
/** 超过 N 行的代码块是否默认折叠;缺省 true */
|
/** 超过 N 行的代码块是否默认折叠;缺省 true */
|
||||||
code_block_auto_fold: boolean;
|
code_block_auto_fold: boolean;
|
||||||
@@ -620,6 +622,7 @@ const DEFAULT_PUBLIC_SETTINGS: PublicSettings = {
|
|||||||
site_description: "姜十三论坛 - 技术分享与讨论社区",
|
site_description: "姜十三论坛 - 技术分享与讨论社区",
|
||||||
allow_register: true,
|
allow_register: true,
|
||||||
allow_comments: true,
|
allow_comments: true,
|
||||||
|
allow_messages: true,
|
||||||
post_cooldown_hours: 24,
|
post_cooldown_hours: 24,
|
||||||
code_block_auto_fold: true,
|
code_block_auto_fold: true,
|
||||||
code_block_fold_lines: 5,
|
code_block_fold_lines: 5,
|
||||||
@@ -641,6 +644,7 @@ function normalizePublicSettings(data: Partial<PublicSettings> | null | undefine
|
|||||||
: DEFAULT_PUBLIC_SETTINGS.site_description,
|
: DEFAULT_PUBLIC_SETTINGS.site_description,
|
||||||
allow_register: data?.allow_register !== false,
|
allow_register: data?.allow_register !== false,
|
||||||
allow_comments: data?.allow_comments !== false,
|
allow_comments: data?.allow_comments !== false,
|
||||||
|
allow_messages: data?.allow_messages !== false,
|
||||||
post_cooldown_hours:
|
post_cooldown_hours:
|
||||||
typeof data?.post_cooldown_hours === "number" && data.post_cooldown_hours >= 0
|
typeof data?.post_cooldown_hours === "number" && data.post_cooldown_hours >= 0
|
||||||
? data.post_cooldown_hours
|
? data.post_cooldown_hours
|
||||||
@@ -1744,6 +1748,7 @@ export type UpdateSiteSettingsBody = {
|
|||||||
site_description?: string;
|
site_description?: string;
|
||||||
allow_register?: boolean;
|
allow_register?: boolean;
|
||||||
allow_comments?: boolean;
|
allow_comments?: boolean;
|
||||||
|
allow_messages?: boolean;
|
||||||
post_cooldown_hours?: number;
|
post_cooldown_hours?: number;
|
||||||
code_block_auto_fold?: boolean;
|
code_block_auto_fold?: boolean;
|
||||||
code_block_fold_lines?: number;
|
code_block_fold_lines?: number;
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ export interface RtSettingsData {
|
|||||||
site_description?: string;
|
site_description?: string;
|
||||||
allow_register?: boolean;
|
allow_register?: boolean;
|
||||||
allow_comments?: boolean;
|
allow_comments?: boolean;
|
||||||
|
allow_messages?: boolean;
|
||||||
post_cooldown_hours?: number;
|
post_cooldown_hours?: number;
|
||||||
code_block_auto_fold?: boolean;
|
code_block_auto_fold?: boolean;
|
||||||
code_block_fold_lines?: number;
|
code_block_fold_lines?: number;
|
||||||
|
|||||||
Reference in New Issue
Block a user