4 Commits

Author SHA1 Message Date
c958dcfd80 chore: 发布 Docker 镜像版本 1.1.7
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 03:01:36 +08:00
84bfbd9a3e fix: 帖子详情右栏默认头像与全站配色一致
作者卡占位头像改为深绿底白字,与 post-avatar 默认样式统一。
2026-09-02 02:50:23 +08:00
500e452c2f feat: 重设计私信页并优化开源展柜体验
私信改为飞书风布局,支持缩略图表情/图片、按会话草稿与用户搜索发起会话;主页发私信直达消息页。开源展柜修复空列表粘滞并改版目录式 UI。
2026-09-02 02:45:29 +08:00
1c0f7ede55 fix: 待审通知实时回填审核态并重构消息页体验 2026-09-02 01:39:27 +08:00
31 changed files with 2596 additions and 669 deletions

View File

@@ -5,7 +5,7 @@ APP_NAME := jiang13
MAIN_PKG := ./cmd/jiang13 MAIN_PKG := ./cmd/jiang13
BUILD_DIR := dist BUILD_DIR := dist
DEV_DATA_DIR := dist/data DEV_DATA_DIR := dist/data
VERSION := 1.1.6 VERSION := 1.1.7
LDFLAGS := -s -w -X main.version=$(VERSION) LDFLAGS := -s -w -X main.version=$(VERSION)
REGISTRY_IMAGE := hangzhang714128/jiang13-forum REGISTRY_IMAGE := hangzhang714128/jiang13-forum

View File

@@ -212,15 +212,15 @@ docker run -d --name jiang13 \
docker login docker login
.\build.bat -Target docker # Windows .\build.bat -Target docker # Windows
# make docker # Linux/macOS # make docker # Linux/macOS
docker push hangzhang714128/jiang13-forum:1.1.6 docker push hangzhang714128/jiang13-forum:1.1.7
docker push hangzhang714128/jiang13-forum:latest docker push hangzhang714128/jiang13-forum:latest
``` ```
或直接构建: 或直接构建:
```bash ```bash
docker build --build-arg VERSION=1.1.6 -t hangzhang714128/jiang13-forum:1.1.6 -t hangzhang714128/jiang13-forum:latest . docker build --build-arg VERSION=1.1.7 -t hangzhang714128/jiang13-forum:1.1.7 -t hangzhang714128/jiang13-forum:latest .
docker push hangzhang714128/jiang13-forum:1.1.6 docker push hangzhang714128/jiang13-forum:1.1.7
docker push hangzhang714128/jiang13-forum:latest docker push hangzhang714128/jiang13-forum:latest
``` ```
@@ -252,19 +252,19 @@ docker push hangzhang714128/jiang13-forum:latest
| `jiang13-*-windows-amd64.exe` | Windows x64 | | `jiang13-*-windows-amd64.exe` | Windows x64 |
| `jiang13-*-linux-amd64` | Linux x64 | | `jiang13-*-linux-amd64` | Linux x64 |
当前 **1.1.6** [Windows](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.6/jiang13-1.1.6-windows-amd64.exe) · [Linux](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.6/jiang13-1.1.6-linux-amd64) 当前 **1.1.7** [Windows](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.7/jiang13-1.1.7-windows-amd64.exe) · [Linux](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.7/jiang13-1.1.7-linux-amd64)
把文件放到目标目录后直接运行(首次会在同目录生成 `app.ini` 把文件放到目标目录后直接运行(首次会在同目录生成 `app.ini`
```bash ```bash
# Windows # Windows
.\jiang13-1.1.6-windows-amd64.exe .\jiang13-1.1.7-windows-amd64.exe
# 或改名为 jiang13.exe 后: # 或改名为 jiang13.exe 后:
.\jiang13.exe .\jiang13.exe
# Linux # Linux
chmod +x jiang13-1.1.6-linux-amd64 chmod +x jiang13-1.1.7-linux-amd64
./jiang13-1.1.6-linux-amd64 ./jiang13-1.1.7-linux-amd64
``` ```
本地刚编译的产物在 `dist/` 本地刚编译的产物在 `dist/`

View File

@@ -12,7 +12,7 @@ $AppName = 'jiang13'
$MainPkg = './cmd/jiang13' $MainPkg = './cmd/jiang13'
$BuildDir = 'dist' $BuildDir = 'dist'
$DevDataDir = 'dist/data' $DevDataDir = 'dist/data'
$Version = '1.1.6' $Version = '1.1.7'
$RegistryImage = 'hangzhang714128/jiang13-forum' $RegistryImage = 'hangzhang714128/jiang13-forum'
$Ldlags = "-s -w -X main.version=$Version" $Ldlags = "-s -w -X main.version=$Version"

View File

@@ -12,6 +12,7 @@ import (
"github.com/kardianos/service" "github.com/kardianos/service"
"git.iioio.com/freefire/jiang13-forum/config" "git.iioio.com/freefire/jiang13-forum/config"
forumsvc "git.iioio.com/freefire/jiang13-forum/service"
"git.iioio.com/freefire/jiang13-forum/model" "git.iioio.com/freefire/jiang13-forum/model"
"git.iioio.com/freefire/jiang13-forum/router" "git.iioio.com/freefire/jiang13-forum/router"
) )
@@ -78,6 +79,9 @@ func (p *program) setup() error {
if err := model.InitDB(cfg.DBPath()); err != nil { if err := model.InitDB(cfg.DBPath()); err != nil {
return fmt.Errorf("数据库初始化失败: %w", err) return fmt.Errorf("数据库初始化失败: %w", err)
} }
if err := forumsvc.BackfillModerationNotifyRefs(); err != nil {
log.Printf("待审通知关联字段回填警告: %v", err)
}
if err := model.InitMonitorDB(cfg.MonitorDBPath()); err != nil { if err := model.InitMonitorDB(cfg.MonitorDBPath()); err != nil {
return fmt.Errorf("监控库初始化失败: %w", err) return fmt.Errorf("监控库初始化失败: %w", err)
} }

View File

@@ -10,7 +10,7 @@
Docker 镜像、Windows exe、Linux 单文件 **共用同一版本号**。有新版本时,以本页为准。 Docker 镜像、Windows exe、Linux 单文件 **共用同一版本号**。有新版本时,以本页为准。
**当前版本1.1.6**2026-09-01 **当前版本1.1.7**2026-09-02
## 去哪看新版本 ## 去哪看新版本
@@ -21,16 +21,16 @@ Docker 镜像、Windows exe、Linux 单文件 **共用同一版本号**。有新
| Windows / Linux | 预编译单文件(与 Docker 同版本) | [Gitea Releases](https://git.iioio.com/freefire/jiang13-forum/releases) | | Windows / Linux | 预编译单文件(与 Docker 同版本) | [Gitea Releases](https://git.iioio.com/freefire/jiang13-forum/releases) |
| 源码 | 提交记录与自行编译 | [Gitea 仓库](https://git.iioio.com/freefire/jiang13-forum) | | 源码 | 提交记录与自行编译 | [Gitea 仓库](https://git.iioio.com/freefire/jiang13-forum) |
**1.1.6 直接下载:** **1.1.7 直接下载:**
- Windows x64[jiang13-1.1.6-windows-amd64.exe](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.6/jiang13-1.1.6-windows-amd64.exe) - Windows x64[jiang13-1.1.7-windows-amd64.exe](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.7/jiang13-1.1.7-windows-amd64.exe)
- Linux x64[jiang13-1.1.6-linux-amd64](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.6/jiang13-1.1.6-linux-amd64) - Linux x64[jiang13-1.1.7-linux-amd64](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.7/jiang13-1.1.7-linux-amd64)
- 校验文件:[SHA256SUMS.txt](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.6/SHA256SUMS.txt) - 校验文件:[SHA256SUMS.txt](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.7/SHA256SUMS.txt)
拉取指定版本镜像: 拉取指定版本镜像:
```bash ```bash
docker pull hangzhang714128/jiang13-forum:1.1.6 docker pull hangzhang714128/jiang13-forum:1.1.7
# 或始终跟随最新 # 或始终跟随最新
docker pull hangzhang714128/jiang13-forum:latest docker pull hangzhang714128/jiang13-forum:latest
``` ```
@@ -47,6 +47,21 @@ Linux赋予执行权限后放到原目录覆盖同样保留 `data/` 与 `a
--- ---
## 1.1.7 — 2026-09-02
私信与开源展柜体验升级,待审通知的审核态更及时。
**新增 / 调整**
- 私信改为飞书风布局:缩略图表情/图片、按会话草稿、用户搜索发起会话
- 主页「发私信」直达消息页对应会话
- 开源展柜改为目录式 UI空列表不再粘滞
- 消息页体验重构;待审通知打开后实时回填审核态
**修复**
- 帖子详情右栏默认头像改为深绿底白字,与列表默认头像配色一致
## 1.1.6 — 2026-09-01 ## 1.1.6 — 2026-09-01
编辑器插入体验与首页默认 Feed 排序更合理。 编辑器插入体验与首页默认 Feed 排序更合理。

View File

@@ -664,6 +664,8 @@ export const api = {
}, },
markNotificationsRead: () => markNotificationsRead: () =>
request<{ message: string }>('/api/messages/notifications/read', { method: 'POST' }), request<{ message: string }>('/api/messages/notifications/read', { method: 'POST' }),
markMessageRead: (id: number) =>
request<{ message: string }>(`/api/messages/${id}/read`, { method: 'POST' }),
sendMessage: (body: { to_user_id: number; subject?: string; content: string }) => sendMessage: (body: { to_user_id: number; subject?: string; content: string }) =>
request<{ message: PrivateMessage }>('/api/messages', { request<{ message: PrivateMessage }>('/api/messages', {
method: 'POST', body: JSON.stringify(body), method: 'POST', body: JSON.stringify(body),

View File

@@ -717,9 +717,13 @@ export interface PrivateMessage {
to_user_id: number; to_user_id: number;
subject: string; subject: string;
content: string; content: string;
kind: 'user' | 'system' | 'reject' | 'report_result' | string; kind: 'user' | 'system' | 'reject' | 'report_result' | 'reply' | 'mention' | 'moderation' | string;
related_post_id?: number; related_post_id?: number;
related_report_id?: number; related_report_id?: number;
related_comment_id?: number;
related_floor?: number;
/** 待审目标实时状态pending|published|rejected|deleted */
related_status?: string;
is_read: boolean; is_read: boolean;
created_at: string; created_at: string;
from_user?: User; from_user?: User;

View File

@@ -9,7 +9,6 @@ import { useAuth } from '../hooks/useAuth';
import { loginPath } from '../utils/authRedirect'; import { loginPath } from '../utils/authRedirect';
import { formatTime } from '../utils/content'; import { formatTime } from '../utils/content';
import { userPath } from '../utils/userPath'; import { userPath } from '../utils/userPath';
import ComposeMessageDialog from './ComposeMessageDialog';
import UserLink from './UserLink'; import UserLink from './UserLink';
interface Props { interface Props {
@@ -28,7 +27,6 @@ export default function PostAuthorCard({
const { user: me } = useAuth(); const { user: me } = useAuth();
const [profile, setProfile] = useState<UserPublic | null>(null); const [profile, setProfile] = useState<UserPublic | null>(null);
const [stats, setStats] = useState<UserActivityStats | null>(null); const [stats, setStats] = useState<UserActivityStats | null>(null);
const [msgOpen, setMsgOpen] = useState(false);
useEffect(() => { useEffect(() => {
if (!author?.id) { if (!author?.id) {
@@ -78,7 +76,7 @@ export default function PostAuthorCard({
nav(loginPath(profileHref)); nav(loginPath(profileHref));
return; return;
} }
setMsgOpen(true); nav(`/messages?peer=${author.id}`);
}; };
return ( return (
@@ -159,16 +157,6 @@ export default function PostAuthorCard({
</Button> </Button>
</div> </div>
</div> </div>
{!isSelf && (
<ComposeMessageDialog
open={msgOpen}
onOpenChange={setMsgOpen}
toUserId={author.id}
toNickname={nick}
onSent={() => nav(`/messages?peer=${author.id}`)}
/>
)}
</div> </div>
); );
} }

View File

@@ -31,7 +31,7 @@ function pickScrollEl(): HTMLElement | null {
const page = document.querySelector<HTMLElement>('.page-wrap:not(.page-wrap--feed)'); const page = document.querySelector<HTMLElement>('.page-wrap:not(.page-wrap--feed)');
if (page) return page; if (page) return page;
const showcase = document.querySelector<HTMLElement>('.showcase-page'); const showcase = document.querySelector<HTMLElement>('.showcase-panel');
if (showcase) return showcase.closest<HTMLElement>('.main-content') ?? showcase; if (showcase) return showcase.closest<HTMLElement>('.main-content') ?? showcase;
const admin = document.querySelector<HTMLElement>('.admin-main'); const admin = document.querySelector<HTMLElement>('.admin-main');

View File

@@ -19,12 +19,14 @@ export default function ShowcaseAsideWidget() {
useEffect(() => { useEffect(() => {
let cancelled = false; let cancelled = false;
const hit = getSessionSnapshot<CommunityShowcaseItem[]>(SHOWCASE_KEY); const hit = getSessionSnapshot<CommunityShowcaseItem[]>(SHOWCASE_KEY);
if (hit !== undefined) { // 非空快照直接用;空数组可能是启动竞态假空,仍再拉
if (hit !== undefined && hit.length > 0) {
setItems(hit); setItems(hit);
setLoading(false); setLoading(false);
return; return;
} }
setLoading(true); if (hit !== undefined) setItems(hit);
setLoading(hit === undefined);
api.communityShowcase() api.communityShowcase()
.then((r) => { .then((r) => {
if (cancelled) return; if (cancelled) return;
@@ -33,10 +35,8 @@ export default function ShowcaseAsideWidget() {
setItems(next); setItems(next);
}) })
.catch(() => { .catch(() => {
if (!cancelled) { // 失败不写空快照,避免假空粘死
setSessionSnapshot(SHOWCASE_KEY, []); if (!cancelled && hit === undefined) setItems([]);
setItems([]);
}
}) })
.finally(() => { .finally(() => {
if (!cancelled) setLoading(false); if (!cancelled) setLoading(false);
@@ -54,17 +54,13 @@ export default function ShowcaseAsideWidget() {
setItems(next); setItems(next);
}) })
.catch(() => { .catch(() => {
if (opts.showLoading) { // 软刷新 / 强刷失败:保持旧 UI不写空快照
setSessionSnapshot(SHOWCASE_KEY, []);
setItems([]);
}
// 软刷新失败:保持旧 UI
}) })
.finally(() => setLoading(false)); .finally(() => setLoading(false));
}; };
const applyHitOrReload = (showLoading: boolean) => { const applyHitOrReload = (showLoading: boolean) => {
const hit = getSessionSnapshot<CommunityShowcaseItem[]>(SHOWCASE_KEY); const hit = getSessionSnapshot<CommunityShowcaseItem[]>(SHOWCASE_KEY);
if (hit !== undefined) { if (hit !== undefined && hit.length > 0) {
setItems(hit); setItems(hit);
setLoading(false); setLoading(false);
return; return;

View File

@@ -13,15 +13,22 @@ type Fetcher<T> = () => Promise<T>;
* 会话快照数据源:有缓存则跳过请求;无缓存时保留上一份画面直到新数据返回。 * 会话快照数据源:有缓存则跳过请求;无缓存时保留上一份画面直到新数据返回。
* 手机下拉软刷新 commit / PAGE_FORCE_REFRESH_EVENT 会应用新快照。 * 手机下拉软刷新 commit / PAGE_FORCE_REFRESH_EVENT 会应用新快照。
*/ */
function isEmptyArray(value: unknown): boolean {
return Array.isArray(value) && value.length === 0;
}
export function useSessionResource<T>( export function useSessionResource<T>(
key: string | null, key: string | null,
fetcher: Fetcher<T>, fetcher: Fetcher<T>,
opts?: { opts?: {
enabled?: boolean; enabled?: boolean;
onError?: (e: unknown) => void; onError?: (e: unknown) => void;
/** 缓存为空数组时仍后台再拉,避免启动竞态假空粘死 */
revalidateEmpty?: boolean;
}, },
) { ) {
const enabled = opts?.enabled !== false; const enabled = opts?.enabled !== false;
const revalidateEmpty = opts?.revalidateEmpty === true;
const fetcherRef = useRef(fetcher); const fetcherRef = useRef(fetcher);
fetcherRef.current = fetcher; fetcherRef.current = fetcher;
const onErrorRef = useRef(opts?.onError); const onErrorRef = useRef(opts?.onError);
@@ -49,7 +56,7 @@ export function useSessionResource<T>(
} }
const hit = getSessionSnapshot<T>(key); const hit = getSessionSnapshot<T>(key);
if (hit !== undefined) { if (hit !== undefined && !(revalidateEmpty && isEmptyArray(hit))) {
setData(hit); setData(hit);
setLoading(false); setLoading(false);
setPending(false); setPending(false);
@@ -57,9 +64,16 @@ export function useSessionResource<T>(
} }
const seq = ++seqRef.current; const seq = ++seqRef.current;
const keep = dataRef.current !== undefined; const keep = dataRef.current !== undefined || (hit !== undefined && isEmptyArray(hit));
if (keep) setPending(true); if (hit !== undefined && isEmptyArray(hit)) {
else setLoading(true); setData(hit);
setPending(true);
setLoading(false);
} else if (keep && dataRef.current !== undefined) {
setPending(true);
} else {
setLoading(true);
}
fetcherRef.current() fetcherRef.current()
.then((next) => { .then((next) => {
@@ -70,6 +84,7 @@ export function useSessionResource<T>(
.catch((e: unknown) => { .catch((e: unknown) => {
if (seq !== seqRef.current) return; if (seq !== seqRef.current) return;
onErrorRef.current?.(e); onErrorRef.current?.(e);
// 失败不写空快照;已有画面则保留
if (!keep) setData(undefined); if (!keep) setData(undefined);
}) })
.finally(() => { .finally(() => {
@@ -81,7 +96,7 @@ export function useSessionResource<T>(
return () => { return () => {
seqRef.current += 1; seqRef.current += 1;
}; };
}, [key, enabled]); }, [key, enabled, revalidateEmpty]);
const replace = useCallback((next: T | ((prev: T | undefined) => T)) => { const replace = useCallback((next: T | ((prev: T | undefined) => T)) => {
setData((prev) => { setData((prev) => {
@@ -99,18 +114,20 @@ export function useSessionResource<T>(
const reload = (opts: { allowLoading: boolean }) => { const reload = (opts: { allowLoading: boolean }) => {
if (!key || !enabled) return; if (!key || !enabled) return;
const warm = getSessionSnapshot<T>(key); const warm = getSessionSnapshot<T>(key);
if (warm !== undefined) { if (warm !== undefined && !(revalidateEmpty && isEmptyArray(warm))) {
setData(warm); setData(warm);
setLoading(false); setLoading(false);
setPending(false); setPending(false);
return; return;
} }
const seq = ++seqRef.current; const seq = ++seqRef.current;
const keep = dataRef.current !== undefined; const keep = dataRef.current !== undefined || (warm !== undefined && isEmptyArray(warm));
if (opts.allowLoading) { if (opts.allowLoading) {
deleteSessionSnapshot(key); deleteSessionSnapshot(key);
if (keep) setPending(true); if (keep) setPending(true);
else setLoading(true); else setLoading(true);
} else if (warm !== undefined && isEmptyArray(warm)) {
setPending(true);
} }
fetcherRef.current() fetcherRef.current()
.then((next) => { .then((next) => {
@@ -138,7 +155,7 @@ export function useSessionResource<T>(
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce); window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit); window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
}; };
}, [key, enabled]); }, [key, enabled, revalidateEmpty]);
return { data, loading, pending, replace, invalidate }; return { data, loading, pending, replace, invalidate };
} }

View File

@@ -72,6 +72,8 @@ export default function MainLayout() {
const [recentComments, setRecentComments] = useState<RecentComment[]>(() => getCachedRecentComments()); const [recentComments, setRecentComments] = useState<RecentComment[]>(() => getCachedRecentComments());
const [recentUsers, setRecentUsers] = useState<RecentUser[]>(() => getCachedRecentUsers()); const [recentUsers, setRecentUsers] = useState<RecentUser[]>(() => getCachedRecentUsers());
const [unreadMessages, setUnreadMessages] = useState(() => getBootUnread()); const [unreadMessages, setUnreadMessages] = useState(() => getBootUnread());
const [dmUnread, setDmUnread] = useState(0);
const [notifyUnread, setNotifyUnread] = useState(0);
const [tags, setTags] = useState<TagCount[]>(() => getCachedTags()); const [tags, setTags] = useState<TagCount[]>(() => getCachedTags());
const [tagsLoading, setTagsLoading] = useState(() => getCachedTags().length === 0); const [tagsLoading, setTagsLoading] = useState(() => getCachedTags().length === 0);
const [postOutline, setPostOutline] = useState<{ const [postOutline, setPostOutline] = useState<{
@@ -309,13 +311,29 @@ export default function MainLayout() {
const refreshUnreadMessages = useCallback(() => { const refreshUnreadMessages = useCallback(() => {
if (!user) { if (!user) {
setUnreadMessages(0); setUnreadMessages(0);
setDmUnread(0);
setNotifyUnread(0);
return; return;
} }
api.messageUnreadCount() api.messageUnreadCount()
.then((r) => setUnreadMessages(r.count || 0)) .then((r) => {
.catch(() => setUnreadMessages(0)); setUnreadMessages(r.count || 0);
setDmUnread(r.dm_count ?? 0);
setNotifyUnread(r.notify_count ?? 0);
})
.catch(() => {
setUnreadMessages(0);
setDmUnread(0);
setNotifyUnread(0);
});
}, [user]); }, [user]);
/** 仅有通知未读时直达通知 Tab避免先看到空私信列表 */
const openMessages = useCallback(() => {
const path = notifyUnread > 0 && dmUnread === 0 ? '/messages?tab=notify' : '/messages';
void transitionTo(nav, path);
}, [nav, notifyUnread, dmUnread]);
useEffect(() => { useEffect(() => {
refreshUnreadMessages(); refreshUnreadMessages();
const onRefresh = () => refreshUnreadMessages(); const onRefresh = () => refreshUnreadMessages();
@@ -667,7 +685,7 @@ export default function MainLayout() {
className="header-icon-btn header-msg-btn" className="header-icon-btn header-msg-btn"
title={unreadMessages > 0 ? `${unreadMessages} 条未读消息` : '站内消息'} title={unreadMessages > 0 ? `${unreadMessages} 条未读消息` : '站内消息'}
aria-label={unreadMessages > 0 ? `站内消息,${unreadMessages} 条未读` : '站内消息'} aria-label={unreadMessages > 0 ? `站内消息,${unreadMessages} 条未读` : '站内消息'}
onClick={() => void transitionTo(nav, '/messages')} onClick={openMessages}
> >
<Mail size={18} aria-hidden /> <Mail size={18} aria-hidden />
{unreadMessages > 0 && ( {unreadMessages > 0 && (
@@ -691,7 +709,7 @@ export default function MainLayout() {
<DropdownMenuItem onClick={() => void transitionTo(nav, '/profile')}> <DropdownMenuItem onClick={() => void transitionTo(nav, '/profile')}>
{typeof user.points === 'number' ? ` · ${user.points} 积分` : ''} {typeof user.points === 'number' ? ` · ${user.points} 积分` : ''}
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem onClick={() => void transitionTo(nav, '/messages')}> <DropdownMenuItem onClick={openMessages}>
{unreadMessages > 0 ? ` (${unreadMessages})` : ''} {unreadMessages > 0 ? ` (${unreadMessages})` : ''}
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem onClick={() => void transitionTo(nav, '/favorites')}></DropdownMenuItem> <DropdownMenuItem onClick={() => void transitionTo(nav, '/favorites')}></DropdownMenuItem>

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,7 @@
import { ExternalLink, Globe2 } from 'lucide-react'; import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowLeft, ExternalLink, Globe2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner'; import { Spinner } from '@/components/ui/spinner';
import { api } from '../api/client'; import { api } from '../api/client';
import type { CommunityShowcaseItem } from '../api/types'; import type { CommunityShowcaseItem } from '../api/types';
@@ -7,12 +10,65 @@ import { getCachedSiteBranding, useSiteBranding } from '../hooks/useSiteBranding
import { InFlowSiteFooter } from '../components/SiteFooter'; import { InFlowSiteFooter } from '../components/SiteFooter';
import { useSessionResource } from '../hooks/useSessionResource'; import { useSessionResource } from '../hooks/useSessionResource';
function siteMark(name: string, url: string): string {
const raw = (name || '').trim() || url.replace(/^https?:\/\//i, '');
const ch = Array.from(raw)[0];
return ch ? ch.toUpperCase() : '?';
}
function hostLabel(url: string): string {
try {
return new URL(url).host;
} catch {
return url.replace(/^https?:\/\//i, '');
}
}
/** 目标站约定路径 /favicon.ico */
function faviconURL(siteURL: string): string | null {
try {
return new URL('/favicon.ico', siteURL).href;
} catch {
return null;
}
}
function ShowcaseFavicon({ name, url }: { name: string; url: string }) {
const src = faviconURL(url);
const [failed, setFailed] = useState(!src);
const mark = siteMark(name, url);
if (failed || !src) {
return (
<span className="showcase-item-mark" aria-hidden>
{mark}
</span>
);
}
return (
<span className="showcase-item-favicon">
<img
src={src}
alt=""
width={40}
height={40}
referrerPolicy="no-referrer"
decoding="async"
onError={() => setFailed(true)}
/>
</span>
);
}
/** 官方精选的公网部署展柜(只读;仅人工精选条目) */ /** 官方精选的公网部署展柜(只读;仅人工精选条目) */
export default function ShowcasePage() { export default function ShowcasePage() {
const nav = useNavigate();
const { branding } = useSiteBranding(); const { branding } = useSiteBranding();
const { data: items = [], loading } = useSessionResource<CommunityShowcaseItem[]>( const { data: items = [], loading } = useSessionResource<CommunityShowcaseItem[]>(
'showcase', 'showcase',
() => api.communityShowcase().then((r) => (Array.isArray(r.items) ? r.items : [])), () => api.communityShowcase().then((r) => (Array.isArray(r.items) ? r.items : [])),
{ revalidateEmpty: true },
); );
usePageSEO({ usePageSEO({
@@ -24,26 +80,36 @@ export default function ShowcasePage() {
return ( return (
<div className="page-wrap"> <div className="page-wrap">
<div className="showcase-page"> <div className="feed-panel list-page-panel showcase-panel">
<header className="showcase-head"> <header className="list-page-panel__head showcase-head">
<div className="showcase-head-mark" aria-hidden> <Button variant="ghost" size="sm" className="list-page-panel__back" onClick={() => nav('/')}>
<Globe2 size={22} /> <ArrowLeft />
</Button>
<div className="showcase-head__title-row">
<h1 className="page-title"></h1>
{!loading && items.length > 0 && (
<span className="showcase-head__count"> {items.length} </span>
)}
</div> </div>
<div> <p className="page-desc">
<h1 className="showcase-title"></h1>
<p className="showcase-desc">
</p> </p>
</div>
</header> </header>
{loading ? ( {loading ? (
<div className="flex justify-center py-16"><Spinner size="lg" /></div> <div className="flex justify-center py-16"><Spinner size="lg" /></div>
) : items.length === 0 ? ( ) : items.length === 0 ? (
<p className="showcase-empty"></p> <div className="showcase-empty list-page-panel__empty">
<Globe2 size={28} strokeWidth={1.5} aria-hidden />
<p></p>
<span></span>
</div>
) : ( ) : (
<ul className="showcase-list"> <ul className="showcase-list">
{items.map((item) => ( {items.map((item) => {
const name = item.site_name || '未命名站点';
return (
<li key={item.site_url} className="showcase-item"> <li key={item.site_url} className="showcase-item">
<a <a
href={item.site_url} href={item.site_url}
@@ -51,21 +117,24 @@ export default function ShowcasePage() {
rel="noopener noreferrer" rel="noopener noreferrer"
className="showcase-item-link" className="showcase-item-link"
> >
<span className="showcase-item-name">{item.site_name || '未命名站点'}</span> <ShowcaseFavicon name={name} url={item.site_url} />
<span className="showcase-item-body">
<span className="showcase-item-name">{name}</span>
<span className="showcase-item-url"> <span className="showcase-item-url">
{item.site_url} {hostLabel(item.site_url)}
<ExternalLink size={12} aria-hidden /> <ExternalLink size={12} aria-hidden />
</span> </span>
{(item.featured_note || item.version) && ( {item.featured_note ? (
<span className="showcase-item-meta"> <span className="showcase-item-note">{item.featured_note}</span>
{item.featured_note || null} ) : null}
{item.featured_note && item.version ? ' · ' : null}
{item.version ? `v${item.version}` : null}
</span> </span>
)} {item.version ? (
<span className="showcase-item-version">v{item.version}</span>
) : null}
</a> </a>
</li> </li>
))} );
})}
</ul> </ul>
)} )}

View File

@@ -23,7 +23,6 @@ import { useForumLimits } from '../hooks/useForumLimits';
import { useSessionResource } from '../hooks/useSessionResource'; import { useSessionResource } from '../hooks/useSessionResource';
import PostListItem from '../components/PostListItem'; import PostListItem from '../components/PostListItem';
import FeedPagination from '../components/FeedPagination'; import FeedPagination from '../components/FeedPagination';
import ComposeMessageDialog from '../components/ComposeMessageDialog';
import { openForumPost } from '../utils/openPost'; import { openForumPost } from '../utils/openPost';
import { formatDateTime } from '../utils/content'; import { formatDateTime } from '../utils/content';
import { usePageSEO } from '../hooks/usePageSEO'; import { usePageSEO } from '../hooks/usePageSEO';
@@ -44,7 +43,6 @@ export default function UserProfilePage() {
const { limits } = useForumLimits(); const { limits } = useForumLimits();
const pageSize = limits.page_size_default > 0 ? limits.page_size_default : 20; const pageSize = limits.page_size_default > 0 ? limits.page_size_default : 20;
const [msgOpen, setMsgOpen] = useState(false);
const [notFound, setNotFound] = useState(false); const [notFound, setNotFound] = useState(false);
const [postPage, setPostPage] = useState(1); const [postPage, setPostPage] = useState(1);
@@ -183,7 +181,7 @@ export default function UserProfilePage() {
nav(loginPath(userPath(profile.id))); nav(loginPath(userPath(profile.id)));
return; return;
} }
setMsgOpen(true); nav(`/messages?peer=${profile.id}`);
}} }}
> >
<Mail size={14} /> <Mail size={14} />
@@ -265,16 +263,6 @@ export default function UserProfilePage() {
</div> </div>
</div> </div>
<InFlowSiteFooter /> <InFlowSiteFooter />
{!isSelf && profile && me && (
<ComposeMessageDialog
open={msgOpen}
onOpenChange={setMsgOpen}
toUserId={profile.id}
toNickname={profile.nickname}
onSent={() => nav(`/messages?peer=${profile.id}`)}
/>
)}
</div> </div>
); );
} }

View File

@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate, useSearchParams } from 'react-router-dom';
import { Trash2, RotateCcw } from 'lucide-react'; import { Trash2, RotateCcw } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
@@ -40,6 +40,8 @@ function formatAdminTime(iso: string) {
export default function AdminCommentsPage() { export default function AdminCommentsPage() {
const nav = useNavigate(); const nav = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const focusId = Number(searchParams.get('id') || 0) || 0;
const { ready } = useAdminGuard(); const { ready } = useAdminGuard();
const [tab, setTab] = useState<Tab>('pending'); const [tab, setTab] = useState<Tab>('pending');
const [comments, setComments] = useState<Comment[]>([]); const [comments, setComments] = useState<Comment[]>([]);
@@ -49,6 +51,9 @@ export default function AdminCommentsPage() {
const [totalPages, setTotalPages] = useState(1); const [totalPages, setTotalPages] = useState(1);
const [pendingCount, setPendingCount] = useState(0); const [pendingCount, setPendingCount] = useState(0);
const [revComment, setRevComment] = useState<Comment | null>(null); const [revComment, setRevComment] = useState<Comment | null>(null);
const [highlightId, setHighlightId] = useState<number | null>(focusId > 0 ? focusId : null);
const focusTriedRef = useRef(false);
const highlightTimer = useRef<ReturnType<typeof setTimeout>>();
const loadList = (p = page, st: Tab = tab) => { const loadList = (p = page, st: Tab = tab) => {
setLoading(true); setLoading(true);
@@ -90,6 +95,45 @@ export default function AdminCommentsPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [ready, tab]); }, [ready, tab]);
// 从通知深链 ?id= 定位并高亮待审行
useEffect(() => {
if (!ready || loading || focusId <= 0 || focusTriedRef.current) return;
if (tab === 'trash') return;
const found = comments.find((c) => c.id === focusId);
if (found) {
focusTriedRef.current = true;
setHighlightId(focusId);
requestAnimationFrame(() => {
document.getElementById(`admin-comment-row-${focusId}`)?.scrollIntoView({
behavior: 'smooth',
block: 'center',
});
});
clearTimeout(highlightTimer.current);
highlightTimer.current = setTimeout(() => setHighlightId(null), 2800);
const next = new URLSearchParams(searchParams);
next.delete('id');
setSearchParams(next, { replace: true });
return;
}
// pending 未找到则切到全部再试一次
if (tab === 'pending') {
setTab('all');
setPage(1);
return;
}
focusTriedRef.current = true;
notify.warning('该评论可能已审核或不在当前列表');
const next = new URLSearchParams(searchParams);
next.delete('id');
setSearchParams(next, { replace: true });
}, [ready, loading, comments, focusId, tab, searchParams, setSearchParams]);
useEffect(() => () => clearTimeout(highlightTimer.current), []);
const approve = async (id: number) => { const approve = async (id: number) => {
try { try {
const r = await api.adminApproveComment(id); const r = await api.adminApproveComment(id);
@@ -268,7 +312,11 @@ export default function AdminCommentsPage() {
</thead> </thead>
<tbody> <tbody>
{comments.map(c => ( {comments.map(c => (
<tr key={c.id}> <tr
key={c.id}
id={`admin-comment-row-${c.id}`}
className={cn(highlightId === c.id && 'admin-row-highlight')}
>
<td>{c.id}</td> <td>{c.id}</td>
<td>#{c.floor}</td> <td>#{c.floor}</td>
<td> <td>

View File

@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate, useSearchParams } from 'react-router-dom';
import { Search, Lock, LockOpen, MessageSquareOff, Trash2, RotateCcw } from 'lucide-react'; import { Search, Lock, LockOpen, MessageSquareOff, Trash2, RotateCcw } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
@@ -32,6 +32,8 @@ function formatAdminTime(iso: string) {
export default function AdminPostsPage() { export default function AdminPostsPage() {
const nav = useNavigate(); const nav = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const focusId = Number(searchParams.get('id') || 0) || 0;
const { ready } = useAdminGuard(); const { ready } = useAdminGuard();
const [tab, setTab] = useState<Tab>('pending'); const [tab, setTab] = useState<Tab>('pending');
const [posts, setPosts] = useState<PostItem[]>([]); const [posts, setPosts] = useState<PostItem[]>([]);
@@ -42,6 +44,9 @@ export default function AdminPostsPage() {
const [pendingCount, setPendingCount] = useState(0); const [pendingCount, setPendingCount] = useState(0);
const [keyword, setKeyword] = useState(''); const [keyword, setKeyword] = useState('');
const [search, setSearch] = useState(''); const [search, setSearch] = useState('');
const [highlightId, setHighlightId] = useState<number | null>(focusId > 0 ? focusId : null);
const focusTriedRef = useRef(false);
const highlightTimer = useRef<ReturnType<typeof setTimeout>>();
const loadActive = (p = page, kw = search, status = tab === 'pending' ? 'pending' : 'all') => { const loadActive = (p = page, kw = search, status = tab === 'pending' ? 'pending' : 'all') => {
setLoading(true); setLoading(true);
@@ -92,6 +97,43 @@ export default function AdminPostsPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps -- 仅随 tab/search/ready 刷新 // eslint-disable-next-line react-hooks/exhaustive-deps -- 仅随 tab/search/ready 刷新
}, [ready, search, tab]); }, [ready, search, tab]);
// 从通知深链 ?id= 定位并高亮
useEffect(() => {
if (!ready || loading || focusId <= 0 || focusTriedRef.current) return;
if (tab === 'trash') return;
const found = posts.find((p) => p.id === focusId);
if (found) {
focusTriedRef.current = true;
setHighlightId(focusId);
requestAnimationFrame(() => {
document.getElementById(`admin-post-row-${focusId}`)?.scrollIntoView({
behavior: 'smooth',
block: 'center',
});
});
clearTimeout(highlightTimer.current);
highlightTimer.current = setTimeout(() => setHighlightId(null), 2800);
const next = new URLSearchParams(searchParams);
next.delete('id');
setSearchParams(next, { replace: true });
return;
}
if (tab === 'pending') {
setTab('active');
return;
}
focusTriedRef.current = true;
notify.warning('该帖子可能已审核或不在当前列表');
const next = new URLSearchParams(searchParams);
next.delete('id');
setSearchParams(next, { replace: true });
}, [ready, loading, posts, focusId, tab, searchParams, setSearchParams]);
useEffect(() => () => clearTimeout(highlightTimer.current), []);
const switchTab = (next: Tab) => { const switchTab = (next: Tab) => {
if (next === tab) return; if (next === tab) return;
setTab(next); setTab(next);
@@ -352,7 +394,11 @@ export default function AdminPostsPage() {
{posts.map(p => { {posts.map(p => {
const edited = p.updated_at && isTimeDiffSignificant(p.created_at, p.updated_at); const edited = p.updated_at && isTimeDiffSignificant(p.created_at, p.updated_at);
return ( return (
<tr key={p.id}> <tr
key={p.id}
id={`admin-post-row-${p.id}`}
className={cn(highlightId === p.id && 'admin-row-highlight')}
>
<td>{p.id}</td> <td>{p.id}</td>
<td className="max-w-[200px] truncate"> <td className="max-w-[200px] truncate">
<button type="button" className="admin-text-link" onClick={() => nav(`/post/${p.id}`)}> <button type="button" className="admin-text-link" onClick={() => nav(`/post/${p.id}`)}>

File diff suppressed because it is too large Load Diff

View File

@@ -89,6 +89,25 @@ export function formatTime(iso: string) {
return `${d.getFullYear()}${d.getMonth() + 1}${d.getDate()}`; return `${d.getFullYear()}${d.getMonth() + 1}${d.getDate()}`;
} }
/** 会话列表时间:今天 HH:mm同年 M月D日更早含年 */
export function formatConvListTime(iso: string) {
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return iso;
const now = new Date();
const pad = (n: number) => String(n).padStart(2, '0');
if (
d.getFullYear() === now.getFullYear()
&& d.getMonth() === now.getMonth()
&& d.getDate() === now.getDate()
) {
return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
if (d.getFullYear() === now.getFullYear()) {
return `${d.getMonth() + 1}${d.getDate()}`;
}
return `${d.getFullYear()}${d.getMonth() + 1}${d.getDate()}`;
}
/** 完整日期时间(用于帖子发布/修改时间展示) */ /** 完整日期时间(用于帖子发布/修改时间展示) */
export function formatDateTime(iso: string) { export function formatDateTime(iso: string) {
const d = new Date(iso); const d = new Date(iso);

View File

@@ -44,7 +44,7 @@ export type HomeBootPayload = {
recent_comments: RecentComment[]; recent_comments: RecentComment[];
recent_users: RecentUser[]; recent_users: RecentUser[];
tags: TagCount[]; tags: TagCount[];
showcase: CommunityShowcaseItem[]; showcase?: CommunityShowcaseItem[];
pages: SitePageSummary[]; pages: SitePageSummary[];
limits: ForumLimitsPublic; limits: ForumLimitsPublic;
branding: SiteBranding; branding: SiteBranding;
@@ -77,7 +77,10 @@ export function consumeHomeBoot(): HomeBootPayload | null {
if (Array.isArray(boot.recent_comments)) setCachedRecentComments(boot.recent_comments); if (Array.isArray(boot.recent_comments)) setCachedRecentComments(boot.recent_comments);
if (Array.isArray(boot.recent_users)) setCachedRecentUsers(boot.recent_users); if (Array.isArray(boot.recent_users)) setCachedRecentUsers(boot.recent_users);
if (Array.isArray(boot.tags)) setCachedTags(boot.tags); if (Array.isArray(boot.tags)) setCachedTags(boot.tags);
if (Array.isArray(boot.showcase)) setSessionSnapshot('showcase', boot.showcase); // 仅当 boot 显式带 showcase 时灌入(侧栏关闭时省略,避免 [] 粘死)
if ('showcase' in boot && Array.isArray(boot.showcase)) {
setSessionSnapshot('showcase', boot.showcase);
}
// 鉴权 / 签到:有 user 字段即种子(含 null = 已确认访客) // 鉴权 / 签到:有 user 字段即种子(含 null = 已确认访客)
if ('user' in boot) { if ('user' in boot) {

View File

@@ -421,13 +421,18 @@ func (h *Handlers) APIAdminRejectComment(c *gin.Context) {
title = "未知帖子" title = "未知帖子"
} }
pid := comment.PostID pid := comment.PostID
_, _ = h.Message.SendSystem( cid := comment.ID
floor := comment.Floor
_, _ = h.Message.SendSystemWithRefs(
comment.UserID, comment.UserID,
"评论未通过审核", "评论未通过审核",
service.FormatCommentRejectContent(title, comment.PostID, comment.Floor, reason), service.FormatCommentRejectContent(title, comment.PostID, comment.Floor, reason),
model.MessageKindReject, model.MessageKindReject,
&pid, service.SystemNotifyRefs{
nil, PostID: &pid,
CommentID: &cid,
Floor: &floor,
},
) )
} }
c.JSON(http.StatusOK, gin.H{"message": "已拒绝该评论并通知作者", "status": model.ContentStatusRejected}) c.JSON(http.StatusOK, gin.H{"message": "已拒绝该评论并通知作者", "status": model.ContentStatusRejected})

View File

@@ -136,6 +136,20 @@ func (h *Handlers) APIMarkNotificationsRead(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "通知已全部标为已读"}) c.JSON(http.StatusOK, gin.H{"message": "通知已全部标为已读"})
} }
// APIMarkMessageRead 单条消息已读
func (h *Handlers) APIMarkMessageRead(c *gin.Context) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || id == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的消息"})
return
}
if err := h.Message.MarkMessageRead(h.currentUserID(c), uint(id)); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "已标为已读"})
}
// APISendMessage 发送私信 // APISendMessage 发送私信
func (h *Handlers) APISendMessage(c *gin.Context) { func (h *Handlers) APISendMessage(c *gin.Context) {
var req struct { var req struct {

View File

@@ -36,7 +36,8 @@ type homeBootPayload struct {
RecentComments []service.RecentCommentItem `json:"recent_comments"` RecentComments []service.RecentCommentItem `json:"recent_comments"`
RecentUsers []service.RecentUserItem `json:"recent_users"` RecentUsers []service.RecentUserItem `json:"recent_users"`
Tags []service.TagCount `json:"tags"` Tags []service.TagCount `json:"tags"`
Showcase []service.CommunityShowcaseItem `json:"showcase"` // omitempty侧栏关闭或未拉取时不写字段避免 SPA 把 [] 当成有效会话快照
Showcase []service.CommunityShowcaseItem `json:"showcase,omitempty"`
Pages []service.SitePageSummary `json:"pages"` Pages []service.SitePageSummary `json:"pages"`
Limits service.ForumLimitsPublic `json:"limits"` Limits service.ForumLimitsPublic `json:"limits"`
Branding service.SiteBranding `json:"branding"` Branding service.SiteBranding `json:"branding"`
@@ -261,13 +262,15 @@ func (h *Handlers) gatherHomeSSR(c *gin.Context, boardID uint) (*homeSSRData, er
go func() { go func() {
defer wg.Done() defer wg.Done()
items, err := h.Community.ListShowcase(c.Request.Host) items, err := h.Community.ListShowcase(c.Request.Host)
if err != nil || items == nil { if err != nil {
// 失败不写 showcase让前端自行请求避免假空粘死
return
}
if items == nil {
items = []service.CommunityShowcaseItem{} items = []service.CommunityShowcaseItem{}
} }
out.boot.Showcase = items out.boot.Showcase = items
}() }()
} else {
out.boot.Showcase = []service.CommunityShowcaseItem{}
} }
uid := h.currentUserID(c) uid := h.currentUserID(c)

View File

@@ -234,8 +234,12 @@ type PrivateMessage struct {
Kind string `gorm:"size:32;default:user;index" json:"kind"` Kind string `gorm:"size:32;default:user;index" json:"kind"`
RelatedPostID *uint `gorm:"index" json:"related_post_id,omitempty"` RelatedPostID *uint `gorm:"index" json:"related_post_id,omitempty"`
RelatedReportID *uint `gorm:"index" json:"related_report_id,omitempty"` RelatedReportID *uint `gorm:"index" json:"related_report_id,omitempty"`
RelatedCommentID *uint `gorm:"index" json:"related_comment_id,omitempty"`
RelatedFloor *int `json:"related_floor,omitempty"` // 评论自身楼号,对应 #floor-N
IsRead bool `gorm:"default:false;index" json:"is_read"` IsRead bool `gorm:"default:false;index" json:"is_read"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
// RelatedStatus 列表接口实时回填pending|published|rejected|deleted不落库
RelatedStatus string `json:"related_status,omitempty" gorm:"-"`
FromUser User `gorm:"foreignKey:FromUserID" json:"from_user,omitempty"` FromUser User `gorm:"foreignKey:FromUserID" json:"from_user,omitempty"`
ToUser User `gorm:"foreignKey:ToUserID" json:"to_user,omitempty"` ToUser User `gorm:"foreignKey:ToUserID" json:"to_user,omitempty"`

View File

@@ -195,6 +195,7 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
api.GET("/messages/unread-count", h.APIMessageUnreadCount) api.GET("/messages/unread-count", h.APIMessageUnreadCount)
api.GET("/messages/notifications", h.APIMessageNotifications) api.GET("/messages/notifications", h.APIMessageNotifications)
api.POST("/messages/notifications/read", h.APIMarkNotificationsRead) api.POST("/messages/notifications/read", h.APIMarkNotificationsRead)
api.POST("/messages/:id/read", h.APIMarkMessageRead)
api.GET("/messages/conversations", h.APIMessageConversations) api.GET("/messages/conversations", h.APIMessageConversations)
api.GET("/messages/conversations/:peerId", h.APIConversationMessages) api.GET("/messages/conversations/:peerId", h.APIConversationMessages)
api.POST("/messages/conversations/:peerId/read", h.APIMarkConversationRead) api.POST("/messages/conversations/:peerId/read", h.APIMarkConversationRead)

View File

@@ -3,11 +3,13 @@ package service
import ( import (
"errors" "errors"
"fmt" "fmt"
"regexp"
"strings" "strings"
"time" "time"
"unicode/utf8" "unicode/utf8"
"git.iioio.com/freefire/jiang13-forum/model" "git.iioio.com/freefire/jiang13-forum/model"
"gorm.io/gorm"
) )
var ( var (
@@ -31,6 +33,8 @@ type MessageSendInput struct {
Kind string Kind string
RelatedPostID *uint RelatedPostID *uint
RelatedReportID *uint RelatedReportID *uint
RelatedCommentID *uint
RelatedFloor *int
} }
// Send 发送私信(用户互发或系统通知) // Send 发送私信(用户互发或系统通知)
@@ -89,6 +93,8 @@ func (s *MessageService) Send(in MessageSendInput) (*model.PrivateMessage, error
Kind: kind, Kind: kind,
RelatedPostID: in.RelatedPostID, RelatedPostID: in.RelatedPostID,
RelatedReportID: in.RelatedReportID, RelatedReportID: in.RelatedReportID,
RelatedCommentID: in.RelatedCommentID,
RelatedFloor: in.RelatedFloor,
IsRead: false, IsRead: false,
} }
if err := model.DB.Create(msg).Error; err != nil { if err := model.DB.Create(msg).Error; err != nil {
@@ -98,8 +104,24 @@ func (s *MessageService) Send(in MessageSendInput) (*model.PrivateMessage, error
return msg, nil return msg, nil
} }
// SystemNotifyRefs 系统通知关联目标(帖子 / 评论 / 举报)
type SystemNotifyRefs struct {
PostID *uint
ReportID *uint
CommentID *uint
Floor *int
}
// SendSystem 系统私信(管理员/系统 → 用户) // SendSystem 系统私信(管理员/系统 → 用户)
func (s *MessageService) SendSystem(toUserID uint, subject, content, kind string, relatedPostID, relatedReportID *uint) (*model.PrivateMessage, error) { func (s *MessageService) SendSystem(toUserID uint, subject, content, kind string, relatedPostID, relatedReportID *uint) (*model.PrivateMessage, error) {
return s.SendSystemWithRefs(toUserID, subject, content, kind, SystemNotifyRefs{
PostID: relatedPostID,
ReportID: relatedReportID,
})
}
// SendSystemWithRefs 系统私信(可附带评论楼层深链)
func (s *MessageService) SendSystemWithRefs(toUserID uint, subject, content, kind string, refs SystemNotifyRefs) (*model.PrivateMessage, error) {
if kind == "" { if kind == "" {
kind = model.MessageKindSystem kind = model.MessageKindSystem
} }
@@ -109,11 +131,27 @@ func (s *MessageService) SendSystem(toUserID uint, subject, content, kind string
Subject: subject, Subject: subject,
Content: content, Content: content,
Kind: kind, Kind: kind,
RelatedPostID: relatedPostID, RelatedPostID: refs.PostID,
RelatedReportID: relatedReportID, RelatedReportID: refs.ReportID,
RelatedCommentID: refs.CommentID,
RelatedFloor: refs.Floor,
}) })
} }
// MarkMessageRead 将单条消息标为已读(仅收件人本人)
func (s *MessageService) MarkMessageRead(userID, messageID uint) error {
if messageID == 0 {
return errors.New("无效的消息")
}
res := model.DB.Model(&model.PrivateMessage{}).
Where("id = ? AND to_user_id = ? AND is_read = ?", messageID, userID, false).
Update("is_read", true)
if res.Error != nil {
return res.Error
}
return nil
}
// MarkAllRead 全部标为已读 // MarkAllRead 全部标为已读
func (s *MessageService) MarkAllRead(userID uint) error { func (s *MessageService) MarkAllRead(userID uint) error {
return model.DB.Model(&model.PrivateMessage{}). return model.DB.Model(&model.PrivateMessage{}).
@@ -175,9 +213,212 @@ func (s *MessageService) ListNotifications(userID uint, page, size int, kind str
if list == nil { if list == nil {
list = []model.PrivateMessage{} list = []model.PrivateMessage{}
} }
s.enrichModerationStatus(list)
return list, total, nil return list, total, nil
} }
// enrichModerationStatus 为待审通知回填目标当前审核状态
func (s *MessageService) enrichModerationStatus(list []model.PrivateMessage) {
if len(list) == 0 {
return
}
resolvedByIndex := enrichModerationCommentIDs(list)
commentIDs := make([]uint, 0, len(list))
postIDs := make([]uint, 0, len(list))
// 历史评论通知:按帖+楼层回查(兜底)
type pfKey struct {
PostID uint
Floor int
}
pfNeeded := make([]pfKey, 0, len(list))
seenC := map[uint]struct{}{}
seenP := map[uint]struct{}{}
seenPF := map[pfKey]struct{}{}
for i := range list {
m := &list[i]
if m.Kind != model.MessageKindModeration {
continue
}
if m.RelatedCommentID != nil && *m.RelatedCommentID > 0 {
id := *m.RelatedCommentID
if _, ok := seenC[id]; !ok {
seenC[id] = struct{}{}
commentIDs = append(commentIDs, id)
}
continue
}
if cid, ok := resolvedByIndex[i]; ok && cid > 0 {
if _, ok := seenC[cid]; !ok {
seenC[cid] = struct{}{}
commentIDs = append(commentIDs, cid)
}
continue
}
if m.RelatedPostID == nil || *m.RelatedPostID == 0 {
continue
}
pid := *m.RelatedPostID
if looksLikeModerationComment(m.Subject, m.Content) {
floor := 0
if m.RelatedFloor != nil && *m.RelatedFloor > 0 {
floor = *m.RelatedFloor
} else {
floor = parseNotifyFloor(m.Content)
}
if floor > 0 {
k := pfKey{PostID: pid, Floor: floor}
if _, ok := seenPF[k]; !ok {
seenPF[k] = struct{}{}
pfNeeded = append(pfNeeded, k)
}
}
continue
}
if _, ok := seenP[pid]; !ok {
seenP[pid] = struct{}{}
postIDs = append(postIDs, pid)
}
}
commentStatus := map[uint]string{}
if len(commentIDs) > 0 {
type row struct {
ID uint
Status string
DeletedAt gorm.DeletedAt
}
var rows []row
_ = model.DB.Unscoped().Model(&model.Comment{}).
Select("id", "status", "deleted_at").
Where("id IN ?", commentIDs).
Find(&rows)
for _, r := range rows {
commentStatus[r.ID] = contentStatusOrDeleted(r.Status, r.DeletedAt)
}
for _, id := range commentIDs {
if _, ok := commentStatus[id]; !ok {
commentStatus[id] = "deleted"
}
}
}
statusByPF := map[pfKey]string{}
if len(pfNeeded) > 0 {
postSet := map[uint]struct{}{}
for _, k := range pfNeeded {
postSet[k.PostID] = struct{}{}
}
pids := make([]uint, 0, len(postSet))
for id := range postSet {
pids = append(pids, id)
}
type row struct {
PostID uint
Floor int
Status string
DeletedAt gorm.DeletedAt
}
var rows []row
_ = model.DB.Unscoped().Model(&model.Comment{}).
Select("post_id", "floor", "status", "deleted_at").
Where("post_id IN ?", pids).
Find(&rows)
for _, r := range rows {
k := pfKey{PostID: r.PostID, Floor: r.Floor}
// 同楼多条时后者覆盖;正常业务一帖一楼唯一
statusByPF[k] = contentStatusOrDeleted(r.Status, r.DeletedAt)
}
for _, k := range pfNeeded {
if _, ok := statusByPF[k]; !ok {
statusByPF[k] = "deleted"
}
}
}
postStatus := map[uint]string{}
if len(postIDs) > 0 {
type row struct {
ID uint
Status string
DeletedAt gorm.DeletedAt
}
var rows []row
_ = model.DB.Unscoped().Model(&model.Post{}).
Select("id", "status", "deleted_at").
Where("id IN ?", postIDs).
Find(&rows)
for _, r := range rows {
postStatus[r.ID] = contentStatusOrDeleted(r.Status, r.DeletedAt)
}
for _, id := range postIDs {
if _, ok := postStatus[id]; !ok {
postStatus[id] = "deleted"
}
}
}
for i := range list {
m := &list[i]
if m.Kind != model.MessageKindModeration {
continue
}
if m.RelatedCommentID != nil && *m.RelatedCommentID > 0 {
m.RelatedStatus = commentStatus[*m.RelatedCommentID]
continue
}
if cid, ok := resolvedByIndex[i]; ok && cid > 0 {
m.RelatedStatus = commentStatus[cid]
continue
}
if m.RelatedPostID == nil || *m.RelatedPostID == 0 {
continue
}
pid := *m.RelatedPostID
if looksLikeModerationComment(m.Subject, m.Content) {
floor := 0
if m.RelatedFloor != nil && *m.RelatedFloor > 0 {
floor = *m.RelatedFloor
} else {
floor = parseNotifyFloor(m.Content)
}
if floor > 0 {
m.RelatedStatus = statusByPF[pfKey{PostID: pid, Floor: floor}]
}
continue
}
m.RelatedStatus = postStatus[pid]
}
}
var notifyFloorRe = regexp.MustCompile(`#(\d+)\s*楼`)
// parseNotifyFloor 从待审评论文案解析楼号(如「#2 楼评论」「#1 楼下」)
func parseNotifyFloor(content string) int {
m := notifyFloorRe.FindStringSubmatch(content)
if len(m) < 2 {
return 0
}
var n int
_, _ = fmt.Sscanf(m[1], "%d", &n)
if n < 0 {
return 0
}
return n
}
func contentStatusOrDeleted(status string, deletedAt gorm.DeletedAt) string {
if deletedAt.Valid {
return "deleted"
}
if status != "" {
return status
}
return model.ContentStatusPublished
}
// MarkNotificationsRead 将系统通知全部标为已读 // MarkNotificationsRead 将系统通知全部标为已读
func (s *MessageService) MarkNotificationsRead(userID uint) error { func (s *MessageService) MarkNotificationsRead(userID uint) error {
return s.MarkConversationRead(userID, 0) return s.MarkConversationRead(userID, 0)

View File

@@ -0,0 +1,166 @@
package service
import (
"math"
"strings"
"time"
"git.iioio.com/freefire/jiang13-forum/model"
)
// looksLikeModerationComment 判断待审通知是否指向评论(含嵌套回复)
func looksLikeModerationComment(subject, content string) bool {
if strings.Contains(subject, "评论") || strings.Contains(content, "评论") {
return true
}
return strings.Contains(content, "回复") || strings.Contains(content, "楼下")
}
// isNestedModerationContent 嵌套回复待审(正文为「#N 楼下…」)
func isNestedModerationContent(content string) bool {
return strings.Contains(content, "楼下")
}
// resolveModerationCommentRef 为历史待审评论通知推断目标评论 ID 与自身楼号
func resolveModerationCommentRef(postID uint, content string, notifyAt time.Time) (commentID uint, floor int) {
if postID == 0 || model.DB == nil {
return 0, 0
}
displayFloor := parseNotifyFloor(content)
if displayFloor <= 0 {
return 0, 0
}
if isNestedModerationContent(content) {
var parent struct {
ID uint
}
err := model.DB.Unscoped().Model(&model.Comment{}).
Select("id").
Where("post_id = ? AND floor = ?", postID, displayFloor).
First(&parent).Error
if err != nil || parent.ID == 0 {
return 0, 0
}
type childRow struct {
ID uint
Floor int
CreatedAt time.Time
}
var children []childRow
_ = model.DB.Unscoped().Model(&model.Comment{}).
Select("id", "floor", "created_at").
Where("post_id = ? AND reply_to = ?", postID, parent.ID).
Find(&children).Error
if len(children) == 0 {
return 0, 0
}
if len(children) == 1 {
return children[0].ID, children[0].Floor
}
best := children[0]
bestDiff := math.MaxFloat64
for _, c := range children {
diff := math.Abs(float64(c.CreatedAt.Sub(notifyAt)))
if diff < bestDiff {
bestDiff = diff
best = c
}
}
// 通知与评论创建时间相差超过 7 天则放弃,避免误配旧回复
if bestDiff > float64(7*24*time.Hour) {
return 0, 0
}
return best.ID, best.Floor
}
var row struct {
ID uint
Floor int
}
err := model.DB.Unscoped().Model(&model.Comment{}).
Select("id", "floor").
Where("post_id = ? AND floor = ?", postID, displayFloor).
First(&row).Error
if err != nil || row.ID == 0 {
return 0, 0
}
return row.ID, row.Floor
}
// BackfillModerationNotifyRefs 为历史 moderation 通知补写 related_comment_id / related_floor
func BackfillModerationNotifyRefs() error {
if model.DB == nil {
return nil
}
var rows []model.PrivateMessage
err := model.DB.Where("kind = ? AND (related_comment_id IS NULL OR related_comment_id = 0)", model.MessageKindModeration).
Find(&rows).Error
if err != nil {
return err
}
for _, m := range rows {
if m.RelatedPostID == nil || *m.RelatedPostID == 0 {
continue
}
if !looksLikeModerationComment(m.Subject, m.Content) {
continue
}
cid, fl := resolveModerationCommentRef(*m.RelatedPostID, m.Content, m.CreatedAt)
if cid == 0 {
continue
}
floor := fl
updates := map[string]interface{}{
"related_comment_id": cid,
"related_floor": floor,
}
_ = model.DB.Model(&model.PrivateMessage{}).Where("id = ?", m.ID).Updates(updates).Error
}
return nil
}
// enrichModerationCommentIDs 为无 related_comment_id 的评论类待审通知解析评论 ID
func enrichModerationCommentIDs(list []model.PrivateMessage) map[int]uint {
out := make(map[int]uint)
for i := range list {
m := &list[i]
if m.Kind != model.MessageKindModeration {
continue
}
if m.RelatedCommentID != nil && *m.RelatedCommentID > 0 {
continue
}
if m.RelatedPostID == nil || *m.RelatedPostID == 0 {
continue
}
if !looksLikeModerationComment(m.Subject, m.Content) {
continue
}
// 嵌套回复优先按子评论匹配,避免 displayFloor 查到父评论状态
if isNestedModerationContent(m.Content) {
cid, _ := resolveModerationCommentRef(*m.RelatedPostID, m.Content, m.CreatedAt)
if cid > 0 {
out[i] = cid
}
continue
}
// 顶层评论:有 related_floor 时按楼号查 ID
if m.RelatedFloor != nil && *m.RelatedFloor > 0 {
var row struct{ ID uint }
if err := model.DB.Unscoped().Model(&model.Comment{}).
Select("id").
Where("post_id = ? AND floor = ?", *m.RelatedPostID, *m.RelatedFloor).
First(&row).Error; err == nil && row.ID > 0 {
out[i] = row.ID
}
continue
}
cid, _ := resolveModerationCommentRef(*m.RelatedPostID, m.Content, m.CreatedAt)
if cid > 0 {
out[i] = cid
}
}
return out
}

View File

@@ -0,0 +1,61 @@
package service
import (
"os"
"path/filepath"
"testing"
"git.iioio.com/freefire/jiang13-forum/model"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
)
// TestProductionDBModerationEnrich 用本地生产库拷贝验证 related_status 回填(无库则跳过)
func TestProductionDBModerationEnrich(t *testing.T) {
dbPath := filepath.Join("..", "dist", "data", "jiang13.db")
if _, err := os.Stat(dbPath); err != nil {
t.Skip("dist/data/jiang13.db 不存在,跳过")
}
db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
model.DB = db
if err := BackfillModerationNotifyRefs(); err != nil {
t.Fatal(err)
}
var adminID uint
if err := db.Model(&model.User{}).Where("role = ?", model.RoleAdmin).Order("id asc").Limit(1).Pluck("id", &adminID).Error; err != nil || adminID == 0 {
t.Skip("无管理员用户,跳过")
}
svc := &MessageService{}
list, _, err := svc.ListNotifications(adminID, 1, 100, "moderation")
if err != nil {
t.Fatal(err)
}
if len(list) == 0 {
t.Skip("无 moderation 通知")
}
pendingUI := 0
published := 0
for _, m := range list {
if m.RelatedStatus == model.ContentStatusPublished {
published++
} else if m.RelatedStatus == "" || m.RelatedStatus == model.ContentStatusPending {
pendingUI++
t.Logf("仍无 published 状态: id=%d subject=%q status=%q content=%q", m.ID, m.Subject, m.RelatedStatus, m.Content)
}
}
t.Logf("moderation=%d published=%d pending_or_empty=%d", len(list), published, pendingUI)
if published == 0 {
t.Fatal("没有任何 moderation 通知回填为 published")
}
if pendingUI > 0 {
t.Fatalf("%d 条通知仍会被 UI 判为待审", pendingUI)
}
}

View File

@@ -0,0 +1,102 @@
package service
import (
"testing"
"time"
"git.iioio.com/freefire/jiang13-forum/model"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
)
func TestParseNotifyFloor(t *testing.T) {
cases := map[string]int{
"用户 X 在《Y》提交了待审核 #2 楼评论": 2,
"用户 X 在《Y》#3 楼下提交了待审核回复": 3,
"无楼号": 0,
}
for content, want := range cases {
if got := parseNotifyFloor(content); got != want {
t.Errorf("parseNotifyFloor(%q) = %d, want %d", content, got, want)
}
}
}
func TestEnrichModerationStatusPublished(t *testing.T) {
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&model.User{}, &model.Post{}, &model.Comment{}, &model.PrivateMessage{}); err != nil {
t.Fatal(err)
}
model.DB = db
post := model.Post{Title: "测试帖", Status: model.ContentStatusPublished, UserID: 1}
if err := db.Create(&post).Error; err != nil {
t.Fatal(err)
}
comment := model.Comment{
PostID: post.ID, UserID: 2, Floor: 2,
Status: model.ContentStatusPublished,
}
if err := db.Create(&comment).Error; err != nil {
t.Fatal(err)
}
pid := post.ID
msg := model.PrivateMessage{
FromUserID: 0,
ToUserID: 1,
Subject: "新的待审核评论",
Content: "用户 A 在《测试帖》提交了待审核 #2 楼评论",
Kind: model.MessageKindModeration,
RelatedPostID: &pid,
CreatedAt: time.Now(),
}
if err := db.Create(&msg).Error; err != nil {
t.Fatal(err)
}
svc := &MessageService{}
list := []model.PrivateMessage{msg}
svc.enrichModerationStatus(list)
if list[0].RelatedStatus != model.ContentStatusPublished {
t.Fatalf("RelatedStatus = %q, want published", list[0].RelatedStatus)
}
}
func TestResolveNestedModerationCommentRef(t *testing.T) {
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&model.Post{}, &model.Comment{}); err != nil {
t.Fatal(err)
}
model.DB = db
post := model.Post{Title: "嵌套", Status: model.ContentStatusPublished}
if err := db.Create(&post).Error; err != nil {
t.Fatal(err)
}
parent := model.Comment{PostID: post.ID, Floor: 1, Status: model.ContentStatusPublished}
child := model.Comment{
PostID: post.ID, Floor: 3, Status: model.ContentStatusPublished,
}
if err := db.Create(&parent).Error; err != nil {
t.Fatal(err)
}
rt := parent.ID
child.ReplyTo = &rt
child.CreatedAt = time.Now()
if err := db.Create(&child).Error; err != nil {
t.Fatal(err)
}
notifyAt := child.CreatedAt.Add(2 * time.Second)
cid, floor := resolveModerationCommentRef(post.ID, "用户 A 在《嵌套》#1 楼下提交了待审核回复", notifyAt)
if cid != child.ID || floor != 3 {
t.Fatalf("resolve = (%d, %d), want (%d, 3)", cid, floor, child.ID)
}
}

View File

@@ -96,9 +96,15 @@ func (s *NotifyService) NotifyCommentPublished(comment *model.Comment) {
subject := "收到新回复" subject := "收到新回复"
content := FormatReplyContent(authorName, title, displayFloor, isNested) content := FormatReplyContent(authorName, title, displayFloor, isNested)
pid := comment.PostID pid := comment.PostID
_, _ = s.messages.SendSystem(toUserID, subject, content, model.MessageKindReply, &pid, nil) cid := comment.ID
floor := comment.Floor
_, _ = s.messages.SendSystemWithRefs(toUserID, subject, content, model.MessageKindReply, SystemNotifyRefs{
PostID: &pid,
CommentID: &cid,
Floor: &floor,
})
s.sendReplyMail(toUserID, authorName, title, comment.PostID, displayFloor, isNested, comment.Content) s.sendReplyMail(toUserID, authorName, title, comment.PostID, comment.Floor, displayFloor, isNested, comment.Content)
} }
// NotifyCommentMentions 评论公开后通知被 @提及的用户(跳过已收到回复通知的人) // NotifyCommentMentions 评论公开后通知被 @提及的用户(跳过已收到回复通知的人)
@@ -125,6 +131,8 @@ func (s *NotifyService) NotifyCommentMentions(comment *model.Comment) {
} }
displayFloor := s.resolveDisplayFloor(comment) displayFloor := s.resolveDisplayFloor(comment)
pid := comment.PostID pid := comment.PostID
cid := comment.ID
floor := comment.Floor
subject := "有人 @了你" subject := "有人 @了你"
content := FormatMentionContent(authorName, title, displayFloor) content := FormatMentionContent(authorName, title, displayFloor)
@@ -132,7 +140,11 @@ func (s *NotifyService) NotifyCommentMentions(comment *model.Comment) {
if uid == 0 || uid == comment.UserID || uid == replyTo { if uid == 0 || uid == comment.UserID || uid == replyTo {
continue continue
} }
_, _ = s.messages.SendSystem(uid, subject, content, model.MessageKindMention, &pid, nil) _, _ = s.messages.SendSystemWithRefs(uid, subject, content, model.MessageKindMention, SystemNotifyRefs{
PostID: &pid,
CommentID: &cid,
Floor: &floor,
})
} }
} }
@@ -149,8 +161,9 @@ func (s *NotifyService) NotifyPendingPost(post *model.Post) {
subject := "新的待审核帖子" subject := "新的待审核帖子"
content := FormatPendingPostContent(authorName, title, post.ID) content := FormatPendingPostContent(authorName, title, post.ID)
pid := post.ID pid := post.ID
s.notifyAdmins(subject, content, model.MessageKindModeration, &pid, func(siteName, baseURL string) (string, string, string) { s.notifyAdmins(subject, content, model.MessageKindModeration, SystemNotifyRefs{PostID: &pid}, func(siteName, baseURL string) (string, string, string) {
return BuildModerationMail(siteName, "帖子", authorName, title, post.ID, 0, false, AbsoluteURL(baseURL, "/admin/posts")) adminPath := fmt.Sprintf("/admin/posts?id=%d", post.ID)
return BuildModerationMail(siteName, "帖子", authorName, title, post.ID, 0, false, AbsoluteURL(baseURL, adminPath))
}) })
} }
@@ -173,14 +186,21 @@ func (s *NotifyService) NotifyPendingComment(comment *model.Comment) {
isNested := comment.ReplyTo != nil && *comment.ReplyTo > 0 isNested := comment.ReplyTo != nil && *comment.ReplyTo > 0
content := FormatPendingCommentContent(authorName, title, displayFloor, isNested) content := FormatPendingCommentContent(authorName, title, displayFloor, isNested)
pid := comment.PostID pid := comment.PostID
s.notifyAdmins(subject, content, model.MessageKindModeration, &pid, func(siteName, baseURL string) (string, string, string) { cid := comment.ID
return BuildModerationMail(siteName, "评论", authorName, title, comment.PostID, displayFloor, isNested, AbsoluteURL(baseURL, "/admin/comments")) floor := comment.Floor
adminPath := fmt.Sprintf("/admin/comments?id=%d", comment.ID)
s.notifyAdmins(subject, content, model.MessageKindModeration, SystemNotifyRefs{
PostID: &pid,
CommentID: &cid,
Floor: &floor,
}, func(siteName, baseURL string) (string, string, string) {
return BuildModerationMail(siteName, "评论", authorName, title, comment.PostID, displayFloor, isNested, AbsoluteURL(baseURL, adminPath))
}) })
} }
func (s *NotifyService) notifyAdmins( func (s *NotifyService) notifyAdmins(
subject, content, kind string, subject, content, kind string,
relatedPostID *uint, refs SystemNotifyRefs,
buildMail func(siteName, baseURL string) (subj, text, html string), buildMail func(siteName, baseURL string) (subj, text, html string),
) { ) {
admins, err := s.listAdmins() admins, err := s.listAdmins()
@@ -197,7 +217,7 @@ func (s *NotifyService) notifyAdmins(
} }
for _, admin := range admins { for _, admin := range admins {
_, _ = s.messages.SendSystem(admin.ID, subject, content, kind, relatedPostID, nil) _, _ = s.messages.SendSystemWithRefs(admin.ID, subject, content, kind, refs)
email := strings.TrimSpace(admin.Email) email := strings.TrimSpace(admin.Email)
if email == "" || mailSubj == "" { if email == "" || mailSubj == "" {
continue continue
@@ -211,7 +231,7 @@ func (s *NotifyService) notifyAdmins(
} }
} }
func (s *NotifyService) sendReplyMail(toUserID uint, authorName, postTitle string, postID uint, displayFloor int, isNested bool, rawContent string) { func (s *NotifyService) sendReplyMail(toUserID uint, authorName, postTitle string, postID uint, ownFloor, displayFloor int, isNested bool, rawContent string) {
if s.mail == nil || !s.settings.MailReady() { if s.mail == nil || !s.settings.MailReady() {
return return
} }
@@ -227,6 +247,10 @@ func (s *NotifyService) sendReplyMail(toUserID uint, authorName, postTitle strin
baseURL := s.settings.SitePublicBaseURL("") baseURL := s.settings.SitePublicBaseURL("")
postPath := s.settings.Permalink().PostPath(postID) postPath := s.settings.Permalink().PostPath(postID)
link := AbsoluteURL(baseURL, postPath) link := AbsoluteURL(baseURL, postPath)
// 直达评论自身楼层(嵌套回复也有独立 floor
if ownFloor > 0 {
link = fmt.Sprintf("%s#floor-%d", link, ownFloor)
}
excerpt := truncateNotifyExcerpt(rawContent, 120) excerpt := truncateNotifyExcerpt(rawContent, 120)
subj, text, html := BuildReplyMail(siteName, authorName, postTitle, displayFloor, isNested, excerpt, link) subj, text, html := BuildReplyMail(siteName, authorName, postTitle, displayFloor, isNested, excerpt, link)
_ = s.mail.SendHTML(email, subj, text, html) _ = s.mail.SendHTML(email, subj, text, html)

View File

@@ -305,14 +305,20 @@ func (s *ReportService) Handle(in HandleReportInput) (*model.PostReport, error)
if commentAuthorID > 0 { if commentAuthorID > 0 {
pid := postID pid := postID
rid := rep.ID rid := rep.ID
cid := *rep.CommentID
floor := commentFloor
body := fmt.Sprintf("你在帖子《%s》下的评论#%d未通过审核。\n\n原因\n%s", postTitle, commentFloor, reason) body := fmt.Sprintf("你在帖子《%s》下的评论#%d未通过审核。\n\n原因\n%s", postTitle, commentFloor, reason)
_, _ = s.messages.SendSystem( _, _ = s.messages.SendSystemWithRefs(
commentAuthorID, commentAuthorID,
fmt.Sprintf("评论未通过审核 · 《%s》", postTitle), fmt.Sprintf("评论未通过审核 · 《%s》", postTitle),
body, body,
model.MessageKindReject, model.MessageKindReject,
&pid, SystemNotifyRefs{
&rid, PostID: &pid,
ReportID: &rid,
CommentID: &cid,
Floor: &floor,
},
) )
} }
default: default:
@@ -345,13 +351,19 @@ func (s *ReportService) Handle(in HandleReportInput) (*model.PostReport, error)
} }
pid := postID pid := postID
rid := rep.ID rid := rep.ID
_, _ = s.messages.SendSystem( resultRefs := SystemNotifyRefs{PostID: &pid, ReportID: &rid}
if isCommentReport && rep.CommentID != nil {
cid := *rep.CommentID
floor := commentFloor
resultRefs.CommentID = &cid
resultRefs.Floor = &floor
}
_, _ = s.messages.SendSystemWithRefs(
rep.ReporterID, rep.ReporterID,
"举报处理结果通知", "举报处理结果通知",
content, content,
model.MessageKindReportResult, model.MessageKindReportResult,
&pid, resultRefs,
&rid,
) )
_ = model.DB.Preload("Post", func(tx *gorm.DB) *gorm.DB { _ = model.DB.Preload("Post", func(tx *gorm.DB) *gorm.DB {