feat: 站点单页、时间线导入与行级 BBCode 短代码

首页右栏接入单页入口与公告置顶/全部页;Markdown 编辑器支持可视化时间线与 Git 导入;隐藏块改为 [hide]/[timeline] 命名闭合,并修复单页/公告 GORM 更新只改 updated_at 的问题。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-09-17 19:52:06 +08:00
parent 2aacf99a49
commit a83276060f
52 changed files with 5073 additions and 648 deletions

View File

@@ -1,9 +1,10 @@
// Package markdown 提供帖子正文隐藏块(:::hide)的解析、校验与脱敏。
// Package markdown 提供帖子正文隐藏块(行级 BBCode [hide]…[/hide])的解析、校验与脱敏。
package markdown
import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"unicode/utf8"
@@ -43,22 +44,25 @@ type DerivedAccess struct {
// ViewerCaps 读者对隐藏块的能力(由 service 填充)
type ViewerCaps struct {
Bypass bool // 作者 / 版主
LoggedIn bool
HasReplied bool
PointsPaid bool // 已支付本帖积分解锁
PasswordUnlocked map[int]bool // 已凭密码解锁的隐藏块下标
Bypass bool // 作者 / 版主
LoggedIn bool
HasReplied bool
PointsPaid bool // 已支付本帖积分解锁
PasswordUnlocked map[int]bool // 已凭密码解锁的隐藏块下标
}
var (
ErrHideNested = errors.New("隐藏块不可嵌套")
ErrHideUnclosed = errors.New("隐藏块未正确闭合")
ErrHideInvalid = errors.New("隐藏块语法无效")
ErrHidePointsNeed = errors.New("积分可见块须指定 1–100000 的积分")
ErrHidePasswordNeed = errors.New("密码可见块须设置 1–64 字符且不含空格的密码")
ErrHideNested = errors.New("隐藏块不可嵌套")
ErrHideUnclosed = errors.New("隐藏块未正确闭合")
ErrHideInvalid = errors.New("隐藏块语法无效")
ErrHidePointsNeed = errors.New("积分可见块须指定 1–100000 的积分")
ErrHidePasswordNeed = errors.New("密码可见块须设置 1–64 字符且不含空格的密码")
)
// ParseHideBlocks 扫描正文中的 :::hide 块(忽略代码围栏内伪语法)。
// 开标记:整行 [hide <kind> …];闭标记:整行 [/hide]
var hideOpenRe = regexp.MustCompile(`(?i)^\[hide(?:\s+(.+))?\]$`)
// ParseHideBlocks 扫描正文中的 [hide]…[/hide] 块(忽略代码围栏内伪语法)。
func ParseHideBlocks(content string) ([]HideBlock, error) {
lines := splitLines(content)
var blocks []HideBlock
@@ -175,7 +179,7 @@ func DeriveAccessFromContent(content string) (DerivedAccess, error) {
}
// SanitizeForViewer 按读者能力脱敏:未满足条件的块清空正文并加 locked。
// 密码块即使已解锁,也不向读者回传明文密码(开标记写成 :::hide password)。
// 密码块即使已解锁,也不向读者回传明文密码(开标记写成 [hide password] 或 [hide password locked])。
func SanitizeForViewer(content string, caps ViewerCaps) (sanitized string, fullyLocked bool) {
blocks, err := ParseHideBlocks(content)
if err != nil {
@@ -209,10 +213,10 @@ func SanitizeForViewer(content string, caps ViewerCaps) (sanitized string, fully
anyVisible = true
}
}
out = append(out, ":::")
out = append(out, "[/hide]")
} else {
out = append(out, openMarkerLine(b.Kind, b.Points, "", true))
out = append(out, ":::")
out = append(out, "[/hide]")
}
cursor = b.End + 1
}
@@ -249,16 +253,16 @@ func WrapContentAsHide(kind string, points int, content string) string {
body := strings.TrimRight(content, "\n")
open := openMarkerLine(kind, points, "", false)
if body == "" {
return open + "\n:::\n"
return open + "\n[/hide]\n"
}
return open + "\n" + body + "\n:::\n"
return open + "\n" + body + "\n[/hide]\n"
}
// HasHideBlocks 快速判断正文是否已含隐藏块(迁移幂等)
func HasHideBlocks(content string) bool {
blocks, err := ParseHideBlocks(content)
if err != nil {
return strings.Contains(content, ":::hide")
return strings.Contains(strings.ToLower(content), "[hide")
}
return len(blocks) > 0
}
@@ -281,28 +285,30 @@ func blockUnlocked(b HideBlock, caps ViewerCaps) bool {
// openMarkerLine 生成开标记。密码仅在原文存储时写入;对外脱敏输出传空 password。
func openMarkerLine(kind string, points int, password string, locked bool) string {
var b strings.Builder
b.WriteString(":::hide ")
b.WriteString("[hide ")
b.WriteString(kind)
if kind == HideKindPoints && points > 0 {
b.WriteByte(' ')
b.WriteString("=")
b.WriteString(strconv.Itoa(points))
}
if kind == HideKindPassword && password != "" && !locked {
b.WriteByte(' ')
b.WriteString("=")
b.WriteString(password)
}
if locked {
b.WriteString(" locked")
}
b.WriteByte(']')
return b.String()
}
// parseOpenMarker 解析 :::hide <kind> [points|password] [locked]
// parseOpenMarker 解析 [hide <kind>[=arg] [locked]]
func parseOpenMarker(trimmed string) (kind string, points int, password string, locked bool, ok bool) {
if !strings.HasPrefix(trimmed, ":::hide") {
m := hideOpenRe.FindStringSubmatch(trimmed)
if m == nil {
return "", 0, "", false, false
}
rest := strings.TrimSpace(trimmed[len(":::hide"):])
rest := strings.TrimSpace(m[1])
if rest == "" {
return "", 0, "", false, false
}
@@ -310,32 +316,43 @@ func parseOpenMarker(trimmed string) (kind string, points int, password string,
if len(parts) == 0 {
return "", 0, "", false, false
}
kind = parts[0]
head := parts[0]
kind = head
arg := ""
if i := strings.IndexByte(head, '='); i >= 0 {
kind = head[:i]
arg = head[i+1:]
}
kind = strings.ToLower(kind)
switch kind {
case HideKindLogin, HideKindReply, HideKindPoints, HideKindPassword:
default:
return "", 0, "", false, false
}
idx := 1
if kind == HideKindPoints {
if idx >= len(parts) {
if arg == "" {
return "", 0, "", false, false
}
n, err := strconv.Atoi(parts[idx])
n, err := strconv.Atoi(arg)
if err != nil {
return "", 0, "", false, false
}
points = n
idx++
} else if kind == HideKindPassword {
// 允许::::hide password locked(脱敏)或 :::hide password <pwd> [locked]
if idx < len(parts) && parts[idx] != "locked" {
password = parts[idx]
idx++
// [hide password=secret] 或脱敏 [hide password locked]
if arg != "" {
password = arg
}
} else if arg != "" {
// login/reply 不应带 =arg
return "", 0, "", false, false
}
for ; idx < len(parts); idx++ {
if parts[idx] == "locked" {
if strings.EqualFold(parts[idx], "locked") {
locked = true
} else {
return "", 0, "", false, false
@@ -356,7 +373,7 @@ func validatePassword(pwd string) error {
}
func isCloseMarker(trimmed string) bool {
return trimmed == ":::"
return strings.EqualFold(trimmed, "[/hide]")
}
func splitLines(s string) []string {
@@ -378,7 +395,7 @@ func ValidateHideContent(content string) error {
case errors.Is(err, ErrHideNested):
return fmt.Errorf("隐藏块不可嵌套")
case errors.Is(err, ErrHideUnclosed):
return fmt.Errorf("隐藏块未正确闭合,请检查 ::: 标记")
return fmt.Errorf("隐藏块未正确闭合,请检查 [/hide] 标记")
case errors.Is(err, ErrHidePointsNeed):
return fmt.Errorf("积分可见块须指定 1–100000 的积分")
case errors.Is(err, ErrHidePasswordNeed):

View File

@@ -6,7 +6,7 @@ import (
)
func TestParseIgnoreCodeFence(t *testing.T) {
src := "公开\n\n```\n:::hide login\n假的\n:::\n```\n\n结尾\n"
src := "公开\n\n```\n[hide login]\n假的\n[/hide]\n```\n\n结尾\n"
blocks, err := ParseHideBlocks(src)
if err != nil {
t.Fatal(err)
@@ -17,7 +17,7 @@ func TestParseIgnoreCodeFence(t *testing.T) {
}
func TestParseMixedAndDerive(t *testing.T) {
src := "公开段\n\n:::hide login\n登录内容\n:::\n\n:::hide points 10\n积分A\n:::\n\n:::hide points 5\n积分B\n:::\n"
src := "公开段\n\n[hide login]\n登录内容\n[/hide]\n\n[hide points=10]\n积分A\n[/hide]\n\n[hide points=5]\n积分B\n[/hide]\n"
blocks, err := ParseHideBlocks(src)
if err != nil {
t.Fatal(err)
@@ -35,7 +35,7 @@ func TestParseMixedAndDerive(t *testing.T) {
}
func TestParseNestedRejected(t *testing.T) {
src := ":::hide login\n外\n:::hide reply\n内\n:::\n:::\n"
src := "[hide login]\n外\n[hide reply]\n内\n[/hide]\n[/hide]\n"
_, err := ParseHideBlocks(src)
if err != ErrHideNested {
t.Fatalf("want ErrHideNested, got %v", err)
@@ -43,7 +43,7 @@ func TestParseNestedRejected(t *testing.T) {
}
func TestSanitizeLocksBody(t *testing.T) {
src := "公开\n\n:::hide login\n秘密内容\n:::\n\n尾\n"
src := "公开\n\n[hide login]\n秘密内容\n[/hide]\n\n尾\n"
out, fully := SanitizeForViewer(src, ViewerCaps{})
if fully {
t.Fatal("should not be fully locked")
@@ -51,7 +51,7 @@ func TestSanitizeLocksBody(t *testing.T) {
if strings.Contains(out, "秘密内容") {
t.Fatalf("leaked: %q", out)
}
if !strings.Contains(out, ":::hide login locked") {
if !strings.Contains(out, "[hide login locked]") {
t.Fatalf("missing locked marker: %q", out)
}
if !strings.Contains(out, "公开") || !strings.Contains(out, "尾") {
@@ -60,7 +60,7 @@ func TestSanitizeLocksBody(t *testing.T) {
}
func TestSanitizeUnlockLogin(t *testing.T) {
src := ":::hide login\n秘密\n:::\n"
src := "[hide login]\n秘密\n[/hide]\n"
out, fully := SanitizeForViewer(src, ViewerCaps{LoggedIn: true})
if fully {
t.Fatal("should see content")
@@ -74,7 +74,7 @@ func TestSanitizeUnlockLogin(t *testing.T) {
}
func TestSanitizeBypass(t *testing.T) {
src := ":::hide points 9\n付费\n:::\n"
src := "[hide points=9]\n付费\n[/hide]\n"
out, _ := SanitizeForViewer(src, ViewerCaps{Bypass: true})
if !strings.Contains(out, "付费") {
t.Fatalf("bypass failed: %q", out)
@@ -82,7 +82,7 @@ func TestSanitizeBypass(t *testing.T) {
}
func TestSanitizePointsPaid(t *testing.T) {
src := ":::hide points 3\n付费文\n:::\n"
src := "[hide points=3]\n付费文\n[/hide]\n"
out, _ := SanitizeForViewer(src, ViewerCaps{LoggedIn: true, PointsPaid: true})
if !strings.Contains(out, "付费文") {
t.Fatalf("paid unlock failed: %q", out)
@@ -90,7 +90,7 @@ func TestSanitizePointsPaid(t *testing.T) {
}
func TestFullyLocked(t *testing.T) {
src := ":::hide reply\n仅回复\n:::\n"
src := "[hide reply]\n仅回复\n[/hide]\n"
_, fully := SanitizeForViewer(src, ViewerCaps{LoggedIn: true})
if !fully {
t.Fatal("expected fully locked")
@@ -98,7 +98,7 @@ func TestFullyLocked(t *testing.T) {
}
func TestCodeInsideHide(t *testing.T) {
src := ":::hide login\n```\n:::hide reply\n伪\n:::\n```\n真\n:::\n"
src := "[hide login]\n```\n[hide reply]\n伪\n[/hide]\n```\n真\n[/hide]\n"
blocks, err := ParseHideBlocks(src)
if err != nil {
t.Fatal(err)
@@ -112,7 +112,7 @@ func TestCodeInsideHide(t *testing.T) {
}
func TestParsePasswordAndSanitize(t *testing.T) {
src := "公开\n\n:::hide password secret1\n密码内容\n:::\n"
src := "公开\n\n[hide password=secret1]\n密码内容\n[/hide]\n"
blocks, err := ParseHideBlocks(src)
if err != nil {
t.Fatal(err)
@@ -131,7 +131,7 @@ func TestParsePasswordAndSanitize(t *testing.T) {
if strings.Contains(out, "secret1") || strings.Contains(out, "密码内容") {
t.Fatalf("leaked: %q", out)
}
if !strings.Contains(out, ":::hide password locked") {
if !strings.Contains(out, "[hide password locked]") {
t.Fatalf("%q", out)
}
out2, _ := SanitizeForViewer(src, ViewerCaps{PasswordUnlocked: map[int]bool{0: true}})
@@ -144,7 +144,7 @@ func TestParsePasswordAndSanitize(t *testing.T) {
}
func TestMatchPasswordBlocks(t *testing.T) {
src := ":::hide password aaa\nA\n:::\n\n:::hide password bbb\nB\n:::\n"
src := "[hide password=aaa]\nA\n[/hide]\n\n[hide password=bbb]\nB\n[/hide]\n"
hit, err := MatchPasswordBlocks(src, "bbb")
if err != nil {
t.Fatal(err)
@@ -155,7 +155,7 @@ func TestMatchPasswordBlocks(t *testing.T) {
}
func TestPasswordNeed(t *testing.T) {
_, err := ParseHideBlocks(":::hide password\n无密码\n:::\n")
_, err := ParseHideBlocks("[hide password]\n无密码\n[/hide]\n")
if err != ErrHidePasswordNeed {
t.Fatalf("got %v", err)
}
@@ -163,10 +163,34 @@ func TestPasswordNeed(t *testing.T) {
func TestWrapContentAsHide(t *testing.T) {
got := WrapContentAsHide("points", 20, "旧正文")
if !strings.HasPrefix(got, ":::hide points 20\n") {
if !strings.HasPrefix(got, "[hide points=20]\n") {
t.Fatalf("%q", got)
}
if !strings.Contains(got, "旧正文") {
t.Fatal(got)
}
}
func TestTimelineDoesNotBreakHideValidate(t *testing.T) {
src := "[timeline]\n## 2026-09-16 feat\n说明\n[/timeline]\n"
if err := ValidateHideContent(src); err != nil {
t.Fatalf("timeline-only should pass: %v", err)
}
}
func TestRewriteLegacyDirectives(t *testing.T) {
src := "公开\n\n:::hide login\n秘\n:::\n\n:::timeline\n## 2026-01-01 A\n:::\n"
got := RewriteLegacyDirectives(src)
if strings.Contains(got, ":::") {
t.Fatalf("legacy remains: %q", got)
}
if !strings.Contains(got, "[hide login]") || !strings.Contains(got, "[/hide]") {
t.Fatalf("hide missing: %q", got)
}
if !strings.Contains(got, "[timeline]") || !strings.Contains(got, "[/timeline]") {
t.Fatalf("timeline missing: %q", got)
}
if err := ValidateHideContent(got); err != nil {
t.Fatal(err)
}
}

View File

@@ -0,0 +1,158 @@
package markdown
import (
"strconv"
"strings"
)
// RewriteLegacyDirectives 将旧式 :::hide / :::timeline / 裸 ::: 改写为行级 BBCode。
// 幂等:已是 BBCode 的内容原样返回(若无旧标记)。代码围栏内不改写。
func RewriteLegacyDirectives(content string) string {
if content == "" {
return content
}
if !strings.Contains(content, ":::") {
return content
}
lines := splitLines(content)
var out []string
inCode := false
i := 0
for i < len(lines) {
trimmed := strings.TrimSpace(lines[i])
if strings.HasPrefix(trimmed, "```") {
inCode = !inCode
out = append(out, lines[i])
i++
continue
}
if inCode {
out = append(out, lines[i])
i++
continue
}
if kind, pts, pwd, locked, ok := parseLegacyHideOpen(trimmed); ok {
bodyLines := make([]string, 0)
j := i + 1
innerCode := false
found := false
for j < len(lines) {
inner := strings.TrimSpace(lines[j])
if strings.HasPrefix(inner, "```") {
innerCode = !innerCode
bodyLines = append(bodyLines, lines[j])
j++
continue
}
if innerCode {
bodyLines = append(bodyLines, lines[j])
j++
continue
}
if inner == ":::" {
found = true
break
}
bodyLines = append(bodyLines, lines[j])
j++
}
out = append(out, openMarkerLine(kind, pts, pwd, locked))
out = append(out, bodyLines...)
if found {
out = append(out, "[/hide]")
i = j + 1
} else {
// 未闭合:仍写出已转换开标记与正文,避免丢内容
i = j
}
continue
}
if trimmed == ":::timeline" || strings.HasPrefix(trimmed, ":::timeline ") {
bodyLines := make([]string, 0)
j := i + 1
innerCode := false
found := false
for j < len(lines) {
inner := strings.TrimSpace(lines[j])
if strings.HasPrefix(inner, "```") {
innerCode = !innerCode
bodyLines = append(bodyLines, lines[j])
j++
continue
}
if innerCode {
bodyLines = append(bodyLines, lines[j])
j++
continue
}
if inner == ":::" {
found = true
break
}
bodyLines = append(bodyLines, lines[j])
j++
}
out = append(out, "[timeline]")
out = append(out, bodyLines...)
if found {
out = append(out, "[/timeline]")
i = j + 1
} else {
i = j
}
continue
}
out = append(out, lines[i])
i++
}
return strings.Join(out, "\n")
}
// parseLegacyHideOpen 解析旧式 :::hide <kind> [arg] [locked]
func parseLegacyHideOpen(trimmed string) (kind string, points int, password string, locked bool, ok bool) {
if !strings.HasPrefix(trimmed, ":::hide") {
return "", 0, "", false, false
}
rest := strings.TrimSpace(trimmed[len(":::hide"):])
if rest == "" {
return "", 0, "", false, false
}
parts := strings.Fields(rest)
if len(parts) == 0 {
return "", 0, "", false, false
}
kind = parts[0]
switch kind {
case HideKindLogin, HideKindReply, HideKindPoints, HideKindPassword:
default:
return "", 0, "", false, false
}
idx := 1
if kind == HideKindPoints {
if idx >= len(parts) {
return "", 0, "", false, false
}
n, err := strconv.Atoi(parts[idx])
if err != nil {
return "", 0, "", false, false
}
points = n
idx++
} else if kind == HideKindPassword {
if idx < len(parts) && parts[idx] != "locked" {
password = parts[idx]
idx++
}
}
for ; idx < len(parts); idx++ {
if parts[idx] == "locked" {
locked = true
} else {
return "", 0, "", false, false
}
}
return kind, points, password, locked, true
}