commit e3e59e7c69cf7e8b35371a36bcfd7a0a965fc90a Author: tamakyi Date: Thu Sep 10 10:56:27 2026 +0800 chore: baseline snapshot before moderation-strictness feature Repo .git was damaged (refs/ missing, index truncated, object store near-empty). Repaired via git init (rebuilt refs), stale index preserved as .git/index.corrupt-20260910.bak, then full worktree committed as a rollback baseline. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4617537 --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +# ---> Go +# If you prefer the allow list template instead of the deny list, see community template: +# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore +# +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +# vendor/ + +# Go workspace file +go.work +go.work.sum + +# env file +.env + +# otherfile +./workbuddy +./scripts +./outputs \ No newline at end of file diff --git a/.workbuddy/backup/autoban-track-notfound-20260905/app.sample.ini b/.workbuddy/backup/autoban-track-notfound-20260905/app.sample.ini new file mode 100644 index 0000000..10c1d99 --- /dev/null +++ b/.workbuddy/backup/autoban-track-notfound-20260905/app.sample.ini @@ -0,0 +1,154 @@ +[app] +production = true +title = "NekoBox" +icp = "" +default_lang = "" ; 站点默认语言:zh-CN / zh-TW / en / ja,留空默认简体中文(访客未设置语言时的兜底) +uptrace_dsn = "" +qiniu_access_key = "" +qiniu_access_secret = "" +aliyun_access_key = "" +aliyun_access_key_secret = "" +share_background = "https://your-default-background.jpg" ; 默认分享图背景图链接(1280x720) +font_path = "static/fonts/NotoSansSC-Regular.otf" ; 中文字体文件路径(相对项目根目录) + +[security] +enable_text_censor = true +ip_blacklist = ; 逗号分隔的IP黑名单,支持精确IP(如1.2.3.4)和CIDR(如1.2.3.0/24),留空不启用 +ip_blacklist_redirect_url = ; 黑名单IP访问时强制跳转到该URL +trust_proxy = false ; 是否信任反向代理设置的 CF-Connecting-IP / X-Real-IP / X-Forwarded-For 头。 + ; 仅当站点部署在可信反向代理(如 nginx/Cloudflare)之后且代理已覆盖这些头时设为 true; + ; 否则保持 false,防止客户端伪造 header 绕过速率限制与 IP 黑名单。 + ; ⚠️ 若站点在 Cloudflare 后且需使用下面的自动封禁,必须设为 true, + ; 否则解析到的将是 Cloudflare 边缘 IP,自动封禁会误伤所有访客。 + ; ⚠️ 开启 trust_proxy 时,必须配合「Cloudflare Tunnel / Authenticated Origin Pull / + ; 防火墙仅放行 Cloudflare / EdgeOne 回源网段」锁定源站,否则攻击者可直连源站并伪造 + ; CF-Connecting-IP / EO-Client-IP 头。无需维护 CDN 庞大 CIDR 清单。 + ; + ; —— 双 CDN(境内腾讯 EdgeOne + 境外 Cloudflare)场景 —— + ; EdgeOne 回源会用 EO-Client-IP 携带客户端真实 IP(等效 CF-Connecting-IP), + ; 本程序在 trust_proxy=true 时已同时信任这两个权威头。 + ; 两家 CDN 并存时必须:① 防火墙仅放行两家回源网段;② 在各家 CDN 的规则引擎中 + ; 删除回源请求里「对方 CDN」的权威头(经 EdgeOne 回源删 CF-Connecting-IP、 + ; 经 Cloudflare 回源删 EO-Client-IP),否则攻击者可借道另一家伪造客户端身份, + ; 绕过限流 / 自动封禁 / 单 IP 投票限制。详细步骤见 outputs/edgeone-cloudflare-dual-cdn-guide.md。 + +trusted_proxies = + ; 逗号分隔的「你自己的」反向代理/负载均衡 IP 或 CIDR(如 127.0.0.1、 + ; 10.0.0.0/8)。仅当 TCP 对端落在该清单内时才解析 X-Forwarded-For / X-Real-IP。 + ; 留空(默认)则这两个头永不被信任,仅采用 CDN 权威头 CF-Connecting-IP / + ; EO-Client-IP(需源站已锁定)。 + ; 注意:此清单用于你自己的基础设施,不是 CDN 的全量 CIDR 清单。 +enable_auto_ban = true ; 自动封禁(fail2ban 风格):检测到批量扫描/探测后临时封禁来源 IP +ban_track_notfound = false ; 是否把「未注册路径的 404」计入封禁统计(默认 false)。正常业务 + ; (域名/题目不存在等均走 302 业务跳转,不产生 404 计数)一律放行, + ; 仅命中后台扫描特征路径(/admin、/.env 等)才参与统计封禁,避免 + ; 共享出口(CDN 边缘 / CGNAT)下正常用户被 404 探测连坐误伤。 + ; 如需恢复对纯 404 字典扫描的封禁再置 true。 +ban_threshold_sensitive = 10 ; 统计窗口内命中敏感路径(/admin、/.env、/wp-admin 等)的次数阈值 +ban_threshold_404 = 20 ; 统计窗口内返回 404 的次数阈值(仅 ban_track_notfound = true 时生效) +ban_window_seconds = 60 ; 统计窗口时长(秒) +ban_duration_minutes = 15 ; 临时封禁时长(分钟),到期自动解除,重启即清零 +security_alert_email = ; 触发封禁时发送告警邮件的收件人(复用下方 SMTP 发信配置),留空不发送 + +[server] +port = 80 +; 绑定监听地址(含端口)。Cloudflare Tunnel 部署时强烈建议设为 127.0.0.1:, +; 使源站端口仅对本地 cloudflared 可见,即使防火墙误配也无法被外部直连伪造 CF-Connecting-IP。 +; 留空(默认)则监听所有网卡 ":port"。 +listen = +salt = "" +# ⚠️ 必填:密码哈希盐,留空会导致启动失败(已在 conf.Init 强制校验) +xsrf_key = "" +# ⚠️ 必填:CSRF token 密钥,留空会导致启动失败(已强制校验) +xsrf_expire = 3600 + +[database] +type = "postgres" +user = "nekobox" +password = "" +host = "127.0.0.1" +port = 5432 +name = "nekobox" +schema = "public" +# 仅在已确认需要自动清理重复 email/domain 时开启;默认关闭,避免启动时改写账号数据。 +dedupe_unique_fields = false + +[redis] +addr = "127.0.0.1:6379" +password = "" + +[recaptcha] +captcha_type = recaptcha ; recaptcha(默认), turnstile, math(本地算数验证码,国内访问友好) +domain = "https://www.recaptcha.net" +site_key = "" +server_key = "" +turnstile_style = false + +[upload] +default_avatar = "" +default_background = "" + +# User avatar and background. +aliyun_endpoint = "" +aliyun_access_id = "" +aliyun_access_secret = "" +aliyun_bucket = "" +aliyun_bucket_cdn_host = "" +image_endpoint = "" +image_access_id = "" +image_access_secret ="" +image_bucket = "" +image_bucket_cdn_host = "" + +# User uploaded images. +image_endpoint = "" +image_access_id = "" +image_access_secret = "" +image_bucket = "" +image_bucket_cdn_host = "" + +[mail] +account = "" +password = "" +port = 465 +smtp = "" + +[limits] +; ── 全站内容 / 数量上限(运行时配置,修改后重启生效)────────────────────── +; 缺失本段或个别键时按内置默认值运行。长度统一按字符(rune)计数。 +; 键留空或填 0/负数时自动回退内置默认值,不会导致启动失败,但也不会按你的意图生效, +; 请按需填写正整数。本文件启用 IgnoreInlineComment,行内分号注释会被并入配置值, +; 因此下面注释一律独占整行、勿写行内注释。 + +; ── 标签与屏蔽词(账号设置页)────────────────────────────────────────────── +; 最多标签个数 +max_tags = 5 +; 单个标签最大字符数 +max_tag_len = 5 +; 最多屏蔽词个数 +max_block_words = 10 +; 单个屏蔽词最大字符数 +max_block_word_len = 10 + +; ── 投票 ──────────────────────────────────────────────────────────────────── +; 参与者填写的「自定义补充选项」(其他/自定义)最大字符数 +custom_answer_len = 200 +; 站长创建投票时单个「选项」文本最大字符数(预设选项) +vote_option_len = 300 + +; ── 提问 / 回答 / 追问 ───────────────────────────────────────────────────── +; 提问正文最大字符数(访客提交的问题内容) +question_content_len = 1000 +; 回答正文最大字符数(箱主对提问的回答,及对追问的回复,共用) +answer_content_len = 2000 +; 追问正文最大字符数(提问者被回答后继续追问的内容) +followup_content_len = 2000 + +; ── 私聊 ──────────────────────────────────────────────────────────────────── +; 单条消息(发送/回复)最大字符数 +chat_message_len = 2000 +; 每个私聊会话的消息条数上限(系统硬顶)。用户只能在 1..该值 之间设置自己的 +; 会话条数上限;新注册用户的默认值即该硬顶。 +chat_max_messages = 200 +; 单用户每日私信条数上限(用户可设范围 0..该值;0 表示不限制每日条数) +daily_message_limit_max = 999 diff --git a/.workbuddy/backup/autoban-track-notfound-20260905/autoban.go b/.workbuddy/backup/autoban-track-notfound-20260905/autoban.go new file mode 100644 index 0000000..9f2004b --- /dev/null +++ b/.workbuddy/backup/autoban-track-notfound-20260905/autoban.go @@ -0,0 +1,266 @@ +// Package autoban 提供 fail2ban 风格的自动临时封禁:检测批量扫描/探测特征后 +// 临时封禁来源 IP,并可回调发送告警。纯标准库实现,便于独立测试与复用。 +package autoban + +import ( + "strings" + "sync" + "time" +) + +// 探测事件类型 +const ( + KindNone = 0 // 无探测特征 + KindSensitive = 1 // 命中敏感路径 + KindNotFound = 2 // 404 响应(未命中敏感路径) +) + +// 默认阈值/窗口(Options 未配置或为 0 时兜底)。 +const ( + DefaultWindowSeconds = 60 + DefaultDurationMinutes = 15 + DefaultThresholdSensitive = 10 + DefaultThreshold404 = 20 + pathSampleMax = 6 +) + +// Options 自动封禁配置。 +type Options struct { + Enabled bool + ThresholdSensitive int // 窗口内敏感路径命中次数 + Threshold404 int // 窗口内 404 次数 + Window time.Duration // 统计窗口 + Duration time.Duration // 封禁时长 + AlertEmail string // 告警收件人(留空不发送) + SendAlert func(ip string, paths []string, durationMinutes int) error // 告警发送函数(nil 则不发送) +} + +// sensitivePaths 常见后台/配置/漏洞探测路径特征(忽略大小写,前缀匹配)。 +var sensitivePaths = []string{ + "/admin", "/wp-admin", "/wp-login.php", "/wp-content", "/wordpress", + "/administrator", "/manager", "/cpanel", "/plesk", + "/.env", "/.git", "/.aws", "/.ssh", "/.svn", "/.hg", "/.htaccess", + "/config", "/configuration", "/backup", "/database", "/db", + "/actuator", "/swagger", "/api-docs", "/openapi", "/v2/api-docs", + "/phpmyadmin", "/pma", "/mysql", "/server-status", "/server-info", + "/shell", "/webshell", "/cmd", "/eval", "/hack", "/shell.php", + "/login.php", "/admin.php", "/index.php", "/console", "/vendor", +} + +type probeEvent struct { + at time.Time + kind int +} + +type probeStat struct { + events []probeEvent + sensitive int + notFound int + paths []string // 命中路径样本(告警用) +} + +// Banner 自动封禁器。方法并发安全。 +type Banner struct { + mu sync.Mutex + + probes map[string]*probeStat + banned map[string]time.Time + alerted map[string]bool + + thresholdSensitive int + threshold404 int + window time.Duration + duration time.Duration + alertEmail string + sendAlert func(ip string, paths []string, durationMinutes int) error + enabled bool +} + +// New 按配置创建封禁器并注册全局清理。 +func New(opts Options) *Banner { + window := opts.Window + if window <= 0 { + window = DefaultWindowSeconds * time.Second + } + duration := opts.Duration + if duration <= 0 { + duration = DefaultDurationMinutes * time.Minute + } + sensitive := opts.ThresholdSensitive + if sensitive <= 0 { + sensitive = DefaultThresholdSensitive + } + notFound := opts.Threshold404 + if notFound <= 0 { + notFound = DefaultThreshold404 + } + b := &Banner{ + probes: make(map[string]*probeStat), + banned: make(map[string]time.Time), + alerted: make(map[string]bool), + thresholdSensitive: sensitive, + threshold404: notFound, + window: window, + duration: duration, + alertEmail: strings.TrimSpace(opts.AlertEmail), + sendAlert: opts.SendAlert, + enabled: opts.Enabled, + } + register(b) + return b +} + +// Record 记录一次探测事件,达到阈值时封禁 IP 并触发一次告警。 +func (b *Banner) Record(ip, path string, kind int) { + if !b.enabled || ip == "" || kind == KindNone { + return + } + b.mu.Lock() + defer b.mu.Unlock() + + now := time.Now() + cutoff := now.Add(-b.window) + + st := b.probes[ip] + if st == nil { + st = &probeStat{} + b.probes[ip] = st + } + + // 滚动清理过期事件并重算计数 + valid := st.events[:0] + sensitive, notFound := 0, 0 + for _, e := range st.events { + if e.at.After(cutoff) { + valid = append(valid, e) + if e.kind == KindSensitive { + sensitive++ + } else if e.kind == KindNotFound { + notFound++ + } + } + } + valid = append(valid, probeEvent{at: now, kind: kind}) + if kind == KindSensitive { + sensitive++ + } else { + notFound++ + } + st.events = valid + st.sensitive = sensitive + st.notFound = notFound + if len(st.paths) < pathSampleMax && path != "" { + st.paths = append(st.paths, path) + } + + if sensitive < b.thresholdSensitive && notFound < b.threshold404 { + return + } + + // 已达阈值:封禁(已在封禁中则跳过) + if until, ok := b.banned[ip]; ok && until.After(now) { + return + } + until := now.Add(b.duration) + b.banned[ip] = until + + // 告警(每 IP 仅一次) + if b.alertEmail != "" && b.sendAlert != nil && !b.alerted[ip] { + b.alerted[ip] = true + sample := append([]string{}, st.paths...) + dur := int(b.duration.Minutes()) + go func() { + _ = b.sendAlert(ip, sample, dur) + }() + } +} + +// IsBanned 判断 IP 是否处于封禁期;到期自动解除。 +func (b *Banner) IsBanned(ip string) bool { + if !b.enabled || ip == "" { + return false + } + b.mu.Lock() + defer b.mu.Unlock() + if until, ok := b.banned[ip]; ok { + if until.After(time.Now()) { + return true + } + delete(b.banned, ip) + } + return false +} + +// IsSensitivePath 判断路径是否命中敏感探测特征(忽略大小写,完整段前缀匹配)。 +func IsSensitivePath(p string) bool { + lower := strings.ToLower(p) + for _, s := range sensitivePaths { + if lower == s || strings.HasPrefix(lower, s+"/") { + return true + } + } + return false +} + +// ---------- 全局注册与清理 ---------- + +var ( + bannersMu sync.Mutex + banners = make(map[*Banner]struct{}) + bannersOnce sync.Once +) + +func register(b *Banner) { + bannersMu.Lock() + banners[b] = struct{}{} + bannersMu.Unlock() + + bannersOnce.Do(func() { + go func() { + for { + time.Sleep(2 * time.Minute) + bannersMu.Lock() + for b := range banners { + b.cleanup() + } + bannersMu.Unlock() + } + }() + }) +} + +// cleanup 定期清理过期探测记录与已到期封禁(防止内存膨胀)。 +func (b *Banner) cleanup() { + b.mu.Lock() + defer b.mu.Unlock() + + now := time.Now() + cutoff := now.Add(-b.window) + + for ip, st := range b.probes { + if len(st.events) == 0 || st.events[len(st.events)-1].at.Before(cutoff) { + delete(b.probes, ip) + continue + } + valid := st.events[:0] + sensitive, notFound := 0, 0 + for _, e := range st.events { + if e.at.After(cutoff) { + valid = append(valid, e) + if e.kind == KindSensitive { + sensitive++ + } else if e.kind == KindNotFound { + notFound++ + } + } + } + st.events = valid + st.sensitive = sensitive + st.notFound = notFound + } + for ip, until := range b.banned { + if !until.After(now) { + delete(b.banned, ip) + } + } +} diff --git a/.workbuddy/backup/autoban-track-notfound-20260905/autoban_test.go b/.workbuddy/backup/autoban-track-notfound-20260905/autoban_test.go new file mode 100644 index 0000000..bd2fd2e --- /dev/null +++ b/.workbuddy/backup/autoban-track-notfound-20260905/autoban_test.go @@ -0,0 +1,123 @@ +package autoban + +import ( + "sync/atomic" + "testing" + "time" +) + +func newTestBanner(thresholdSensitive, threshold404 int, window, duration time.Duration, alertEmail string, alertCalls *int64) *Banner { + return New(Options{ + Enabled: true, + ThresholdSensitive: thresholdSensitive, + Threshold404: threshold404, + Window: window, + Duration: duration, + AlertEmail: alertEmail, + SendAlert: func(ip string, paths []string, dur int) error { + if alertCalls != nil { + atomic.AddInt64(alertCalls, 1) + } + return nil + }, + }) +} + +func TestSensitiveThreshold(t *testing.T) { + b := newTestBanner(2, 5, time.Minute, time.Minute, "", nil) + b.Record("1.2.3.4", "/admin", KindSensitive) + if b.IsBanned("1.2.3.4") { + t.Fatal("should not be banned before reaching threshold") + } + b.Record("1.2.3.4", "/.env", KindSensitive) + if !b.IsBanned("1.2.3.4") { + t.Fatal("expected ban after reaching sensitive threshold") + } +} + +func TestNotFoundThreshold(t *testing.T) { + b := newTestBanner(10, 3, time.Minute, time.Minute, "", nil) + for i := 0; i < 3; i++ { + b.Record("5.6.7.8", "/random-"+string(rune('a'+i)), KindNotFound) + } + if !b.IsBanned("5.6.7.8") { + t.Fatal("expected ban after reaching 404 threshold") + } +} + +func TestWindowExpiry(t *testing.T) { + b := newTestBanner(2, 5, 50*time.Millisecond, time.Minute, "", nil) + b.Record("1.1.1.1", "/admin", KindSensitive) + time.Sleep(80 * time.Millisecond) // 事件滑出窗口 + b.Record("1.1.1.1", "/.env", KindSensitive) + if b.IsBanned("1.1.1.1") { + t.Fatal("events outside the window must not accumulate") + } +} + +func TestDurationExpiry(t *testing.T) { + b := newTestBanner(1, 5, time.Minute, 60*time.Millisecond, "", nil) + b.Record("2.2.2.2", "/admin", KindSensitive) + if !b.IsBanned("2.2.2.2") { + t.Fatal("expected ban") + } + time.Sleep(100 * time.Millisecond) // 封禁到期 + if b.IsBanned("2.2.2.2") { + t.Fatal("ban should expire after duration") + } +} + +func TestAlertOncePerIP(t *testing.T) { + var calls int64 + b := newTestBanner(1, 5, time.Minute, time.Minute, "admin@example.com", &calls) + b.Record("9.9.9.9", "/wp-admin", KindSensitive) + b.Record("9.9.9.9", "/.git", KindSensitive) // 已在封禁中,不应重复告警 + b.Record("9.9.9.9", "/config", KindSensitive) + + // sendAlert 异步调用,轮询等待最多 500ms + deadline := time.Now().Add(500 * time.Millisecond) + for atomic.LoadInt64(&calls) == 0 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + if got := atomic.LoadInt64(&calls); got != 1 { + t.Fatalf("expected exactly 1 alert, got %d", got) + } +} + +func TestDisabled(t *testing.T) { + b := New(Options{Enabled: false}) + b.Record("3.3.3.3", "/admin", KindSensitive) + if b.IsBanned("3.3.3.3") { + t.Fatal("disabled auto-ban must not ban") + } +} + +func TestDefaults(t *testing.T) { + b := New(Options{Enabled: true}) // 全部走默认值 + if b.thresholdSensitive != DefaultThresholdSensitive || b.threshold404 != DefaultThreshold404 { + t.Fatalf("default thresholds wrong: %d/%d", b.thresholdSensitive, b.threshold404) + } + if b.window != DefaultWindowSeconds*time.Second || b.duration != DefaultDurationMinutes*time.Minute { + t.Fatalf("default window/duration wrong: %v/%v", b.window, b.duration) + } +} + +func TestIsSensitivePath(t *testing.T) { + cases := []struct { + path string + want bool + }{ + {"/admin", true}, + {"/admin/panel", true}, + {"/WP-ADMIN", true}, + {"/.env", true}, + {"/user/questions", false}, + {"/vote/abc123", false}, + {"/administratorx", false}, // 前缀必须完整段匹配,避免误伤 + } + for _, c := range cases { + if got := IsSensitivePath(c.path); got != c.want { + t.Errorf("IsSensitivePath(%q) = %v, want %v", c.path, got, c.want) + } + } +} diff --git a/.workbuddy/backup/autoban-track-notfound-20260905/route.go b/.workbuddy/backup/autoban-track-notfound-20260905/route.go new file mode 100644 index 0000000..dc32c09 --- /dev/null +++ b/.workbuddy/backup/autoban-track-notfound-20260905/route.go @@ -0,0 +1,409 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package route + +import ( + "encoding/gob" + "io" + "net/http" + "strings" + "time" + + "github.com/flamego/cache" + cacheRedis "github.com/flamego/cache/redis" + "github.com/flamego/csrf" + "github.com/flamego/flamego" + "github.com/flamego/recaptcha" + "github.com/flamego/session" + "github.com/flamego/session/mysql" + sessionRedis "github.com/flamego/session/redis" + "github.com/flamego/template" + "github.com/sirupsen/logrus" + + "github.com/tamakyi/TamaBox/internal/captcha" + "github.com/tamakyi/TamaBox/internal/conf" + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/form" + "github.com/tamakyi/TamaBox/internal/i18n" + "github.com/tamakyi/TamaBox/internal/mail" + "github.com/tamakyi/TamaBox/internal/route/chat" // 私聊路由 + "github.com/tamakyi/TamaBox/internal/security/autoban" + "github.com/tamakyi/TamaBox/internal/shared" + templatepkg "github.com/tamakyi/TamaBox/internal/template" + "github.com/tamakyi/TamaBox/route" + "github.com/tamakyi/TamaBox/route/auth" + "github.com/tamakyi/TamaBox/route/pixel" + "github.com/tamakyi/TamaBox/route/question" + "github.com/tamakyi/TamaBox/route/service" + "github.com/tamakyi/TamaBox/route/user" + "github.com/tamakyi/TamaBox/route/vote" + "github.com/tamakyi/TamaBox/static" + "github.com/tamakyi/TamaBox/templates" +) + +// CSRFUserSessionKey 是 CSRF token 绑定的会话键,必须与登录时写入的会话键一致 +// (见 route/auth/login.go 中 ctx.Session.Set("uid", ...))。flamego/csrf 默认使用 +// "userID",若不与之对齐,token 的 id 恒为 "0",任意匿名访客从公开页面取到的 token +// 对全部已登录用户均有效,CSRF 退化为全站公开常量。 +// +// 本常量同时被 csrf_binding_test.go 引用,作为单一事实来源:一旦被误改,回归测试会在 +// CI 失败,避免修复悄悄倒退。 +const CSRFUserSessionKey = "uid" + +// securityHeaders adds security-related HTTP headers to every response. +func securityHeaders() flamego.Handler { + return func(ctx flamego.Context) { + w := ctx.ResponseWriter() + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("X-Frame-Options", "DENY") + w.Header().Set("X-XSS-Protection", "1; mode=block") + w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin") + // HSTS:仅当站点以 https 对外提供服务时下发,避免 http 部署下把用户锁死在 https。 + if strings.HasPrefix(conf.App.ExternalURL, "https") { + w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains") + } + } +} + +func New() *flamego.Flame { + f := flamego.Classic() + if conf.App.Production { + flamego.SetEnv(flamego.EnvTypeProd) + } + + // 自动封禁实例:整个请求链路共享同一个,供中间件与 f.NotFound 复用, + // 避免对业务性 302→/(语言切换、登出、投票不存在等)误判为路径扫描。 + ab := autoban.New(autoban.Options{ + Enabled: conf.Security.EnableAutoBan, + ThresholdSensitive: conf.Security.BanThresholdSensitive, + Threshold404: conf.Security.BanThreshold404, + Window: time.Duration(conf.Security.BanWindowSeconds) * time.Second, + Duration: time.Duration(conf.Security.BanDurationMinutes) * time.Minute, + AlertEmail: conf.Security.SecurityAlertEmail, + SendAlert: mail.SendSecurityAlertMail, + }) + // 需要输出详细日志时配置如下 + // if conf.App.Production { + // flamego.SetEnv(flamego.EnvTypeProd) + // } + + templateFS, err := template.EmbedFS(templates.FS, ".", []string{".html"}) + if err != nil { + logrus.WithError(err).Fatal("Failed to embed templates file system") + } + + gob.Register(time.Time{}) + gob.Register(context.Flash{}) + gob.Register(captcha.StoredAnswer{}) + var sessionStorage interface{} + initer := session.MemoryIniter() + if conf.Database.DSN != "" { + initer = mysql.Initer() + sessionStorage = mysql.Config{ + DSN: conf.Database.DSN, + Lifetime: 7 * 24 * time.Hour, + } + } + if conf.Redis.Addr != "" { + initer = sessionRedis.Initer() + sessionStorage = sessionRedis.Config{ + Options: &sessionRedis.Options{ + Addr: conf.Redis.Addr, + Password: conf.Redis.Password, + DB: 1, + }, + Lifetime: 7 * 24 * time.Hour, + } + } + sessioner := session.Sessioner(session.Options{ + Initer: initer, + Config: sessionStorage, + // 显式声明 cookie 安全属性,不依赖库默认值: + // - HTTPOnly:禁止 JS 读取,降低 XSS 窃取会话的风险 + // - SameSite=Lax:阻断经典跨站表单 POST(CSRF 的主要防线之一) + // - Secure:仅在站点以 https 对外服务时下发,避免 http 本地开发下 cookie 不生效。 + // 缺失 Secure 时,HSTS 尚未落地的首次访问可被主动 MITM 诱导明文请求窃取会话。 + Cookie: session.CookieOptions{ + HTTPOnly: true, + SameSite: http.SameSiteLaxMode, + Secure: strings.HasPrefix(conf.App.ExternalURL, "https"), + }, + }) + + f.Use(flamego.Static(flamego.StaticOptions{ + FileSystem: http.FS(static.FS), + Prefix: "/static", + // 静态资源随二进制发布,内容变更需重新部署;1 天缓存是安全折中 + CacheControl: func() string { + return "public, max-age=86400" + }, + })) + + f.Use(securityHeaders()) + f.Use(ipBlacklistMiddleware()) + f.Use(autobanMiddleware(ab)) + // 全局请求体上限:必须在任何会读取 body 的中间件(尤其 Contexter 内的 CSRF 校验) + // 之前执行,否则超大 multipart 会在 Bind 的路由级限制生效前落盘临时文件耗尽磁盘。 + f.Use(requestBodyLimitMiddleware()) + + reqUserSignOut := context.Toggle(&context.ToggleOptions{UserSignOutRequired: true}) + reqUserSignIn := context.Toggle(&context.ToggleOptions{UserSignInRequired: true}) + + f.Group("", func() { + f.Get("/", route.Home) + f.Get("/pixel", reqUserSignIn, pixel.Index) + f.Get("/sponsor", route.Sponsor) + f.Get("/change-logs", route.ChangeLogs) + f.Get("/about-me", route.AboutMe) + f.Get("/robots.txt", func(c context.Context) { + fs, err := static.FS.Open("robots.txt") + if err != nil { + c.ResponseWriter().WriteHeader(404) + return + } + defer func() { _ = fs.Close() }() + c.ResponseWriter().Header().Set("Content-Type", "text/plain; charset=utf-8") + c.ResponseWriter().Header().Set("Cache-Control", "public, max-age=86400") + _, _ = io.Copy(c.ResponseWriter(), fs) + }) + f.Get("/favicon.ico", func(c context.Context) { + fs, _ := static.FS.Open("favicon.ico") + defer func() { _ = fs.Close() }() + c.ResponseWriter().Header().Set("Content-Type", "image/x-icon") + c.ResponseWriter().Header().Set("Cache-Control", "public, max-age=86400") + _, _ = io.Copy(c.ResponseWriter(), fs) + }) + + f.Get("/sitemap.xml", func(c context.Context) { + fs, err := static.FS.Open("sitemap.xml") + if err != nil { + c.ResponseWriter().WriteHeader(404) + return + } + defer func() { _ = fs.Close() }() + c.ResponseWriter().Header().Set("Content-Type", "application/xml") + c.ResponseWriter().Header().Set("Content-Type", "text/xml; charset=utf-8") + c.ResponseWriter().Header().Set("Cache-Control", "public, max-age=86400") + _, _ = io.Copy(c.ResponseWriter(), fs) + }) + + f.Get("/llms.txt", func(c context.Context) { + fs, err := static.FS.Open("llms.txt") + if err != nil { + c.ResponseWriter().WriteHeader(404) + return + } + defer func() { _ = fs.Close() }() + c.ResponseWriter().Header().Set("Content-Type", "text/plain; charset=utf-8") + c.ResponseWriter().Header().Set("Cache-Control", "public, max-age=86400") + _, _ = io.Copy(c.ResponseWriter(), fs) + }) + + f.Get("/llms-full.txt", func(c context.Context) { + fs, err := static.FS.Open("llms-full.txt") + if err != nil { + c.ResponseWriter().WriteHeader(404) + return + } + defer func() { _ = fs.Close() }() + c.ResponseWriter().Header().Set("Content-Type", "text/plain; charset=utf-8") + c.ResponseWriter().Header().Set("Cache-Control", "public, max-age=86400") + _, _ = io.Copy(c.ResponseWriter(), fs) + }) + + f.Group("", func() { + f.Combo("/register").Get(auth.Register).Post(form.Bind(form.Register{}), rateLimitMiddleware(10, 1*time.Minute), auth.RegisterAction) + f.Combo("/login").Get(auth.Login).Post(form.Bind(form.Login{}), rateLimitMiddleware(20, 1*time.Minute), auth.LoginAction) + f.Combo("/forgot-password").Get(auth.ForgotPassword).Post(form.Bind(form.ForgotPassword{}), rateLimitMiddleware(5, 5*time.Minute), auth.ForgotPasswordAction) + f.Combo("/recover-password").Get(auth.RecoverPassword).Post(form.Bind(form.RecoverPassword{}), auth.RecoverPasswordAction) + }, reqUserSignOut) + + // 页面密码验证路由(独立于密码保护中间件);限流防爆破 + f.Combo("/_/{domain}/password").Get(question.PasswordPage).Post(rateLimitMiddleware(10, 1*time.Minute), question.VerifyPagePassword) + + // 独立的分享图路由(不经过 Pager 中间件,直接返回图片) + // 注意:仍挂载 question.Pager,页面设置了密码时必须先通过密码验证, + // 否则分享图会绕过页面密码保护(与单题分享图行为一致)。 + f.Group("/_/{domain}", func() { + f.Get("/share-card", question.ShareCard) + }, question.Pager) + + f.Group("/_/{domain}", func() { + f.Combo("").Get(question.List).Post(form.Bind(form.NewQuestion{}), rateLimitMiddleware(30, 1*time.Minute), question.New) + f.Group("/{questionID}", func() { + f.Get("", question.Item) + f.Get("/share-card", question.QuestionShareCard) + f.Post("/delete", question.Delete) + f.Post("/set-private", question.SetPrivate) + f.Post("/set-public", question.SetPublic) + f.Post("/pin", question.TogglePin) + f.Post("/read", question.SetRead) + f.Post("/unread", question.SetUnread) + f.Post("/answer", reqUserSignIn, form.Bind(form.PublishAnswerQuestion{}), question.PublishAnswer) + f.Post("/follow-up", form.Bind(form.PublishFollowUpQuestion{}), question.PublishFollowUp) + f.Post("/follow-up/{followUpID}/answer", reqUserSignIn, form.Bind(form.AnswerFollowUpQuestion{}), question.AnswerFollowUp) + }, question.Questioner) + + // 新增:私聊路由(需要登录,使用 Token 标识对话) + f.Group("/chat/{token}", func() { + f.Get("", chat.ConversationPage) + f.Post("/send", rateLimitMiddleware(20, 1*time.Minute), chat.SendMessage) + f.Post("/delete", chat.DeleteConversation) + f.Post("/block", chat.ToggleBlockUser) + }, reqUserSignIn) + }, question.Pager) // Pager 中间件已内置页面密码检查 + + f.Get("/explore", user.Explore) + + // 匿名投票参与端(公开):token 链接入口 + f.Group("/vote/{token}", func() { + f.Get("", vote.Page) + // 提交限流优先按登录用户/签名 vote_fp 计数,IP 仅作高阈值兜底,避免共享出口误伤。 + f.Post("/submit", voteSubmitRateLimitMiddleware(20, 1*time.Minute), vote.Submit) + }) + + // 公开页语言切换:把语言偏好写入 session(由 session 中间件随其 cookie 一并持久化) + // 后跳回原页面。此前写独立 lang cookie 会被 session 中间件的 Set-Cookie 整体覆盖而失效, + // 故改为托管在 session 中。仅允许站内相对路径,防开放重定向。 + f.Get("/i18n/{lang}", func(c context.Context) { + lang := i18n.Resolve(c.Param("lang")) + // 写入 session,避免被 session 中间件的 Set-Cookie 覆盖(匿名用户也走 session 中间件)。 + c.Session.Set("lang", lang) + to := c.Query("to") + // 仅允许站内相对路径,防开放重定向: + // 拒绝空、非 "/" 开头、以 "//" 开头的协议相对路径,以及含反斜杠/控制字符的变体。 + if to == "" || !strings.HasPrefix(to, "/") || + strings.HasPrefix(to, "//") || strings.ContainsAny(to, "\\\x00\r\n\t") { + to = "/" + } + c.Redirect(to) + }) + + // 算数验证码 API(仅在 captcha_type = "math" 时生效,但路由本身不依赖中间件) + // 加限流:防止匿名脚本无限生成/轮询爆破(答案本身对客户端可见,限流是主要节流手段)。 + f.Get("/api/captcha/generate", rateLimitMiddleware(20, 1*time.Minute), captcha.GenerateHandler) + f.Post("/api/captcha/verify", rateLimitMiddleware(20, 1*time.Minute), captcha.VerifyHandler) + + f.Group("/user", func() { + f.Get("/questions", user.QuestionList) + + // 匿名投票管理(箱主侧) + f.Group("/votes", func() { + f.Get("", user.VoteList) + f.Get("/new", user.VoteNew) + f.Post("", rateLimitMiddleware(10, 1*time.Minute), user.VoteCreate) + f.Get("/{voteID}/edit", user.VoteEdit) + f.Post("/{voteID}", rateLimitMiddleware(10, 1*time.Minute), user.VoteUpdate) + f.Post("/{voteID}/publish", user.VotePublish) + f.Post("/{voteID}/close", user.VoteClose) + f.Post("/{voteID}/delete", user.VoteDelete) + f.Get("/{voteID}/results", user.VoteResults) + f.Get("/{voteID}/preview", user.VotePreview) + // 导出为只读操作(幂等、无副作用),用 GET 链接下载,避免表单提交 + f.Get("/{voteID}/export", user.VoteExportCSV) + }) + + f.Group("/profile", func() { + f.Get("", user.Profile) + f.Post("/update", form.Bind(form.UpdateProfile{}), rateLimitMiddleware(10, 1*time.Minute), user.UpdateProfile) + f.Post("/export", user.ExportProfile) + f.Post("/export-json", user.ExportProfileJSON) + f.Combo("/deactivate").Get(user.DeactivateProfile).Post(user.DeactivateProfileAction) + + f.Post("/update-page-password", form.Bind(form.UpdatePagePassword{}), rateLimitMiddleware(10, 1*time.Minute), user.UpdatePagePassword) + f.Post("/update-ask-password", form.Bind(form.UpdateAskPassword{}), rateLimitMiddleware(10, 1*time.Minute), user.UpdateAskPassword) + + f.Post("/update-chat-settings", user.UpdateChatSettings) + + // 功能管理(提问 / 私聊 / 投票 的开关、定时开关与定量收集): + // 不单独开页面,作为账号设置页的三个面板,保存后回跳到对应面板。 + f.Group("/features", func() { + f.Post("/update", rateLimitMiddleware(20, 1*time.Minute), user.FeaturesUpdate) + f.Post("/reset-quota", rateLimitMiddleware(20, 1*time.Minute), user.FeatureResetQuota) + }) + }) + // 防骚扰设置:注册限制(harassment/update)与全局屏蔽词(blockwords/update) + // 拆为两个独立入口。屏蔽词在提问/私聊/投票三个设置面板共用一份,保存后经 + // ?tab= 参数回跳到来源面板。 + f.Post("/harassment/update", form.Bind(form.UpdateHarassment{}), user.UpdateHarassment) + f.Post("/blockwords/update", form.Bind(form.UpdateBlockWords{}), user.UpdateBlockWords) + f.Post("/tags/update", form.Bind(form.UpdateTags{}), user.UpdateTags) + // Logout 必须用 POST:GET 会留下 CSRF 风险(第三方图片/链接可触发退出登录) + f.Post("/logout", auth.Logout) + }, reqUserSignIn) + + f.Group("/api/v1", func() { + f.Group("/user", func() { + f.Get("", reqUserSignIn, user.ProfileAPI) + f.Group("/{domain}", func() { + f.Group("/questions", func() { + f.Get("", rateLimitMiddleware(60, 1*time.Minute), question.ListAPI) + }) + }) + }) + // 像素追踪代理:仅暴露只读 GET(f.Any 会放行写方法,曾有 CSRF 豁免 + 写方法放行的风险), + // 并加限流防止被用作高频打点通道。 + f.Get("/pixel/{**}", reqUserSignIn, rateLimitMiddleware(30, 1*time.Minute), pixel.Proxy) + // 服务反代仅暴露只读 GET:本网关是把已登录用户的请求转发到配置好的内部服务, + // 不应允许任意写方法,避免被用作对内网后端的越权操作入口。 + f.Get("/service/{**}", reqUserSignIn, service.Proxy) + f.Get("/explore/random", rateLimitMiddleware(60, 1*time.Minute), user.RandomRecommend) + // 首页"提问箱信息统计"公开接口(服务端 30 分钟缓存),供前端定时刷新 + f.Get("/site-stats", rateLimitMiddleware(60, 1*time.Minute), route.SiteStatsAPI) + }, context.APIEndpoint) + }, + cache.Cacher(cache.Options{ + Initer: cacheRedis.Initer(), + Config: cacheRedis.Config{ + Options: &cacheRedis.Options{ + Addr: conf.Redis.Addr, + Password: conf.Redis.Password, + DB: 0, + }, + }, + }), + recaptcha.V3( + recaptcha.Options{ + Secret: conf.Recaptcha.ServerKey, + VerifyURL: func() recaptcha.VerifyURL { + if conf.Recaptcha.TurnstileStyle { + return "https://challenges.cloudflare.com/turnstile/v0/siteverify" + } + return recaptcha.VerifyURLGlobal + }(), + }, + ), + sessioner, + csrf.Csrfer(csrf.Options{ + Secret: conf.Server.XSRFKey, + Header: "X-CSRF-Token", + // ⚠️ 必须与 route/auth/login.go 中 ctx.Session.Set("uid", ...) 的 key 一致。 + // flamego/csrf 默认 SessionKey 为 "userID",若不显式指定,s.Get("userID") + // 恒为 nil,token 内绑定的 id 恒为 "0" —— 由于校验是无状态 HMAC 重算 + // (不与 session 中存储的 token 比对),这会导致任意匿名访客从公开的 + // /login 页面取到的 token 对所有已登录用户均有效,CSRF 退化为全站公开常量。 + // 回归测试见 route/csrf_binding_test.go(引用 CSRFUserSessionKey)。 + SessionKey: CSRFUserSessionKey, + }), + template.Templater(template.Options{ + FileSystem: templateFS, + FuncMaps: templatepkg.FuncMap(), + }), + context.Contexter(), + ) + f.NotFound(func(ctx flamego.Context) { + // 真正的 404 探测在此计数(仅此处,不把业务 302→/ 误判为扫描)。 + // 注意:flamego 的 NotFound 会先写入 404 状态再 Redirect 到 "/", + // 因此这里在 Redirect 之前记录,确保状态为 404。 + // 键必须与 autobanMiddleware 中的 IsBanned/Record 保持一致(同样经 LimitKey 聚合), + // 否则 404 计数会记在另一个键上,导致封禁永不生效。 + if ip := shared.LimitKey(shared.ResolveClientIP(ctx.Request().Request)); ip != "" { + ab.Record(ip, ctx.Request().URL.Path, autoban.KindNotFound) + } + ctx.Redirect("/") + }) + + return f +} diff --git a/.workbuddy/backup/autoban-track-notfound-20260905/static.go b/.workbuddy/backup/autoban-track-notfound-20260905/static.go new file mode 100644 index 0000000..e32d120 --- /dev/null +++ b/.workbuddy/backup/autoban-track-notfound-20260905/static.go @@ -0,0 +1,128 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package conf + +// Build time and commit information. +// +// ⚠️ WARNING: should only be set by "-ldflags". +var ( + BuildTime string + BuildCommit = "dev" +) + +var ( + App struct { + Production bool `ini:"production"` + ExternalURL string `ini:"external_url"` + ICP string `ini:"icp"` + DefaultLang string `ini:"default_lang"` // 站点默认语言(zh-CN/zh-TW/en/ja),留空回退简体中文 + UptraceDSN string `ini:"uptrace_dsn"` + QiniuAccessKey string `ini:"qiniu_access_key"` + QiniuAccessSecret string `ini:"qiniu_access_secret"` + AliyunAccessKey string `ini:"aliyun_access_key"` + AliyunAccessKeySecret string `ini:"aliyun_access_key_secret"` + SentryDSN string `ini:"sentry_dsn"` + MaintenanceMode bool `ini:"maintenance_mode"` + ShareBackground string `ini:"share_background"` + FontPath string `ini:"font_path"` + } + + Security struct { + EnableTextCensor bool `ini:"enable_text_censor"` + IPBlacklist string `ini:"ip_blacklist"` + IPBlacklistRedirectURL string `ini:"ip_blacklist_redirect_url"` + // TrustProxy 为 true 时信任 CDN 权威客户端头 CF-Connecting-IP / EO-Client-IP + // (以及受信代理设置的 X-Real-IP / X-Forwarded-For);否则一律使用 RemoteAddr, + // 防止客户端伪造 header 绕过速率限制与 IP 黑名单。 + TrustProxy bool `ini:"trust_proxy"` + // TrustedProxies 逗号分隔的 IP / CIDR 列表,仅限“你自己的”反向代理/负载均衡基础设施 + // (例如本机 nginx 的 127.0.0.1、私有网络 LB)。仅当 TCP 对端落在该清单内时才会解析 + // X-Forwarded-For / X-Real-IP。留空则这两个头永不被信任(CDN 权威头 CF-Connecting-IP / + // EO-Client-IP 仍会被采用,前提是源站已被对应 CDN 锁定)。 + // 目的:避免维护 Cloudflare / EdgeOne 等上游 CDN 的庞大 CIDR 清单——源站应配合 + // Cloudflare Tunnel / Authenticated Origin Pull / 防火墙仅放行 CDN 回源网段锁定, + // 使 CF-Connecting-IP / EO-Client-IP 成为权威客户端 IP。 + TrustedProxies string `ini:"trusted_proxies"` + // 自动封禁(fail2ban 风格):检测批量扫描/探测特征后临时封禁来源 IP。 + EnableAutoBan bool `ini:"enable_auto_ban"` + BanThresholdSensitive int `ini:"ban_threshold_sensitive"` // 窗口内敏感路径命中次数 + BanThreshold404 int `ini:"ban_threshold_404"` // 窗口内 404 次数 + BanWindowSeconds int `ini:"ban_window_seconds"` // 统计窗口(秒) + BanDurationMinutes int `ini:"ban_duration_minutes"` // 封禁时长(分钟) + SecurityAlertEmail string `ini:"security_alert_email"` // 触发封禁时告警收件人(留空不发送) + } + + Server struct { + Port int `ini:"port"` + Listen string `ini:"listen"` // 绑定监听地址(含端口)。留空则默认 ":port"(监听所有网卡)。 + Salt string `ini:"salt"` + XSRFKey string `ini:"xsrf_key"` + } + + Database struct { + DSN string + + Type string `ini:"type"` + User string `ini:"user"` + Password string `ini:"password"` + Host string `ini:"host"` + Port uint `ini:"port"` + Name string `ini:"name"` + Schema string `ini:"schema"` + DedupeUniqueFields bool `ini:"dedupe_unique_fields"` + } + + Redis struct { + Addr string `ini:"addr"` + Password string `ini:"password"` + } + + Recaptcha struct { + CaptchaType string `ini:"captcha_type"` + Domain string `ini:"domain"` + SiteKey string `ini:"site_key"` + ServerKey string `ini:"server_key"` + TurnstileStyle bool `ini:"turnstile_style"` + } + + Pixel struct { + Host string `ini:"host"` + } + + Upload struct { + DefaultAvatarURL string `ini:"default_avatar"` + DefaultBackground string `ini:"default_background"` + DefaultBackgroundImageURL string `ini:"default_qrbackgroundimage"` + AliyunEndpoint string `ini:"aliyun_endpoint"` + AliyunAccessID string `ini:"aliyun_access_id"` + AliyunAccessSecret string `ini:"aliyun_access_secret"` + AliyunBucket string `ini:"aliyun_bucket"` + AliyunBucketCDNHost string `ini:"aliyun_bucket_cdn_host"` + ImageEndpoint string `ini:"image_endpoint"` + ImageAccessID string `ini:"image_access_id"` + ImageAccessSecret string `ini:"image_access_secret"` + ImageBucket string `ini:"image_bucket"` + ImageBucketCDNHost string `ini:"image_bucket_cdn_host"` + } + + Mail struct { + Account string `ini:"account"` + Password string `ini:"password"` + Port int `ini:"port"` + SMTP string `ini:"smtp"` + // SkipTLSVerify 跳过 SMTP TLS 证书校验(仅自签名/内网 SMTP 需要,默认 false 校验证书) + SkipTLSVerify bool `ini:"skip_tls_verify"` + } + + Service struct { + Backends []struct { + Prefix string `ini:"prefix"` + ForwardURL string `ini:"forward_url"` + } + // TLSInsecureSkipVerify 跳过反向代理到后端服务的 TLS 证书校验 + // (仅内网后端使用自签名证书时需要,默认 false 校验证书) + TLSInsecureSkipVerify bool `ini:"tls_insecure_skip_verify"` + } +) diff --git a/.workbuddy/backup/cdn-migration-20260905/header.html b/.workbuddy/backup/cdn-migration-20260905/header.html new file mode 100644 index 0000000..8a6eb93 --- /dev/null +++ b/.workbuddy/backup/cdn-migration-20260905/header.html @@ -0,0 +1,977 @@ + + + + + + {{ .Title }} + + + + + + + + + + + + + + + + + {{ if .VConsole }} + + + {{ end }} + + + + + + {{ if eq .CaptchaType "math" }} + + + {{ else if .RecaptchaTurnstileStyle }} + + + {{ else }} + + + {{ end }} + {{ if ne SentryDSN "" }} + + + {{ end }} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {{ if .NoIndex }}{{ end }} + {{ if .IsUserPage }} + + + + + + + + + {{ else }} + + + + + + + {{ end }} + + + + + + + + + + + + +
+ {{ if not .IsUserPage }} + + {{ end }} + +
+ + + +{{ if .IsPixel }} +
+{{ else }} +
+{{ end }} + +{{ if eq .CaptchaType "math" }} +
+
+

{{t .LangCode "captcha.title"}}

+

{{t .LangCode "captcha.hint"}}

+
+ {{t .LangCode "captcha.loading"}} + +
+
+ +
+ +
+ + +
+
+
+ + + + +{{ end }} \ No newline at end of file diff --git a/.workbuddy/backup/cdn-migration-20260905/list.html b/.workbuddy/backup/cdn-migration-20260905/list.html new file mode 100644 index 0000000..4215219 --- /dev/null +++ b/.workbuddy/backup/cdn-migration-20260905/list.html @@ -0,0 +1,309 @@ +{{template "base/header" .}} + + + + + +
+
+
+ +

{{ .PageUser.Name }}

+

{{ .PageUser.Intro }}

+
+ {{ if and .PageUser.Acfunlink (ne .PageUser.Acfunlink "none") }} + + acfunlink + + {{ end }} + {{ if and .PageUser.Bililink (ne .PageUser.Bililink "none") }} + + bililink + + {{ end }} + {{ if and .PageUser.Weibolink (ne .PageUser.Weibolink "none") }} + + weibolink + + {{ end }} + {{ if and .PageUser.Xiaohongshulink (ne .PageUser.Xiaohongshulink "none") }} + + xiaohongshulink + + {{ end }} + {{ if and .PageUser.Bloglink (ne .PageUser.Bloglink "none") }} + + bloglink + + {{ end }} +
+
+
+
+ +
+
+ {{ if .CanAsk }} + + + +
+ + +

{{t .LangCode "ask.scan" .PageUser.Name}}
{{ if .RegisterOnlyAsk }}{{t .LangCode "ask.registerOnly"}}{{ else }}{{t .LangCode "ask.anonymous"}}{{ end }}

+ + + + + + + {{ end }} + {{template "base/alert" .}} + + +
+ + {{ if .VoteEnabled }} + + {{ else }} + + + {{ end }} +
+ +
+ {{template "question/new-question-template" .}} + + {{ if ne (len .PageQuestions) 0 }} +

{{t .LangCode "ask.history" .PageUser.Name}} ({{ .AnsweredCount }})

+ {{ template "question/history-template" . }} + {{ end }} +
+ + +
+
+ +{{template "base/footer" .}} \ No newline at end of file diff --git a/.workbuddy/backup/cdn-migration-20260905/profile.html b/.workbuddy/backup/cdn-migration-20260905/profile.html new file mode 100644 index 0000000..13ef910 --- /dev/null +++ b/.workbuddy/backup/cdn-migration-20260905/profile.html @@ -0,0 +1,1527 @@ +{{template "base/header" .}} + + + + + + + + + + + + + + + + +{{template "base/alert" .}} + + +
+
+ +
+

{{t .LangCode "profile.cropTitle"}}

+
+
+
+ +
+

+
+ +
+
+ + +
+ + + + +
+ + +
+
+ {{ .CSRFTokenHTML }} + + +
+

{{t .LangCode "profile.card.basic"}}

+
+ + +
+
+ + +
+
+ +
+ +
+
+ + +
+
+ +
+ +
+
+ + + {{t .LangCode "admin.langHint"}} +
+
+ + +
+
+ +
+
+ + +
+

{{t .LangCode "profile.card.avatarBg"}}

+
+
+ + + + 1:1 +
+ + +
+ {{t .LangCode "profile.avatarCropHint"}} +
+
+ + + + 16:9 +
+ + +
+ {{t .LangCode "profile.backgroundCropHint"}} +
+
+ +
+ +
+
+ + +
+
    +
  • + {{t .LangCode "profile.card.qr"}} +
    +
    +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + + {{t .LangCode "admin.customFgHint"}} +
    +
    + +
    + + {{.LoggedUser.Dotscale}} + +
    +
    +
    + +
    + + {{.LoggedUser.Backgroundimagealpha}} + +
    +
    +
    + +
    + + +
    + {{t .LangCode "admin.qrPreviewHint"}} +
    +
    +
    +
    +

    {{t .LangCode "admin.preview"}}

    +
    +
    +
    + {{t .LangCode "admin.themePreset"}} +
    + + + + +
    +
    +
    + +
    +

    {{t .LangCode "admin.previewHint"}}

    +
    +
    +
    +
    +
  • +
+
+ +
+
+ + +
+
    +
  • + {{t .LangCode "admin.social"}} +
    + {{t .LangCode "admin.socialHint"}} + + + + + +
    +
  • +
+
+ +
+
+ + +
+

{{t .LangCode "profile.card.password"}}

+
+ + +
+
+ + +
+

{{t .LangCode "profile.pwdNote"}}

+
+
+ +
+
+
+ + +
+

{{t .LangCode "admin.tags"}}

+
+ {{ .CSRFTokenHTML }} +
+ + +
+
+ +
+
+ +
+
+
+ + +
+

{{t .LangCode "admin.pagePassword"}}

+
+ {{ .CSRFTokenHTML }} +
+ + +
+
+ +
+
+
+ + +
+

{{t .LangCode "admin.account"}}

+ +
+
+ + + +
+ {{ with .FeatureQuestion }}{{template "user/feature-control-form" .}}{{ end }} + +
+
+
+ {{ $.CSRFTokenHTML }} + {{t $.LangCode "admin.harassment"}} +
+
+ +
+
+ +
+
+
+ + + {{ template "user/global-blockwords" (dict "Root" $ "Action" "/user/blockwords/update?tab=question") }} + +
+
+
+ {{ $.CSRFTokenHTML }} + {{t $.LangCode "admin.askPassword"}} +
+ + +
+
+ +
+
+
+
+ + +
+ +
+ {{ with .FeatureChat }}{{template "user/feature-control-form" .}}{{ end }} + +
+
+ {{ $.CSRFTokenHTML }} + {{t $.LangCode "admin.chat"}} +
+ + {{ with $.ChatLimits }} + + {{ end }} +
+
+ + {{ with $.ChatLimits }} + + {{ end }} + {{t $.LangCode "admin.dailyLimitHint"}} +
+
+ +
+
+
+ +
+ + {{ template "user/global-blockwords" (dict "Root" $ "Action" "/user/blockwords/update?tab=chat") }} +
+ + +
+ {{ with .FeatureVote }}{{template "user/feature-control-form" .}}{{ end }} + +
+ + {{ template "user/global-blockwords" (dict "Root" $ "Action" "/user/blockwords/update?tab=vote") }} +
+ + + + + + + + + +{{template "base/footer" .}} diff --git a/.workbuddy/backup/cdn-migration-20260905/question-not-found.html b/.workbuddy/backup/cdn-migration-20260905/question-not-found.html new file mode 100644 index 0000000..a81806f --- /dev/null +++ b/.workbuddy/backup/cdn-migration-20260905/question-not-found.html @@ -0,0 +1,105 @@ +{{template "base/header" .}} + + + + + +
+
+
+ +

{{ .PageUser.Name }}

+

{{ .PageUser.Intro }}

+
+ {{ if and .PageUser.Acfunlink (ne .PageUser.Acfunlink "none") }} + + acfunlink + + {{ end }} + {{ if and .PageUser.Bililink (ne .PageUser.Bililink "none") }} + + bililink + + {{ end }} + {{ if and .PageUser.Weibolink (ne .PageUser.Weibolink "none") }} + + weibolink + + {{ end }} + {{ if and .PageUser.Xiaohongshulink (ne .PageUser.Xiaohongshulink "none") }} + + xiaohongshulink + + {{ end }} + {{ if and .PageUser.Bloglink (ne .PageUser.Bloglink "none") }} + + bloglink + + {{ end }} +
+
+
+
+ +
+
+ {{ if .CanAsk }} + + + +
+ + +

扫码向@{{ .PageUser.Name }}提问
{{ if .RegisterOnlyAsk }}{{t .LangCode "ask.registerOnly"}}{{ else }}{{t .LangCode "ask.anonymous"}}{{ end }}

+ {{ end }} + {{template "base/alert" .}} + {{template "question/new-question-template" .}} + +
+ {{ if ne (len .PageQuestions) 0 }} +

@{{ .PageUser.Name }} 以前回答过的问题 ({{ .AnsweredCount }})

+ {{ template "question/history-template" . }} + {{ end }} +
+
+{{template "base/footer" .}} \ No newline at end of file diff --git a/.workbuddy/backup/domain-shiroko-20260906/footer.html b/.workbuddy/backup/domain-shiroko-20260906/footer.html new file mode 100644 index 0000000..e6e0b60 --- /dev/null +++ b/.workbuddy/backup/domain-shiroko-20260906/footer.html @@ -0,0 +1,102 @@ +

+
Powered by NekoBox | {{ ICP }}
{{t .LangCode "site.footer.runtime"}}: +
+ + {{t .LangCode "site.footer.admin"}} + | {{t .LangCode "site.footer.notice"}} + | {{t .LangCode "site.footer.chat"}} + | {{t .LangCode "site.footer.drive"}} + | {{t .LangCode "site.footer.status"}} + | {{t .LangCode "site.footer.nav"}} +

+ + +
+
+ + + + diff --git a/.workbuddy/backup/domain-shiroko-20260906/header.html b/.workbuddy/backup/domain-shiroko-20260906/header.html new file mode 100644 index 0000000..eb6c166 --- /dev/null +++ b/.workbuddy/backup/domain-shiroko-20260906/header.html @@ -0,0 +1,1029 @@ + + + + + + {{ .Title }} + + + + + + + + + + + + + + + + + + {{ if .VConsole }} + + + {{ end }} + + + {{ if eq .CaptchaType "math" }} + + + {{ else if .RecaptchaTurnstileStyle }} + + + {{ else }} + + + {{ end }} + {{ if ne SentryDSN "" }} + + + {{ end }} + + + + + + + + + + + + + + + + + + + + + + + + + + + {{ if .NoIndex }}{{ end }} + {{ if .IsUserPage }} + + + + + + + + + {{ else }} + + + + + + + {{ end }} + + + + + + + + + + + + + + +
+ {{ if not .IsUserPage }} + + {{ end }} + +
+ + + +{{ if .IsPixel }} +
+{{ else }} +
+{{ end }} + +{{ if eq .CaptchaType "math" }} +
+
+

{{t .LangCode "captcha.title"}}

+

{{t .LangCode "captcha.hint"}}

+
+ {{t .LangCode "captcha.loading"}} + +
+
+ +
+ +
+ + +
+
+
+ + + + +{{ end }} \ No newline at end of file diff --git a/.workbuddy/backup/domain-shiroko-20260906/home.html b/.workbuddy/backup/domain-shiroko-20260906/home.html new file mode 100644 index 0000000..63c52a8 --- /dev/null +++ b/.workbuddy/backup/domain-shiroko-20260906/home.html @@ -0,0 +1,122 @@ +{{template "base/header" .}} +
+

{{t .LangCode "site.title"}}

+


⭐一个无需注册即可提问的匿名提问箱。你不需要下载App,不需要绑定社交账号,甚至连邮箱都不需要是真的。
⭐本站在原版的基础上新增了问题页面的二维码、私聊、投票、追加提问等功能以及更多自定义内容。各位用户可自行修改二维码背景图、颜色等个性化配置。
⭐可以到站长唯一提问提问箱链接小狼的提问箱尝试相关功能或给我提意见。
⭐可以加群:小狼的群一起水群。

+

近期将国内段访问交由EdgeOne接管,境外访问照旧由CloudFlare提供,经测试国内访问速度有所提升。但因EdgeOne Free套餐不提供CIDR列表,IP放行采取自动抓取手动维护模式,如果出现521错误请刷新一下页面,过几天应该就好了。

+

近期更新:
⭐2026.9 增加了提问、投票、私聊的总开关,可以设置定时收集、定量收集或关闭功能,顺便调整了前后端显示,看起来更易用了一些。
⭐2026.8 新增了投票功能、追加提问、多语言、Markdown显示、置顶显示等多个功能,详情见这里。
⭐2026.8 放弃使用recaptcha等对国内用户非常不友好的验证方式,更新了密码加密方式,修复了图片上传等一系列问题。
⭐2026.5 增加了私聊功能,可进行连续性对话,详见介绍;另有增加提问箱的卡片分享,更直观和美观。
⭐2026.2 新增了用户展示和标签功能,如果你希望陌生人给你提问,可以在设置页面给自己贴上5个标签并选择是否展示在探索页面:点我访问,详情见狼的公告板

+

一点提醒:
⭐本站唯一指定认证站长:小狼,注意不要被骗。 +
⭐本站不允许垃圾信息、广告、辱骂、涉政、暴恐、色情、违禁、无意义、灌水提问的出现,如有涉证或不良言论将直接删除。

+
+

{{t .LangCode "site.stats"}}:

{{if .SiteStats}}{{.SiteStats.Text}}{{end}}

+ + +
+ + {{template "base/footer" .}} \ No newline at end of file diff --git a/.workbuddy/backup/domain-shiroko-20260906/llms-full.txt b/.workbuddy/backup/domain-shiroko-20260906/llms-full.txt new file mode 100644 index 0000000..8685afd --- /dev/null +++ b/.workbuddy/backup/domain-shiroko-20260906/llms-full.txt @@ -0,0 +1,121 @@ +# 狼的提问箱 / Wolf's Question Box — 完整说明 + +狼的提问箱(Wolf's Question Box)是一个免费、无需注册的匿名提问箱服务,是 NekoBox 的社区分支(community fork)。访客无需下载 App、绑定社交账号或提供邮箱,即可向箱主匿名提问;箱主可公开或私密回答,并与提问者进行追问式的多轮对话。 + +> 隐私声明:单个提问箱内的问答内容属于用户隐私,不对外公开索引,也不写入 sitemap。本文件仅使用站点的公开功能信息,不包含任何具体提问箱或提问内容。 + +## 1. 服务定位 + +- 面向个人创作者、UP 主、博主等,提供一个让粉丝/陌生人匿名提问的入口。 +- 匿名是核心:提问者不需要任何账号、邮箱或社交登录。 +- 多语言界面:简体中文、繁体中文、英文、日文。 +- 内置浅色 / 深色主题切换。 + +## 2. 核心功能详解 + +### 2.1 匿名提问 +访客打开任意箱主的提问箱页面即可直接提问,全程无需登录。提问内容以纯文本或 Markdown 提交。 + +### 2.2 回答与追问(多轮对话) +- 箱主可对问题进行公开回答。 +- 提问者可就同一问题「继续追问」,箱主可再次回复,形成来回多轮对话,适合连续交流、澄清或访谈场景。 +- 已回答的追问,箱主可随时「更新回答」。 + +### 2.3 Markdown 渲染 +问题与回答支持 Markdown 显示(标题、列表、引用、代码块、表格、图片等),保留排版格式。 + +### 2.4 置顶 +箱主可将重要或精彩的问题「置顶」,固定展示在提问箱顶部,便于新访客一眼看到。 + +### 2.5 访问密码 / 提问密码 +- **查看密码**:访问提问箱页面时需要输入密码,适合仅对特定人群开放。 +- **提问密码**:向某提问箱提问时需要输入密码,防止陌生人随意刷屏。 +- 密码采用加密方式存储,不保存明文。 + +### 2.6 二维码分享 +每个问题页均可生成分享二维码,箱主可自定义二维码的背景图与颜色,方便线下或社媒直接扫码访问。 + +### 2.7 标签与探索页 +- 箱主最多可设置 5 个标签,并选择是否展示在「探索」页面。 +- 「探索」页(`/explore`)按用户与标签发现其他公开提问箱,是站内唯一的公开内容发现入口。 + +### 2.8 私聊 +箱主与访客之间可进行一对一的连续私密对话(私聊),区别于公开问答,内容不对外展示。 + +### 2.9 多语言 +界面支持简体中文、繁体中文、英文、日文四种语言,跟随用户选择或浏览器/站点偏好。 + +### 2.10 深色模式 +全站内置浅色 / 深色主题切换,偏好记忆在本地 cookie。 + +### 2.11 验证码与图片上传 +- 为兼顾国内外用户,已弃用对国内不友好的 reCAPTCHA,改用更友好的验证方式(如算数验证码 / Turnstile)。 +- 提问与回答支持图片上传,上传前会做像素总量校验以防解压炸弹。 + +## 3. 使用流程 + +### 创建提问箱(箱主) +1. 访问 `/register` 注册一个免费账号,获得专属提问箱与二级域名(如 `/_/你的用户名`)。 +2. 在 `/user/profile` 设置用户名、头像、简介与标签。 +3. 按需开启「查看密码」或「提问密码」,并设置是否参与探索页。 + +### 匿名提问(访客) +1. 打开某箱主的提问箱页面(如 `/_/用户名`)。 +2. 若箱主设置了提问密码,先输入密码。 +3. 填写问题并提交(可勾选邮件通知,但邮箱非必填)。 +4. 等待箱主公开回答;如需补充,可使用「追问」。 + +### 分享 +- 复制提问箱链接,或使用问题页二维码分享。 +- 推荐国内用户使用主域名 `https://box.tama.guru`。 + +## 4. 常见问题(FAQ) + +### 4.1 给提问者(访客) + +- **提问需要注册吗?** 不需要。任何人都能匿名提问;只有创建与管理提问箱(注册账号)才需要登录。 +- **我的匿名性能保证吗?** 提问者无需提供账号或邮箱即可提问;是否填写通知邮箱完全可选,不填也能正常使用。 +- **我可以追问吗?** 可以。对箱主已公开回答的问题,你可「继续追问」,箱主再次回复后形成来回多轮对话,适合澄清、访谈或连续交流。 +- **我能收到回答通知吗?** 可以。提问时若留下邮箱(可选),箱主首次公开回答后你会收到邮件通知;邮件内含一条私密链接,可凭其查看该问题、接收回复并继续追问。 +- **提问有数量限制吗?** 有基础频率限制(约 30 条/分钟/IP)以防刷屏滥用,正常使用基本无感。 +- **能上传图片吗?** 能。提问与回答均支持图片上传,上传前会做像素总量等安全校验以防解压炸弹。 +- **需要验证码吗?** 需要。提问前需通过验证码(算数验证码 / Turnstile),已弃用对国内不友好的 reCAPTCHA,兼顾国内外用户。 +- **提问内容会被搜索引擎收录吗?** 不会。单个提问箱及其问答内容属于用户隐私,已排除在索引与 sitemap 之外;仅首页、注册、登录、探索页等公开页可被收录。 + +### 4.2 给箱主(创作者) + +- **如何创建提问箱?** 注册一个免费账号,即可获得专属路径(如 `/_/你的用户名`),作为你的匿名提问箱。 +- **如何设置个人资料?** 在 `/user/profile` 设置用户名、头像、简介与标签。 +- **如何限制谁能访问或提问?** 可开启「查看密码」(访问页面需密码)与「提问密码」(提问需密码),均以加密形式存储,服务端不保存明文。 +- **我能删除某条提问吗?** 可以。箱主可删除提问箱内的任意提问。 +- **我能隐藏某条提问/回答吗?** 可以。单条问题可设为「私密」不对外公开展示,也可随时改回公开。 +- **如何把精彩问题置顶?** 使用「置顶」功能,将重要或精彩的问题固定在提问箱顶部,便于新访客一眼看到。 +- **如何出现在探索页?** 设置最多 5 个标签,并选择是否展示在「探索」页(`/explore`),这是站内唯一的公开内容发现入口。 +- **我能和访客私聊吗?** 可以。支持一对一连续私密对话(区别于公开问答);可拉黑对方、或删除整个对话,被拉黑方将无法继续发送。 +- **有新提问/新消息会通知我吗?** 会。若你已设置邮箱,有新提问、新私聊消息时会收到邮件通知。 +- **分享卡片 / 二维码能自定义吗?** 可以。问题页与提问箱页面均可生成分享卡片与二维码,并自定义二维码背景图与颜色,方便线下或社媒直接扫码访问。 +- **内容审核如何运作?** 采用自动与人工结合的审核,对垃圾信息、广告、辱骂、涉政、暴恐、色情、违禁及无意义灌水内容进行处置与删除。 + +### 4.3 通用 + +- **支持哪些语言?** 简体中文、繁体中文、英文、日文;可在页面切换,偏好记忆于本地 cookie。 +- **支持深色模式吗?** 支持。全站内置浅色 / 深色主题切换,偏好同样记忆于本地 cookie。 +- **这是 NekoBox 吗?** 不是。TamaBox(狼的提问箱)是 NekoBox 的社区分支(community fork),在功能与多语言方面做了扩展。 +- **收费吗?** 免费。 +- **数据安全吗?** 密码加密存储,图片上传前后均做安全校验,单个提问箱内容不对外索引。 +- **如何分享我的提问箱?** 复制提问箱链接,或使用页面二维码、分享卡片;国内用户推荐使用主域名 `https://box.tama.guru`。 +- **忘记密码怎么办?** 登录页提供找回密码流程(通过注册邮箱重置),具体以登录页提示为准。 + +## 5. 隐私与使用政策 + +- **隐私**:单个提问箱内容属于用户隐私,不对外索引、不写入 sitemap。 +- **内容规范**:禁止垃圾信息、广告、辱骂、涉政、暴恐、色情、违禁、无意义或灌水内容;违规内容将被删除。 +- **数据安全**:图片上传前后均做安全校验,密码加密存储。 + +## 6. 资源 + +- 更新日志(功能更新记录):https://blog.tama.guru/record/tamabox_changelog_20260813 +- 站点首页:https://box.tama.guru/ +- 探索页:https://box.tama.guru/explore +- 注册:https://box.tama.guru/register +- 登录:https://box.tama.guru/login diff --git a/.workbuddy/backup/domain-shiroko-20260906/llms.txt b/.workbuddy/backup/domain-shiroko-20260906/llms.txt new file mode 100644 index 0000000..843add9 --- /dev/null +++ b/.workbuddy/backup/domain-shiroko-20260906/llms.txt @@ -0,0 +1,29 @@ +# 狼的提问箱 / Wolf's Question Box + +> 狼的提问箱(Wolf's Question Box)是一个免费、无需注册的匿名提问箱服务。访客无需下载 App、绑定社交账号或提供邮箱,即可向箱主匿名提问;箱主可公开或私密回答,并与提问者进行追问式的多轮对话。本站为 NekoBox 的社区分支(community fork)。单个提问箱内的问答内容属于用户隐私,不对外公开索引。 + +## 概述 +- [首页](https://box.tama.guru/): 站点介绍与多语言落地页。 +- [探索](https://box.tama.guru/explore): 按用户与标签发现公开的提问箱。 +- [注册](https://box.tama.guru/register): 免费创建自己的提问箱。 +- [登录](https://box.tama.guru/login): 登录以管理你的提问箱。 + +## 核心功能 +- 匿名提问:无需账号、邮箱或社交登录即可提问。 +- 回答与追问:箱主可公开回答;提问者可继续追问,箱主可回复,形成多轮来回对话。 +- Markdown 渲染:问题与回答支持 Markdown 显示。 +- 访问控制:可分别设置「查看提问箱密码」与「提问密码」,密码加密存储。 +- 置顶:将重要问题置顶展示。 +- 二维码分享:每个问题页生成可分享二维码,背景图与颜色可自定义。 +- 标签与发现:最多添加 5 个标签,展示于探索页。 +- 私聊:与箱主一对一的连续私密对话。 +- 多语言界面:简体中文、繁体中文、英文、日文。 +- 深色模式:内置浅色 / 深色主题切换。 + +## 资源 +- [完整说明 (llms-full.txt)](https://box.tama.guru/llms-full.txt): 站点完整功能说明、使用流程、FAQ 与隐私政策。 +- [更新日志](https://blog.tama.guru/record/tamabox_changelog_20260813): 近期功能更新(追问、多语言、Markdown、置顶等)。 + +## 使用政策 +- 隐私:单个提问箱内容属于隐私,已排除在搜索引擎索引与 sitemap 之外。 +- 内容规范:禁止垃圾信息、广告、辱骂、涉政、暴恐、色情、违禁、无意义或灌水内容,违规内容将被删除。 diff --git a/.workbuddy/backup/domain-shiroko-20260906/register.go b/.workbuddy/backup/domain-shiroko-20260906/register.go new file mode 100644 index 0000000..1eab76d --- /dev/null +++ b/.workbuddy/backup/domain-shiroko-20260906/register.go @@ -0,0 +1,92 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package auth + +import ( + "github.com/flamego/recaptcha" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + + "github.com/tamakyi/TamaBox/internal/captcha" + "github.com/tamakyi/TamaBox/internal/conf" + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/db" + "github.com/tamakyi/TamaBox/internal/form" + "github.com/tamakyi/TamaBox/internal/i18n" + "github.com/tamakyi/TamaBox/internal/shared" +) + +func Register(ctx context.Context) { + ctx.Success("auth/register") +} + +func RegisterAction(ctx context.Context, f form.Register, recaptcha recaptcha.RecaptchaV3) { + if ctx.HasError() { + ctx.Success("auth/register") + return + } + + // Check captcha code (unified: recaptcha, turnstile, or math). + ok, err := captcha.Verify(f.Recaptcha, shared.ResolveClientIP(ctx.Request().Request), ctx.Session, recaptcha, ctx.Lang()) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to check captcha") + ctx.SetErrorFlash(err.Error()) + ctx.Redirect("/register") + return + } + if !ok { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "captcha.error")) + ctx.Redirect("/register") + return + } + + if err := db.Users.Create(ctx.Request().Context(), db.CreateUserOptions{ + Name: f.Name, + Password: f.Password, + Email: f.Email, + Avatar: conf.Upload.DefaultAvatarURL, + Domain: f.Domain, + Background: conf.Upload.DefaultBackground, + Intro: "问你想问的", + Qrcodebackcolor: "#FDF8F0", + Qrcodecolor: "#C45500", + Usernamecolor: "#000000", + Introcolor: "#000000", + Dotscale: "0.35", + BackgroundImage: conf.Upload.DefaultBackgroundImageURL, + Backgroundimagealpha: "0.8", + Qrcodepdpcolor: "#C45500", + Acfunlink: "none", + Bililink: "none", + Weibolink: "none", + Bloglink: "box.tama.guru", + Xiaohongshulink: "none", + Language: i18n.Resolve(f.Language), // 注册时选择的界面语言;留空回退站点默认 + }); err != nil { + switch { + case errors.Is(err, db.ErrDuplicateEmail): + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "auth.errDuplicateEmail"))) + case errors.Is(err, db.ErrDuplicateDomain): + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "auth.errDuplicateDomain"))) + case errors.Is(err, db.ErrBadCredential): + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "auth.errBadCredential"))) + + default: + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to create new user") + ctx.SetInternalError() + } + + ctx.Success("auth/register") + return + } + + // 成功提示跟随用户注册时选择的语言 + lang := "zh-CN" + if l, ok := ctx.Data["Lang"].(string); ok && l != "" { + lang = l + } + ctx.SetSuccessFlash(i18n.T(lang, "auth.register.success")) + ctx.Redirect("/login") +} diff --git a/.workbuddy/backup/domain-shiroko-20260906/robots.txt b/.workbuddy/backup/domain-shiroko-20260906/robots.txt new file mode 100644 index 0000000..4977c33 --- /dev/null +++ b/.workbuddy/backup/domain-shiroko-20260906/robots.txt @@ -0,0 +1,7 @@ +User-agent: * +Disallow: /_/ +Disallow: /user/ +Allow: /explore +Allow: /llms.txt +Allow: /llms-full.txt +Sitemap: https://box.tama.guru/sitemap.xml diff --git a/.workbuddy/backup/domain-shiroko-20260906/route.go.bak b/.workbuddy/backup/domain-shiroko-20260906/route.go.bak new file mode 100644 index 0000000..872608e --- /dev/null +++ b/.workbuddy/backup/domain-shiroko-20260906/route.go.bak @@ -0,0 +1,414 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package route + +import ( + "encoding/gob" + "io" + "net/http" + "strings" + "time" + + "github.com/flamego/cache" + cacheRedis "github.com/flamego/cache/redis" + "github.com/flamego/csrf" + "github.com/flamego/flamego" + "github.com/flamego/recaptcha" + "github.com/flamego/session" + "github.com/flamego/session/mysql" + sessionRedis "github.com/flamego/session/redis" + "github.com/flamego/template" + "github.com/sirupsen/logrus" + + "github.com/tamakyi/TamaBox/internal/captcha" + "github.com/tamakyi/TamaBox/internal/conf" + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/form" + "github.com/tamakyi/TamaBox/internal/i18n" + "github.com/tamakyi/TamaBox/internal/mail" + "github.com/tamakyi/TamaBox/internal/route/chat" // 私聊路由 + "github.com/tamakyi/TamaBox/internal/security/autoban" + "github.com/tamakyi/TamaBox/internal/shared" + templatepkg "github.com/tamakyi/TamaBox/internal/template" + "github.com/tamakyi/TamaBox/route" + "github.com/tamakyi/TamaBox/route/auth" + "github.com/tamakyi/TamaBox/route/pixel" + "github.com/tamakyi/TamaBox/route/question" + "github.com/tamakyi/TamaBox/route/service" + "github.com/tamakyi/TamaBox/route/user" + "github.com/tamakyi/TamaBox/route/vote" + "github.com/tamakyi/TamaBox/static" + "github.com/tamakyi/TamaBox/templates" +) + +// CSRFUserSessionKey 是 CSRF token 绑定的会话键,必须与登录时写入的会话键一致 +// (见 route/auth/login.go 中 ctx.Session.Set("uid", ...))。flamego/csrf 默认使用 +// "userID",若不与之对齐,token 的 id 恒为 "0",任意匿名访客从公开页面取到的 token +// 对全部已登录用户均有效,CSRF 退化为全站公开常量。 +// +// 本常量同时被 csrf_binding_test.go 引用,作为单一事实来源:一旦被误改,回归测试会在 +// CI 失败,避免修复悄悄倒退。 +const CSRFUserSessionKey = "uid" + +// securityHeaders adds security-related HTTP headers to every response. +func securityHeaders() flamego.Handler { + return func(ctx flamego.Context) { + w := ctx.ResponseWriter() + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("X-Frame-Options", "DENY") + w.Header().Set("X-XSS-Protection", "1; mode=block") + w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin") + // HSTS:仅当站点以 https 对外提供服务时下发,避免 http 部署下把用户锁死在 https。 + if strings.HasPrefix(conf.App.ExternalURL, "https") { + w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains") + } + } +} + +func New() *flamego.Flame { + f := flamego.Classic() + if conf.App.Production { + flamego.SetEnv(flamego.EnvTypeProd) + } + + // 自动封禁实例:整个请求链路共享同一个,供中间件与 f.NotFound 复用, + // 避免对业务性 302→/(语言切换、登出、投票不存在等)误判为路径扫描。 + // 404 是否参与统计由 ban_track_notfound 控制(默认 false:正常业务一律放行, + // 仅敏感扫描路径计数封禁,见 conf.Security.BanTrackNotFound)。 + ab := autoban.New(autoban.Options{ + Enabled: conf.Security.EnableAutoBan, + TrackNotFound: conf.Security.BanTrackNotFound, + ThresholdSensitive: conf.Security.BanThresholdSensitive, + Threshold404: conf.Security.BanThreshold404, + Window: time.Duration(conf.Security.BanWindowSeconds) * time.Second, + Duration: time.Duration(conf.Security.BanDurationMinutes) * time.Minute, + AlertEmail: conf.Security.SecurityAlertEmail, + SendAlert: mail.SendSecurityAlertMail, + }) + // 需要输出详细日志时配置如下 + // if conf.App.Production { + // flamego.SetEnv(flamego.EnvTypeProd) + // } + + templateFS, err := template.EmbedFS(templates.FS, ".", []string{".html"}) + if err != nil { + logrus.WithError(err).Fatal("Failed to embed templates file system") + } + + gob.Register(time.Time{}) + gob.Register(context.Flash{}) + gob.Register(captcha.StoredAnswer{}) + var sessionStorage interface{} + initer := session.MemoryIniter() + if conf.Database.DSN != "" { + initer = mysql.Initer() + sessionStorage = mysql.Config{ + DSN: conf.Database.DSN, + Lifetime: 7 * 24 * time.Hour, + } + } + if conf.Redis.Addr != "" { + initer = sessionRedis.Initer() + sessionStorage = sessionRedis.Config{ + Options: &sessionRedis.Options{ + Addr: conf.Redis.Addr, + Password: conf.Redis.Password, + DB: 1, + }, + Lifetime: 7 * 24 * time.Hour, + } + } + sessioner := session.Sessioner(session.Options{ + Initer: initer, + Config: sessionStorage, + // 显式声明 cookie 安全属性,不依赖库默认值: + // - HTTPOnly:禁止 JS 读取,降低 XSS 窃取会话的风险 + // - SameSite=Lax:阻断经典跨站表单 POST(CSRF 的主要防线之一) + // - Secure:仅在站点以 https 对外服务时下发,避免 http 本地开发下 cookie 不生效。 + // 缺失 Secure 时,HSTS 尚未落地的首次访问可被主动 MITM 诱导明文请求窃取会话。 + Cookie: session.CookieOptions{ + HTTPOnly: true, + SameSite: http.SameSiteLaxMode, + Secure: strings.HasPrefix(conf.App.ExternalURL, "https"), + }, + }) + + f.Use(flamego.Static(flamego.StaticOptions{ + FileSystem: http.FS(static.FS), + Prefix: "/static", + // 静态资源随二进制发布,内容变更需重新部署;1 天缓存是安全折中 + CacheControl: func() string { + return "public, max-age=86400" + }, + })) + + f.Use(securityHeaders()) + f.Use(ipBlacklistMiddleware()) + f.Use(autobanMiddleware(ab)) + // 全局请求体上限:必须在任何会读取 body 的中间件(尤其 Contexter 内的 CSRF 校验) + // 之前执行,否则超大 multipart 会在 Bind 的路由级限制生效前落盘临时文件耗尽磁盘。 + f.Use(requestBodyLimitMiddleware()) + + reqUserSignOut := context.Toggle(&context.ToggleOptions{UserSignOutRequired: true}) + reqUserSignIn := context.Toggle(&context.ToggleOptions{UserSignInRequired: true}) + + f.Group("", func() { + f.Get("/", route.Home) + f.Get("/pixel", reqUserSignIn, pixel.Index) + f.Get("/sponsor", route.Sponsor) + f.Get("/change-logs", route.ChangeLogs) + f.Get("/about-me", route.AboutMe) + f.Get("/robots.txt", func(c context.Context) { + fs, err := static.FS.Open("robots.txt") + if err != nil { + c.ResponseWriter().WriteHeader(404) + return + } + defer func() { _ = fs.Close() }() + c.ResponseWriter().Header().Set("Content-Type", "text/plain; charset=utf-8") + c.ResponseWriter().Header().Set("Cache-Control", "public, max-age=86400") + _, _ = io.Copy(c.ResponseWriter(), fs) + }) + f.Get("/favicon.ico", func(c context.Context) { + fs, _ := static.FS.Open("favicon.ico") + defer func() { _ = fs.Close() }() + c.ResponseWriter().Header().Set("Content-Type", "image/x-icon") + c.ResponseWriter().Header().Set("Cache-Control", "public, max-age=86400") + _, _ = io.Copy(c.ResponseWriter(), fs) + }) + + f.Get("/sitemap.xml", func(c context.Context) { + fs, err := static.FS.Open("sitemap.xml") + if err != nil { + c.ResponseWriter().WriteHeader(404) + return + } + defer func() { _ = fs.Close() }() + c.ResponseWriter().Header().Set("Content-Type", "application/xml") + c.ResponseWriter().Header().Set("Content-Type", "text/xml; charset=utf-8") + c.ResponseWriter().Header().Set("Cache-Control", "public, max-age=86400") + _, _ = io.Copy(c.ResponseWriter(), fs) + }) + + f.Get("/llms.txt", func(c context.Context) { + fs, err := static.FS.Open("llms.txt") + if err != nil { + c.ResponseWriter().WriteHeader(404) + return + } + defer func() { _ = fs.Close() }() + c.ResponseWriter().Header().Set("Content-Type", "text/plain; charset=utf-8") + c.ResponseWriter().Header().Set("Cache-Control", "public, max-age=86400") + _, _ = io.Copy(c.ResponseWriter(), fs) + }) + + f.Get("/llms-full.txt", func(c context.Context) { + fs, err := static.FS.Open("llms-full.txt") + if err != nil { + c.ResponseWriter().WriteHeader(404) + return + } + defer func() { _ = fs.Close() }() + c.ResponseWriter().Header().Set("Content-Type", "text/plain; charset=utf-8") + c.ResponseWriter().Header().Set("Cache-Control", "public, max-age=86400") + _, _ = io.Copy(c.ResponseWriter(), fs) + }) + + f.Group("", func() { + f.Combo("/register").Get(auth.Register).Post(form.Bind(form.Register{}), rateLimitMiddleware(10, 1*time.Minute), auth.RegisterAction) + f.Combo("/login").Get(auth.Login).Post(form.Bind(form.Login{}), rateLimitMiddleware(20, 1*time.Minute), auth.LoginAction) + f.Combo("/forgot-password").Get(auth.ForgotPassword).Post(form.Bind(form.ForgotPassword{}), rateLimitMiddleware(5, 5*time.Minute), auth.ForgotPasswordAction) + f.Combo("/recover-password").Get(auth.RecoverPassword).Post(form.Bind(form.RecoverPassword{}), auth.RecoverPasswordAction) + }, reqUserSignOut) + + // 页面密码验证路由(独立于密码保护中间件);限流防爆破 + f.Combo("/_/{domain}/password").Get(question.PasswordPage).Post(rateLimitMiddleware(10, 1*time.Minute), question.VerifyPagePassword) + + // 独立的分享图路由(不经过 Pager 中间件,直接返回图片) + // 注意:仍挂载 question.Pager,页面设置了密码时必须先通过密码验证, + // 否则分享图会绕过页面密码保护(与单题分享图行为一致)。 + f.Group("/_/{domain}", func() { + f.Get("/share-card", question.ShareCard) + }, question.Pager) + + f.Group("/_/{domain}", func() { + f.Combo("").Get(question.List).Post(form.Bind(form.NewQuestion{}), rateLimitMiddleware(30, 1*time.Minute), question.New) + f.Group("/{questionID}", func() { + f.Get("", question.Item) + f.Get("/share-card", question.QuestionShareCard) + f.Post("/delete", question.Delete) + f.Post("/set-private", question.SetPrivate) + f.Post("/set-public", question.SetPublic) + f.Post("/pin", question.TogglePin) + f.Post("/read", question.SetRead) + f.Post("/unread", question.SetUnread) + f.Post("/answer", reqUserSignIn, form.Bind(form.PublishAnswerQuestion{}), question.PublishAnswer) + f.Post("/follow-up", form.Bind(form.PublishFollowUpQuestion{}), question.PublishFollowUp) + f.Post("/follow-up/{followUpID}/answer", reqUserSignIn, form.Bind(form.AnswerFollowUpQuestion{}), question.AnswerFollowUp) + }, question.Questioner) + + // 新增:私聊路由(需要登录,使用 Token 标识对话) + f.Group("/chat/{token}", func() { + f.Get("", chat.ConversationPage) + f.Post("/send", rateLimitMiddleware(20, 1*time.Minute), chat.SendMessage) + f.Post("/delete", chat.DeleteConversation) + f.Post("/block", chat.ToggleBlockUser) + }, reqUserSignIn) + }, question.Pager) // Pager 中间件已内置页面密码检查 + + f.Get("/explore", user.Explore) + + // 匿名投票参与端(公开):token 链接入口 + f.Group("/vote/{token}", func() { + f.Get("", vote.Page) + // 提交限流优先按登录用户/签名 vote_fp 计数,IP 仅作高阈值兜底,避免共享出口误伤。 + f.Post("/submit", voteSubmitRateLimitMiddleware(20, 1*time.Minute), vote.Submit) + }) + + // 公开页语言切换:把语言偏好写入 session(由 session 中间件随其 cookie 一并持久化) + // 后跳回原页面。此前写独立 lang cookie 会被 session 中间件的 Set-Cookie 整体覆盖而失效, + // 故改为托管在 session 中。仅允许站内相对路径,防开放重定向。 + f.Get("/i18n/{lang}", func(c context.Context) { + lang := i18n.Resolve(c.Param("lang")) + // 写入 session,避免被 session 中间件的 Set-Cookie 覆盖(匿名用户也走 session 中间件)。 + c.Session.Set("lang", lang) + to := c.Query("to") + // 仅允许站内相对路径,防开放重定向: + // 拒绝空、非 "/" 开头、以 "//" 开头的协议相对路径,以及含反斜杠/控制字符的变体。 + if to == "" || !strings.HasPrefix(to, "/") || + strings.HasPrefix(to, "//") || strings.ContainsAny(to, "\\\x00\r\n\t") { + to = "/" + } + c.Redirect(to) + }) + + // 算数验证码 API(仅在 captcha_type = "math" 时生效,但路由本身不依赖中间件) + // 加限流:防止匿名脚本无限生成/轮询爆破(答案本身对客户端可见,限流是主要节流手段)。 + f.Get("/api/captcha/generate", rateLimitMiddleware(20, 1*time.Minute), captcha.GenerateHandler) + f.Post("/api/captcha/verify", rateLimitMiddleware(20, 1*time.Minute), captcha.VerifyHandler) + + f.Group("/user", func() { + f.Get("/questions", user.QuestionList) + + // 匿名投票管理(箱主侧) + f.Group("/votes", func() { + f.Get("", user.VoteList) + f.Get("/new", user.VoteNew) + f.Post("", rateLimitMiddleware(10, 1*time.Minute), user.VoteCreate) + f.Get("/{voteID}/edit", user.VoteEdit) + f.Post("/{voteID}", rateLimitMiddleware(10, 1*time.Minute), user.VoteUpdate) + f.Post("/{voteID}/publish", user.VotePublish) + f.Post("/{voteID}/close", user.VoteClose) + f.Post("/{voteID}/delete", user.VoteDelete) + f.Get("/{voteID}/results", user.VoteResults) + f.Get("/{voteID}/preview", user.VotePreview) + // 导出为只读操作(幂等、无副作用),用 GET 链接下载,避免表单提交 + f.Get("/{voteID}/export", user.VoteExportCSV) + }) + + f.Group("/profile", func() { + f.Get("", user.Profile) + f.Post("/update", form.Bind(form.UpdateProfile{}), rateLimitMiddleware(10, 1*time.Minute), user.UpdateProfile) + f.Post("/export", user.ExportProfile) + f.Post("/export-json", user.ExportProfileJSON) + f.Combo("/deactivate").Get(user.DeactivateProfile).Post(user.DeactivateProfileAction) + + f.Post("/update-page-password", form.Bind(form.UpdatePagePassword{}), rateLimitMiddleware(10, 1*time.Minute), user.UpdatePagePassword) + f.Post("/update-ask-password", form.Bind(form.UpdateAskPassword{}), rateLimitMiddleware(10, 1*time.Minute), user.UpdateAskPassword) + + f.Post("/update-chat-settings", user.UpdateChatSettings) + + // 功能管理(提问 / 私聊 / 投票 的开关、定时开关与定量收集): + // 不单独开页面,作为账号设置页的三个面板,保存后回跳到对应面板。 + f.Group("/features", func() { + f.Post("/update", rateLimitMiddleware(20, 1*time.Minute), user.FeaturesUpdate) + f.Post("/reset-quota", rateLimitMiddleware(20, 1*time.Minute), user.FeatureResetQuota) + }) + }) + // 防骚扰设置:注册限制(harassment/update)与全局屏蔽词(blockwords/update) + // 拆为两个独立入口。屏蔽词在提问/私聊/投票三个设置面板共用一份,保存后经 + // ?tab= 参数回跳到来源面板。 + f.Post("/harassment/update", form.Bind(form.UpdateHarassment{}), user.UpdateHarassment) + f.Post("/blockwords/update", form.Bind(form.UpdateBlockWords{}), user.UpdateBlockWords) + f.Post("/tags/update", form.Bind(form.UpdateTags{}), user.UpdateTags) + // Logout 必须用 POST:GET 会留下 CSRF 风险(第三方图片/链接可触发退出登录) + f.Post("/logout", auth.Logout) + }, reqUserSignIn) + + f.Group("/api/v1", func() { + f.Group("/user", func() { + f.Get("", reqUserSignIn, user.ProfileAPI) + f.Group("/{domain}", func() { + f.Group("/questions", func() { + f.Get("", rateLimitMiddleware(60, 1*time.Minute), question.ListAPI) + }) + }) + }) + // 像素追踪代理:仅暴露只读 GET(f.Any 会放行写方法,曾有 CSRF 豁免 + 写方法放行的风险), + // 并加限流防止被用作高频打点通道。 + f.Get("/pixel/{**}", reqUserSignIn, rateLimitMiddleware(30, 1*time.Minute), pixel.Proxy) + // 服务反代仅暴露只读 GET:本网关是把已登录用户的请求转发到配置好的内部服务, + // 不应允许任意写方法,避免被用作对内网后端的越权操作入口。 + f.Get("/service/{**}", reqUserSignIn, service.Proxy) + f.Get("/explore/random", rateLimitMiddleware(60, 1*time.Minute), user.RandomRecommend) + // 首页"提问箱信息统计"公开接口(服务端 30 分钟缓存),供前端定时刷新 + f.Get("/site-stats", rateLimitMiddleware(60, 1*time.Minute), route.SiteStatsAPI) + }, context.APIEndpoint) + }, + cache.Cacher(cache.Options{ + Initer: cacheRedis.Initer(), + Config: cacheRedis.Config{ + Options: &cacheRedis.Options{ + Addr: conf.Redis.Addr, + Password: conf.Redis.Password, + DB: 0, + }, + }, + }), + recaptcha.V3( + recaptcha.Options{ + Secret: conf.Recaptcha.ServerKey, + VerifyURL: func() recaptcha.VerifyURL { + if conf.Recaptcha.TurnstileStyle { + return "https://challenges.cloudflare.com/turnstile/v0/siteverify" + } + return recaptcha.VerifyURLGlobal + }(), + }, + ), + sessioner, + csrf.Csrfer(csrf.Options{ + Secret: conf.Server.XSRFKey, + Header: "X-CSRF-Token", + // ⚠️ 必须与 route/auth/login.go 中 ctx.Session.Set("uid", ...) 的 key 一致。 + // flamego/csrf 默认 SessionKey 为 "userID",若不显式指定,s.Get("userID") + // 恒为 nil,token 内绑定的 id 恒为 "0" —— 由于校验是无状态 HMAC 重算 + // (不与 session 中存储的 token 比对),这会导致任意匿名访客从公开的 + // /login 页面取到的 token 对所有已登录用户均有效,CSRF 退化为全站公开常量。 + // 回归测试见 route/csrf_binding_test.go(引用 CSRFUserSessionKey)。 + SessionKey: CSRFUserSessionKey, + }), + template.Templater(template.Options{ + FileSystem: templateFS, + FuncMaps: templatepkg.FuncMap(), + }), + context.Contexter(), + ) + f.NotFound(func(ctx flamego.Context) { + // 真正的 404 探测在此记录(仅此处,不把业务 302→/ 误判为扫描)。 + // 注意:flamego 的 NotFound 会先写入 404 状态再 Redirect 到 "/", + // 因此这里在 Redirect 之前记录,确保状态为 404。 + // 键必须与 autobanMiddleware 中的 IsBanned/Record 保持一致(同样经 LimitKey 聚合), + // 否则 404 计数会记在另一个键上,导致封禁永不生效。 + // ⚠️ 该 404 计数受 ban_track_notfound 配置控制,默认关闭(正常业务一律放行, + // 仅敏感扫描路径计数封禁);Record 内部对未开启的 KindNotFound 直接忽略。 + if ip := shared.LimitKey(shared.ResolveClientIP(ctx.Request().Request)); ip != "" { + ab.Record(ip, ctx.Request().URL.Path, autoban.KindNotFound) + } + ctx.Redirect("/") + }) + + return f +} diff --git a/.workbuddy/backup/domain-shiroko-20260906/sitemap.xml b/.workbuddy/backup/domain-shiroko-20260906/sitemap.xml new file mode 100644 index 0000000..d5e91c3 --- /dev/null +++ b/.workbuddy/backup/domain-shiroko-20260906/sitemap.xml @@ -0,0 +1,58 @@ + + + + + https://box.tama.guru/explore + 0.3 + 2026-02-27 + weekly + + + + https://box.tama.guru/ + 0.3 + 2026-02-27 + weekly + + + + https://box.tama.guru/register + 0.3 + 2026-02-27 + weekly + + + + https://box.tama.guru/login + 0.3 + 2026-02-27 + weekly + + + + https://box.tama.guru/_/tamakyi + 0.3 + 2026-02-27 + weekly + + + + https://box.tama.guru + 0.3 + 2026-02-27 + weekly + + + + https://box.tama.guru/change-logs + 0.3 + 2026-02-27 + weekly + + + \ No newline at end of file diff --git a/.workbuddy/backup/domain-shiroko-20260906/text.go b/.workbuddy/backup/domain-shiroko-20260906/text.go new file mode 100644 index 0000000..60cc7f4 --- /dev/null +++ b/.workbuddy/backup/domain-shiroko-20260906/text.go @@ -0,0 +1,118 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package censor + +import ( + "context" + "encoding/json" + "fmt" + "strings" +) + +type ForbiddenType string + +const ( + ForbiddenTypeSpam ForbiddenType = "spam" + ForbiddenTypeAd ForbiddenType = "ad" + ForbiddenTypePolitics ForbiddenType = "politics" + ForbiddenTypeTerrorism ForbiddenType = "terrorism" + ForbiddenTypeAbuse ForbiddenType = "abuse" + ForbiddenTypePorn ForbiddenType = "porn" + ForbiddenTypeFlood ForbiddenType = "flood" + ForbiddenTypeContraband ForbiddenType = "contraband" + ForbiddenTypeMeaningless ForbiddenType = "meaningless" + ForbiddenTypeHarmful ForbiddenType = "harmful" +) + +func (f ForbiddenType) String() string { + return map[ForbiddenType]string{ + ForbiddenTypeSpam: "含垃圾信息", + ForbiddenTypeAd: "广告", + ForbiddenTypePolitics: "涉政", + ForbiddenTypeTerrorism: "暴恐", + ForbiddenTypeAbuse: "辱骂", + ForbiddenTypePorn: "色情", + ForbiddenTypeFlood: "灌水", + ForbiddenTypeContraband: "违禁", + ForbiddenTypeMeaningless: "无意义", + ForbiddenTypeHarmful: "不良场景", + }[f] +} + +type TextCensorResponse struct { + SourceName string `json:"source_name"` + Pass bool `json:"pass"` + ForbiddenType ForbiddenType `json:"forbidden_type"` + Hint string `json:"hint"` + Confidence float64 `json:"confidence"` + RawResponse json.RawMessage `json:"raw_response"` +} + +func (r *TextCensorResponse) ToJSON() []byte { + jsonBytes, _ := json.Marshal(r) + return jsonBytes +} + +func (r *TextCensorResponse) ErrorMessage() string { + errorMessage := "内容安全检查不通过" + if r.ForbiddenType != "" { + errorMessage += fmt.Sprintf(" [%s]", r.ForbiddenType.String()) + } + if r.Hint != "" { + errorMessage += fmt.Sprintf(",相关标签:%q", r.Hint) + } + return errorMessage +} + +type TextCensor interface { + Censor(ctx context.Context, text string) (*TextCensorResponse, error) + String() string +} + +var TrustedHosts = []string{ + "xhslink.com", // 小红书 + "weibo.com", // 微博 + "b23.tv", // Bilibili + "acfun.cn", + "aixifan.com", + "github.com", + "tama.guru", + "337845818.best", + "x.com", + "bilibili.com", +} + +// RemoveTrustedURL removes the trusted URL from the text, +// in order to bypass the URL censoring. +// 仅当可信域名后紧跟路径分隔符(/ ? #)或位于字符串结尾时才视为可信, +// 避免 github.com.evil.tld 被朴素替换误判为 github.com 之子域而漏审。 +func RemoveTrustedURL(str string) string { + for _, host := range TrustedHosts { + for _, protocol := range []string{"http://", "https://"} { + needle := protocol + host + var b strings.Builder + rest := str + for { + idx := strings.Index(rest, needle) + if idx < 0 { + b.WriteString(rest) + break + } + b.WriteString(rest[:idx]) + after := rest[idx+len(needle):] + if len(after) == 0 || after[0] == '/' || after[0] == '?' || after[0] == '#' { + // 可信域名边界:跳过该前缀,从域名之后继续(域名本身被移除,不进入审核)。 + rest = after + } else { + // 非可信域名边界(如 github.com.evil):保留前缀,从其后继续扫描。 + b.WriteString(needle) + rest = after + } + } + str = b.String() + } + } + return str +} diff --git a/.workbuddy/backup/p0-avatar-qrcode-20260905/internal/storage/s3.go b/.workbuddy/backup/p0-avatar-qrcode-20260905/internal/storage/s3.go new file mode 100644 index 0000000..7f93ca5 --- /dev/null +++ b/.workbuddy/backup/p0-avatar-qrcode-20260905/internal/storage/s3.go @@ -0,0 +1,279 @@ +// Copyright 2024 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package storage + +import ( + "bytes" + "context" + "fmt" + "image" + _ "image/gif" + _ "image/jpeg" + _ "image/png" + "io" + "mime/multipart" + "os" + "os/exec" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/chai2010/webp" + "github.com/disintegration/imaging" + "github.com/pkg/errors" + "github.com/thanhpk/randstr" + "github.com/wuhan005/gadget" + + "github.com/tamakyi/TamaBox/internal/conf" + "github.com/tamakyi/TamaBox/internal/imagecheck" +) + +// MaxUploadBytes 是单次图片上传的内存读取上限(8MB)。 +// 调用方虽在 HTTP 层对 fileHeader.Size 做了校验,但该值可被客户端伪造, +// 因此在读取前用 io.LimitReader 兜底,避免超大文件将内存撑爆(DoS)。 +const MaxUploadBytes = 8 * 1024 * 1024 + +// aspect 约束一次上传的宽高比(wantW:wantH,容差 DefaultAspectTolerance)。 +// 头像固定 1:1、页面背景固定 16:9:客户端裁剪后即为精确比例, +// 服务端复校验用于拦截绕过前端直接 POST 的越界图片。 +type aspect struct { + W, H float64 +} + +func (a *aspect) check(data []byte) error { + if a == nil { + return nil + } + return imagecheck.CheckAspectRatio(bytes.NewReader(data), a.W, a.H, imagecheck.DefaultAspectTolerance) +} + +// UploadAvatarToS3 上传头像:除通用校验/转换外强制 1:1 宽高比。 +func UploadAvatarToS3(file multipart.File, fileHeader *multipart.FileHeader) (string, error) { + return uploadPictureToS3(file, fileHeader, &aspect{W: 1, H: 1}) +} + +// UploadBackgroundToS3 上传页面背景:除通用校验/转换外强制 16:9 宽高比。 +func UploadBackgroundToS3(file multipart.File, fileHeader *multipart.FileHeader) (string, error) { + return uploadPictureToS3(file, fileHeader, &aspect{W: 16, H: 9}) +} + +// UploadPictureToS3 上传通用图片到 Cloudflare R2,自动转换为 WebP(动画 GIF 可选转换) +func UploadPictureToS3(file multipart.File, fileHeader *multipart.FileHeader) (string, error) { + return uploadPictureToS3(file, fileHeader, nil) +} + +// uploadPictureToS3 是上传管线实现:读入 → 魔数 → (可选)比例校验 → 像素总量校验 +// → 解码 → WebP 转换 → 落盘 R2。avatar/background 的固定比例校验复用同一管线, +// 仅通过 aspect 参数区分,避免为一种用途复制一套上传代码。 +func uploadPictureToS3(file multipart.File, fileHeader *multipart.FileHeader, asp *aspect) (string, error) { + // 1. 限制读取大小,防止超大上传撑爆内存(DoS)。 + // 先用 LimitReader 截断到 MaxUploadBytes+1 字节;若实际读到的字节数超过上限则直接拒绝。 + limited := io.LimitReader(file, MaxUploadBytes+1) + fileData, err := io.ReadAll(limited) + if err != nil { + return "", errors.Wrap(err, "read file data") + } + if int64(len(fileData)) > MaxUploadBytes { + return "", errors.New("uploaded file is too large") + } + + // 2. 校验文件魔数,仅允许 JPEG / PNG / GIF / WebP + if !isSupportedImage(fileData) { + return "", errors.New("unsupported file type: not a valid image") + } + + // 2.5 用途宽高比校验(头像 1:1 / 背景 16:9),绕过前端裁剪的直传在此被拦截 + if err := asp.check(fileData); err != nil { + return "", err + } + + fileReader := bytes.NewReader(fileData) + + // 3. 解码前先校验像素总量(防解压炸弹),再解码图片获取格式;解码失败则直接返回错误。 + if err := imagecheck.CheckPixelLimit(bytes.NewReader(fileData)); err != nil { + return "", err + } + + _, format, err := image.Decode(fileReader) + if err != nil { + return "", errors.Wrap(err, "image decode failed, file may be corrupted") + } + + var uploadData []byte + var contentType string + + // 重置 reader,以便后续可能的 resize 操作 + if _, err := fileReader.Seek(0, io.SeekStart); err != nil { + return "", errors.Wrap(err, "reset reader") + } + + // 4. 根据格式进行转换或直接使用原图 + switch format { + case "gif": + webpData, err := convertGifToAnimatedWebP(fileData) + if err != nil { + // 转换失败则回退到原始 GIF + uploadData = fileData + contentType = "image/gif" + } else { + uploadData = webpData + contentType = "image/webp" + } + default: + // 静态图片(JPEG / PNG / WebP 等)转换为静态 WebP + webpData, err := ConvertStaticImageToWebP(fileReader) + if err != nil { + // 转换失败时回退到原始图片 + uploadData = fileData + contentType = mimeTypeFromFormat(format) + } else { + uploadData = webpData + contentType = "image/webp" + } + } + + // 5. 生成存储路径(无后缀名) + now := time.Now() + year := now.Year() + month := int(now.Month()) + day := now.Day() + key := fmt.Sprintf("%s%d/%02d/%02d/%s", PictureKeyPrefix, year, month, day, randstr.Hex(15)) + + // 6. 获取共享 S3 客户端 + client, err := GetS3Client() + if err != nil { + return "", errors.Wrap(err, "get S3 client") + } + + // 7. 上传到 R2 + if err := gadget.Retry(5, func() error { + _, err := client.PutObject(context.Background(), &s3.PutObjectInput{ + Bucket: aws.String(conf.Upload.ImageBucket), + Key: aws.String(key), + Body: bytes.NewReader(uploadData), + ContentLength: aws.Int64(int64(len(uploadData))), + ContentType: aws.String(contentType), + }) + return err + }); err != nil { + return "", errors.Wrap(err, "put object after retry") + } + + // 8. 返回 CDN URL + return fmt.Sprintf("https://%s/%s", conf.Upload.ImageBucketCDNHost, key), nil +} + +// ConvertStaticImageToWebP 将静态图片(JPEG/PNG等)转换为 WebP 格式 +// 限制最大宽度为 1920px,保持比例 +func ConvertStaticImageToWebP(r io.Reader) ([]byte, error) { + // 先整体读入并校验像素总量(防解压炸弹),再完整解码。 + data, err := io.ReadAll(r) + if err != nil { + return nil, errors.Wrap(err, "read image") + } + if err := imagecheck.CheckPixelLimit(bytes.NewReader(data)); err != nil { + return nil, errors.Wrap(err, "check image pixel limit") + } + + img, _, err := image.Decode(bytes.NewReader(data)) + if err != nil { + return nil, errors.Wrap(err, "decode image") + } + + maxWidth := 1920 + if img.Bounds().Dx() > maxWidth { + img = imaging.Resize(img, maxWidth, 0, imaging.Lanczos) + } + + buf := new(bytes.Buffer) + if err := webp.Encode(buf, img, &webp.Options{Quality: 80}); err != nil { + return nil, errors.Wrap(err, "webp encode") + } + return buf.Bytes(), nil +} + +// convertGifToAnimatedWebP 将 GIF 文件数据转换为动画 WebP(需要系统安装 cwebp 工具) +// 如果 cwebp 不可用,返回错误,调用方应回退到原始 GIF +func convertGifToAnimatedWebP(gifData []byte) ([]byte, error) { + _, err := exec.LookPath("cwebp") + if err != nil { + return nil, errors.New("cwebp not found in PATH") + } + + tmpGif, err := os.CreateTemp("", "input_*.gif") + if err != nil { + return nil, errors.Wrap(err, "create temp gif") + } + defer os.Remove(tmpGif.Name()) + if _, err := tmpGif.Write(gifData); err != nil { + return nil, errors.Wrap(err, "write temp gif") + } + tmpGif.Close() + + tmpWebp, err := os.CreateTemp("", "output_*.webp") + if err != nil { + return nil, errors.Wrap(err, "create temp webp") + } + defer os.Remove(tmpWebp.Name()) + tmpWebp.Close() + + cmd := exec.Command("cwebp", "-q", "80", "-mixed", "-mt", "-quiet", tmpGif.Name(), "-o", tmpWebp.Name()) + if err := cmd.Run(); err != nil { + return nil, errors.Wrap(err, "run cwebp") + } + + webpData, err := os.ReadFile(tmpWebp.Name()) + if err != nil { + return nil, errors.Wrap(err, "read webp output") + } + return webpData, nil +} + +// mimeTypeFromFormat 根据图片格式返回 MIME 类型 +func mimeTypeFromFormat(format string) string { + switch format { + case "jpeg": + return "image/jpeg" + case "png": + return "image/png" + case "gif": + return "image/gif" + case "webp": + return "image/webp" + default: + return "application/octet-stream" + } +} + +// isSupportedImage 通过文件头魔数判断是否为支持的图片格式 +func isSupportedImage(data []byte) bool { + if len(data) < 4 { + return false + } + + // JPEG: FF D8 FF + if data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF { + return true + } + + // PNG: 89 50 4E 47 + if bytes.Equal(data[:4], []byte{0x89, 0x50, 0x4E, 0x47}) { + return true + } + + // GIF: GIF87a / GIF89a + if len(data) >= 6 { + if bytes.Equal(data[:6], []byte("GIF87a")) || bytes.Equal(data[:6], []byte("GIF89a")) { + return true + } + } + + // WebP: RIFF ... WEBP + if len(data) >= 12 && bytes.Equal(data[:4], []byte("RIFF")) && bytes.Equal(data[8:12], []byte("WEBP")) { + return true + } + + return false +} diff --git a/.workbuddy/backup/p0-avatar-qrcode-20260905/templates/base/header.html b/.workbuddy/backup/p0-avatar-qrcode-20260905/templates/base/header.html new file mode 100644 index 0000000..09c4e2e --- /dev/null +++ b/.workbuddy/backup/p0-avatar-qrcode-20260905/templates/base/header.html @@ -0,0 +1,977 @@ + + + + + + {{ .Title }} + + + + + + + + + + + + + + + + + + {{ if .VConsole }} + + + {{ end }} + + + + + + {{ if eq .CaptchaType "math" }} + + + {{ else if .RecaptchaTurnstileStyle }} + + + {{ else }} + + + {{ end }} + {{ if ne SentryDSN "" }} + + + {{ end }} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {{ if .NoIndex }}{{ end }} + {{ if .IsUserPage }} + + + + + + + + + {{ else }} + + + + + + + {{ end }} + + + + + + + + + + + +
+ {{ if not .IsUserPage }} + + {{ end }} + +
+ + + +{{ if .IsPixel }} +
+{{ else }} +
+{{ end }} + +{{ if eq .CaptchaType "math" }} +
+
+

{{t .LangCode "captcha.title"}}

+

{{t .LangCode "captcha.hint"}}

+
+ {{t .LangCode "captcha.loading"}} + +
+
+ +
+ +
+ + +
+
+
+ + + + +{{ end }} \ No newline at end of file diff --git a/.workbuddy/backup/p0-avatar-qrcode-20260905/templates/question/list.html b/.workbuddy/backup/p0-avatar-qrcode-20260905/templates/question/list.html new file mode 100644 index 0000000..35f243c --- /dev/null +++ b/.workbuddy/backup/p0-avatar-qrcode-20260905/templates/question/list.html @@ -0,0 +1,309 @@ +{{template "base/header" .}} + + + + + +
+
+
+ +

{{ .PageUser.Name }}

+

{{ .PageUser.Intro }}

+
+ {{ if and .PageUser.Acfunlink (ne .PageUser.Acfunlink "none") }} + + acfunlink + + {{ end }} + {{ if and .PageUser.Bililink (ne .PageUser.Bililink "none") }} + + bililink + + {{ end }} + {{ if and .PageUser.Weibolink (ne .PageUser.Weibolink "none") }} + + weibolink + + {{ end }} + {{ if and .PageUser.Xiaohongshulink (ne .PageUser.Xiaohongshulink "none") }} + + xiaohongshulink + + {{ end }} + {{ if and .PageUser.Bloglink (ne .PageUser.Bloglink "none") }} + + bloglink + + {{ end }} +
+
+
+
+ +
+
+ {{ if .CanAsk }} + + + +
+ + +

{{t .LangCode "ask.scan" .PageUser.Name}}
{{ if .RegisterOnlyAsk }}{{t .LangCode "ask.registerOnly"}}{{ else }}{{t .LangCode "ask.anonymous"}}{{ end }}

+ + + + + + + {{ end }} + {{template "base/alert" .}} + + +
+ + {{ if .VoteEnabled }} + + {{ else }} + + + {{ end }} +
+ +
+ {{template "question/new-question-template" .}} + + {{ if ne (len .PageQuestions) 0 }} +

{{t .LangCode "ask.history" .PageUser.Name}} ({{ .AnsweredCount }})

+ {{ template "question/history-template" . }} + {{ end }} +
+ + +
+
+ +{{template "base/footer" .}} \ No newline at end of file diff --git a/.workbuddy/backup/p0-avatar-qrcode-20260905/templates/question/question-not-found.html b/.workbuddy/backup/p0-avatar-qrcode-20260905/templates/question/question-not-found.html new file mode 100644 index 0000000..eeb6bde --- /dev/null +++ b/.workbuddy/backup/p0-avatar-qrcode-20260905/templates/question/question-not-found.html @@ -0,0 +1,105 @@ +{{template "base/header" .}} + + + + + +
+
+
+ +

{{ .PageUser.Name }}

+

{{ .PageUser.Intro }}

+
+ {{ if and .PageUser.Acfunlink (ne .PageUser.Acfunlink "none") }} + + acfunlink + + {{ end }} + {{ if and .PageUser.Bililink (ne .PageUser.Bililink "none") }} + + bililink + + {{ end }} + {{ if and .PageUser.Weibolink (ne .PageUser.Weibolink "none") }} + + weibolink + + {{ end }} + {{ if and .PageUser.Xiaohongshulink (ne .PageUser.Xiaohongshulink "none") }} + + xiaohongshulink + + {{ end }} + {{ if and .PageUser.Bloglink (ne .PageUser.Bloglink "none") }} + + bloglink + + {{ end }} +
+
+
+
+ +
+
+ {{ if .CanAsk }} + + + +
+ + +

扫码向@{{ .PageUser.Name }}提问
{{ if .RegisterOnlyAsk }}{{t .LangCode "ask.registerOnly"}}{{ else }}{{t .LangCode "ask.anonymous"}}{{ end }}

+ {{ end }} + {{template "base/alert" .}} + {{template "question/new-question-template" .}} + +
+ {{ if ne (len .PageQuestions) 0 }} +

@{{ .PageUser.Name }} 以前回答过的问题 ({{ .AnsweredCount }})

+ {{ template "question/history-template" . }} + {{ end }} +
+
+{{template "base/footer" .}} \ No newline at end of file diff --git a/.workbuddy/backup/p0-avatar-qrcode-20260905/templates/user/profile.html b/.workbuddy/backup/p0-avatar-qrcode-20260905/templates/user/profile.html new file mode 100644 index 0000000..5e337d6 --- /dev/null +++ b/.workbuddy/backup/p0-avatar-qrcode-20260905/templates/user/profile.html @@ -0,0 +1,1527 @@ +{{template "base/header" .}} + + + + + + + + + + + + + + + + +{{template "base/alert" .}} + + +
+
+ +
+

{{t .LangCode "profile.cropTitle"}}

+
+
+
+ +
+

+
+ +
+
+ + +
+ + + + +
+ + +
+
+ {{ .CSRFTokenHTML }} + + +
+

{{t .LangCode "profile.card.basic"}}

+
+ + +
+
+ + +
+
+ +
+ +
+
+ + +
+
+ +
+ +
+
+ + + {{t .LangCode "admin.langHint"}} +
+
+ + +
+
+ +
+
+ + +
+

{{t .LangCode "profile.card.avatarBg"}}

+
+
+ + + + 1:1 +
+ + +
+ {{t .LangCode "profile.avatarCropHint"}} +
+
+ + + + 16:9 +
+ + +
+ {{t .LangCode "profile.backgroundCropHint"}} +
+
+ +
+ +
+
+ + +
+
    +
  • + {{t .LangCode "profile.card.qr"}} +
    +
    +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + + {{t .LangCode "admin.customFgHint"}} +
    +
    + +
    + + {{.LoggedUser.Dotscale}} + +
    +
    +
    + +
    + + {{.LoggedUser.Backgroundimagealpha}} + +
    +
    +
    + +
    + + +
    + {{t .LangCode "admin.qrPreviewHint"}} +
    +
    +
    +
    +

    {{t .LangCode "admin.preview"}}

    +
    +
    +
    + {{t .LangCode "admin.themePreset"}} +
    + + + + +
    +
    +
    + +
    +

    {{t .LangCode "admin.previewHint"}}

    +
    +
    +
    +
    +
  • +
+
+ +
+
+ + +
+
    +
  • + {{t .LangCode "admin.social"}} +
    + {{t .LangCode "admin.socialHint"}} + + + + + +
    +
  • +
+
+ +
+
+ + +
+

{{t .LangCode "profile.card.password"}}

+
+ + +
+
+ + +
+

{{t .LangCode "profile.pwdNote"}}

+
+
+ +
+
+
+ + +
+

{{t .LangCode "admin.tags"}}

+
+ {{ .CSRFTokenHTML }} +
+ + +
+
+ +
+
+ +
+
+
+ + +
+

{{t .LangCode "admin.pagePassword"}}

+
+ {{ .CSRFTokenHTML }} +
+ + +
+
+ +
+
+
+ + +
+

{{t .LangCode "admin.account"}}

+ +
+
+ + + +
+ {{ with .FeatureQuestion }}{{template "user/feature-control-form" .}}{{ end }} + +
+
+
+ {{ $.CSRFTokenHTML }} + {{t $.LangCode "admin.harassment"}} +
+
+ +
+
+ +
+
+
+ + + {{ template "user/global-blockwords" (dict "Root" $ "Action" "/user/blockwords/update?tab=question") }} + +
+
+
+ {{ $.CSRFTokenHTML }} + {{t $.LangCode "admin.askPassword"}} +
+ + +
+
+ +
+
+
+
+ + +
+ +
+ {{ with .FeatureChat }}{{template "user/feature-control-form" .}}{{ end }} + +
+
+ {{ $.CSRFTokenHTML }} + {{t $.LangCode "admin.chat"}} +
+ + {{ with $.ChatLimits }} + + {{ end }} +
+
+ + {{ with $.ChatLimits }} + + {{ end }} + {{t $.LangCode "admin.dailyLimitHint"}} +
+
+ +
+
+
+ +
+ + {{ template "user/global-blockwords" (dict "Root" $ "Action" "/user/blockwords/update?tab=chat") }} +
+ + +
+ {{ with .FeatureVote }}{{template "user/feature-control-form" .}}{{ end }} + +
+ + {{ template "user/global-blockwords" (dict "Root" $ "Action" "/user/blockwords/update?tab=vote") }} +
+ + + + + + + + + +{{template "base/footer" .}} diff --git a/.workbuddy/backup/remove-vercount-20260906/dict_en.go b/.workbuddy/backup/remove-vercount-20260906/dict_en.go new file mode 100644 index 0000000..c3c7f1c --- /dev/null +++ b/.workbuddy/backup/remove-vercount-20260906/dict_en.go @@ -0,0 +1,842 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package i18n + +// enDict English copy. +var enDict = map[string]string{ + // Navigation + "nav.explore": "Explore", + "nav.mine": "Mine", + "nav.register": "Sign up", + "nav.login": "Log in", + "nav.ask": "Ask", + "nav.settings": "Settings", + "nav.lang": "Language", + + // Common + "common.login": "Log in", + "common.forgot": "Forgot password", + "common.submit": "Submit", + "common.cancel": "Cancel", + "common.save": "Save", + "common.close": "Close", + "common.delete": "Delete", + "common.moveUp": "Move up", + "common.moveDown": "Move down", + "common.share": "Share", + "common.verifying": "Verifying...", + "common.submitting": "Submitting...", + "common.uploading": "Uploading...", + "common.lang": "Language", + "common.menu": "Menu", + + "common.pleaseWait": "Please wait...", + "common.backHome": "Back to Home", + "common.theme": "Toggle dark/light mode", + + // Site + "site.title": "Wolf's Question Box | Anonymous Question Box", + "site.description": "Wolf's Question Box is an anonymous question box — ask me anything without signing up, a safe space to share and respond.", + "site.keywords": "Anonymous Question Box,question box,anonymous ask,ask anonymously,Wolf's Question Box,anonymous Q&A", + "site.footer.visitor": "You are visitor #%s", + "site.footer.pageview": "This page has been viewed %s times", + "site.footer.runtime": "The box has been alive for", + "site.footer.admin": "Contact admin", + "site.footer.notice": "Announcements", + "site.footer.chat": "Chat room", + "site.footer.drive": "Drive", + "site.footer.status": "Status", + "site.footer.nav": "Links", + "site.maintenance": "The site is under maintenance. Please come back later ~", + + // Auth + "auth.login.title": "User Log in", + "auth.login.email": "Email", + "auth.login.password": "Password", + "auth.login.submit": "Log in", + "auth.login.forgot": "Forgot password", + "auth.register.title": "User Sign up", + "auth.register.name": "Nickname", + "auth.register.email": "Email", + "auth.register.password": "Password", + "auth.register.submit": "Sign up", + "auth.forgot.title": "Forgot password", + "auth.forgot.email": "Email", + "auth.forgot.submit": "Send reset email", + "auth.forgot.submitBtn": "Recover password", + "auth.forgot.sent": "An email has been sent to %s, please check your inbox.", + "auth.recover.title": "Reset password", + "auth.recover.greeting": "%s, you are resetting your password:", + "auth.recover.password": "New password", + "auth.recover.confirm": "Confirm password", + "auth.recover.submit": "Reset password", + + // Explore + "explore.title": "Explore User Tags", + "explore.notice": "Here you can find users who enabled \"Show my tags on the homepage\". This feature is off by default. To get discovered here, go to your profile settings and enable it.", + "explore.shuffle": "Shuffle", + "explore.empty": "No users to show yet. Enable it and be the first!", + "explore.hotVotes": "Hot polls", + "explore.questionsTab": "Questions", + "explore.votesTab": "Polls", + "explore.votesTitle": "Public polls", + "explore.votesDesc": "Browse active public polls and join the topics that interest you.", + "explore.randomVote": "Random pick", + "explore.allVotes": "All polls", + "explore.noVotes": "There are no public polls available right now.", + + // Ask page + "ask.scan": "Scan to ask @%s", + "ask.anonymous": "Anyone can ask anonymously", + "ask.registerOnly": "Only registered users can ask", + "ask.nextOpenAt": "Next opening: %s", + "ask.lastCloseAt": "Last closed: %s", + "weekday.0": "Sun", + "weekday.1": "Mon", + "weekday.2": "Tue", + "weekday.3": "Wed", + "weekday.4": "Thu", + "weekday.5": "Fri", + "weekday.6": "Sat", + "ask.pinned": "Pinned", + "ask.share": "Share this box", + "ask.placeholder": "Write your question here...", + "ask.chatPlaceholder": "Write your chat message here...", + "ask.addImage": "Add image", + "ask.private": "Don't publish after reply", + "ask.notify": "Notify me", + "ask.emailPlaceholder": "Enter your email address", + "ask.submit": "Send question", + "ask.chat": "Start a chat", + "ask.chatDisabled": "Chat is disabled on this box", + "ask.chatLimit": "Message limit: %d", + "ask.history": "Previously answered by @%s", + "ask.loginRequired": "Log in required", + "ask.loginRequiredChat": "You need to log in to start a chat", + "ask.goLogin": "Go to login", + "ask.needPassword": "This box requires a password", + "ask.needLogin": "The owner only allows registered users to ask questions. Please log in first.", + "ask.pleaseEmail": "Please enter your email to receive notifications", + "ask.generating": "Generating share card…", + "ask.genFailed": "Failed to generate share card. Please try again later", + "ask.networkError": "Network error", + "ask.shareFilename": "share.png", + + // Question item + "qitem.answer": "Answer", + "qitem.delete": "Delete", + "qitem.private": "Make private", + "qitem.public": "Make public", + "qitem.asked": "Asked", + "qitem.pending": "Pending reply", + "qitem.answeredBy": "Answer by @%s on %s", + "qitem.danger": "Danger!", + "qitem.deleteConfirm": "Are you sure you want to delete this question? This cannot be undone.", + "qitem.deleteConfirmBtn": "Yes, delete", + "qitem.backToBox": "Back to %s's question box", + "qitem.answerTitle": "Answer the question", + "qitem.answerPlaceholder": "Write your answer here...", + "qitem.emailNotifyHint": "The asker left their email. Once you answer this question for the first time, they will receive an email notification.", + "qitem.submitAnswer": "Answer", + "qitem.updateAnswer": "Update answer", + "qitem.askMore": "Ask something else?", + "qitem.markRead": "Mark as read", + "qitem.markUnread": "Mark as unread", + "qitem.readLocked": "Answered, locked as read", + + // Admin / profile page + "admin.profile": "Profile", + "admin.lang": "Language", + "admin.langHint": "Choose the language visitors see when they open your question box (admin pages follow this too)", + "admin.email": "Email", + "admin.name": "Nickname", + "admin.nameColor": "Nickname color", + "admin.oldPassword": "Old password", + "admin.newPassword": "New password", + "admin.notify": "New question notifications", + "admin.personalize": "Customization", + "admin.intro": "Box introduction", + "admin.introColor": "Introduction color", + "admin.qrBgColor": "QR background color (light part)", + "admin.qrPdColor": "QR finder pattern color (corner squares)", + "admin.qrFgColor": "QR foreground color", + "admin.qrDotSize": "QR dot size (←small large→)", + "admin.qrBgAlpha": "QR background opacity (←opaque transparent→)", + "admin.avatar": "Avatar", + "admin.background": "Box background", + "admin.qrBackground": "QR background image", + "admin.social": "Social links", + "admin.harassment": "Anti-harassment", + "admin.askLimit": "Asking restriction", + "admin.blockWords": "Blocked words (press Enter or comma to add, up to 10 words, 10 characters each)", + "admin.chat": "Chat settings", + "admin.chatMaxMessages": "Max messages per chat", + "admin.chatDailyLimit": "Daily message limit per user", + "admin.tags": "Tags", + "admin.tagsHint": "Tags (up to 5, 5 characters each, press Enter or comma to add)", + "admin.tagsPlaceholder": "e.g. anime, music, games", + "admin.tagInputHint": "Type and press Enter or comma to add", + "admin.tagInputDuplicate": "Already exists, ignored", + "admin.pagePassword": "Page access password", + "admin.pagePasswordHint": "Set a page password (leave empty to disable)", + "admin.askPassword": "Ask password", + "admin.askPasswordHint": "Set a password for asking (leave empty to disable)", + "admin.saveProfile": "Save changes", + "admin.updated": "Profile updated successfully", + "admin.logout": "Log out", + "admin.export": "Export data", + + // Admin settings (additional) + "admin.oldPasswordHint": "Only needed when changing password; leave empty to keep it unchanged", + "admin.newPasswordHint": "6-64 characters; leave empty to keep it unchanged", + "admin.notifyEmail": "Email", + "admin.useCustomFg": "Use custom foreground color (otherwise auto-matched)", + "admin.customFgHint": "Only takes effect when enabled; otherwise the color is auto-generated", + "admin.avatarPlaceholder": "Upload avatar (non-1:1 images will be squished)", + "admin.backgroundPlaceholder": "Upload box background", + "admin.qrBackgroundPlaceholder": "Upload QR background (a background that is too dark may make the QR code unreadable)", + "admin.qrPreviewHint": "The preview updates instantly after choosing an image", + "admin.preview": "Live preview", + "admin.themePreset": "Preset themes", + "admin.themeDefault": "Default", + "admin.themeDark": "Dark", + "admin.themeOcean": "Ocean", + "admin.themeSunset": "Sunset", + "admin.resetDefaults": "🔄 Reset to defaults", + "admin.previewHint": "Adjustments are for preview only; click \"Save changes\" to apply", + "admin.socialHint": "Check the box and fill in the profile URL (no https:// needed). Unchecked items won't be shown on your page.", + "admin.enableAcfun": "Enable AcFun", + "admin.enableBili": "Enable Bilibili", + "admin.enableWeibo": "Enable Weibo", + "admin.enableXiaohongshu": "Enable Xiaohongshu", + "admin.enableBlog": "Enable Personal Blog", + "admin.registerOnly": "Only allow registered users to ask me questions", + "admin.updateHarassment": "Update anti-harassment settings", + "admin.globalBlockWords": "Global blocked words", + "admin.globalBlockWordsHint": "Blocked words apply to questions, chat messages sent to you, and vote submissions. This single setting is shared across the question / chat / vote panels and takes effect immediately from any of them.", + "admin.updateBlockWords": "Save blocked words", + "admin.allowChat": "Allow registered users to start a chat with me", + "admin.dailyLimitHint": "0 means unlimited", + "admin.updateChat": "Update chat settings", + "admin.showInHome": "Show my tags on the home page (let other users find me by tags)", + "admin.updateTags": "Update tags", + "admin.updatePagePassword": "Update page password", + "admin.pagePasswordPlaceholder": "Enter page access password", + "admin.updateAskPassword": "Update ask password", + "admin.askPasswordPlaceholder": "Enter ask password", + "admin.account": "Account settings", + "admin.exportHint": "You can export all your personal data from %s, including your basic information, received questions and answers.", + "admin.exportJSON": "Export all data (JSON)", + "admin.exportJSONHint": "Includes questions, answers, follow-ups and chats for full backup or migration.", + "admin.deactivate": "Deactivate my account", + "admin.deactivateHint": "You can deactivate your account at any time. After deactivation, your account can no longer log in, your question box page and questions will be inaccessible, and others won't be able to send you new questions.This action cannot be undone. Please be careful!", + "admin.socialRequired": "Please fill in the link or uncheck the box", + + // Question management + "qlist.title": "My Questions", + "qlist.answered": "Answered", + "qlist.pending": "Pending", + "qlist.private": "Private", + "qlist.empty": "No questions yet. Share your box and get some!", + "qlist.action": "Actions", + "qlist.answerNow": "Answer", + "qlist.sort": "Sort", + "qlist.status": "Status", + "qlist.type": "Type", + "qlist.latest": "Latest", + "qlist.oldest": "Oldest", + "qlist.all": "All", + "qlist.public": "Normal question", + "qlist.privateQuestion": "Private question", + "qlist.received": "Questions I received", + "qlist.myChats": "Chats I started", + "qlist.statsTotal": "Total questions", + "qlist.statsAnswered": "Answered", + "qlist.statsUnanswered": "Unanswered", + "qlist.statsPrivate": "Private", + "qlist.statsPinned": "Pinned", + "qlist.statsChats": "Chats", + "qlist.searchPlaceholder": "Search questions or answers...", + "qlist.searchBtn": "Search", + "qlist.searchClear": "Clear", + "qlist.questionsTab": "Questions", + "qlist.votesTab": "Votes", + "qlist.chatsTab": "Chats", + "qlist.receivedChats": "Chats I received", + "qlist.chatEmpty": "No chats yet. Share your question box to start chatting!", + "qlist.pinnedShort": "Pin", + "qlist.privateShort": "Pvt", + "qlist.chatStatsTotal": "Total chats", + "qlist.chatStatsReceived": "Received", + "qlist.chatStatsInitiated": "Initiated", + "qlist.chatStatsClosed": "Closed", + "qlist.unansweredShort": "Open", + "qlist.readShort": "Read", + "qlist.unreadShort": "Unread", + "qitem.markReadShort": "Mark", + "qlist.pinShort": "Pin", + "qlist.unpinShort": "Unpin", + "qlist.myVotes": "My votes", + "qlist.loadMore": "Load more", + "qlist.newVote": "New vote", + "qlist.edit": "Edit", + "qlist.untitledVote": "Untitled vote", + "qlist.blocked": "Blocked", + "qlist.unanswered": "Unanswered", + + // Site logo suffix (random animal emoji + suffix) + "site.logoSuffix": "'s Question Box", + "site.stats": "Question Box Statistics", + + // Captcha modal + "captcha.title": "Verification", + "captcha.hint": "Solve the math problem below to prove you are not a robot", + "captcha.refresh": "New problem", + "captcha.submit": "Verify & submit", + "captcha.loading": "Loading...", + "captcha.loadFailed": "Load failed", + "captcha.loadRetry": "Load failed, please retry", + "captcha.inputAnswer": "Please enter the answer", + "captcha.wrongAnswer": "Wrong answer, please recalculate", + "captcha.verifyFailed": "Verification failed, please retry", + + // Register page extras + "auth.register.domain.prefix": "Custom domain (your box URL will be: %s + ", + "auth.register.domain.suffix": " + what you fill in below)", + "auth.register.confirm": "Confirm password", + "auth.register.language": "Language", + "auth.register.languageDefault": "Use site default", + "auth.register.success": "Registration successful, welcome to TamaBox!", + + // Explore page extras + "explore.recommend": "Random picks", + "explore.search": "Search tags...", + "explore.sortLatest": "Newest", + "explore.sortOldest": "Oldest", + "explore.noTags": "No tags", + "explore.noRecommend": "No recommendations yet", + "explore.hotTags": "Hot Tags", + "explore.hotQuestions": "Hot Questions", + "explore.noResult": "No users match your criteria.", + "explore.lazy": "This user is too lazy to write anything~", + "explore.prevPage": "Previous", + "explore.nextPage": "Next", + "explore.loading": "Loading...", + "explore.loadFailed": "Load failed", + + // Question box password page + "password.title": "This question box is password protected", + "password.desc": "This question box is password protected. Enter the password to view its contents.", + "password.input": "Enter the access password", + "password.enter": "Enter", + "password.submit": "Confirm", + + // Question not found + "qitem.notFound": "Question not found or has been deleted", + + // Chat page + "chat.title": "Chat", + "chat.input": "Type a message...", + "chat.send": "Send", + "chat.delete": "Delete conversation", + "chat.block": "Block user", + "chat.unblock": "Unblock user", + "chat.empty": "No messages yet. Say something~", + "chat.withAsker": "Chat with the asker", + "chat.withUser": "Chat with %s", + "chat.closed": "Conversation closed", + "chat.closedNoSend": "The conversation is closed. You cannot send new messages.", + "chat.remaining": "Messages left: %d (of %d total)", + "chat.me": "Me", + "chat.other": "Other", + "chat.userBlocked": "This user has been blocked", + "chat.addImage": "Add image (optional, max 5MB)", + "chat.confirm": "Confirm", + "chat.confirmBlock": "Block this user? They won't be able to send you messages anymore.", + "chat.confirmUnblock": "Unblock this user? They will be able to send you messages again.", + "chat.deleteConfirm": "Delete this conversation? The other party will no longer be able to see it, and this cannot be undone.", + "maintenance.title": "NekoBox is under maintenance...", + "maintenance.desc": "NekoBox is currently under maintenance and temporarily unavailable. Please come back later~", + + // Single-question share (v4) + "qitem.shareCard": "Share this question", + + // Follow-ups (v4) + "followup.title": "Follow-ups", + "followup.content": "Follow-up: ", + "followup.answerPlaceholder": "Answer this follow-up...", + "followup.answerBtn": "Answer", + "followup.waiting": "Waiting for answer...", + "followup.askMore": "Add a follow-up", + "followup.remaining": "%d / %d follow-ups remaining", + "followup.contentPlaceholder": "Add more details...", + "followup.waitingReply": "Your follow-up has been sent. Waiting for the box owner to reply...", + "followup.submit": "Submit", + + // Pinning (v4) + "qlist.pinned": "Pinned", + "qlist.pin": "Pin", + "qlist.unpin": "Unpin", + "qlist.readStatus": "Read status", + "qlist.read": "Read", + "qlist.unread": "Unread", + "qlist.statsRead": "Read", + "qlist.statsUnread": "Unread", + + // Question submitted page (v4) + "success.title": "Question sent successfully!", + "success.yourQuestion": "Your question:", + "success.emailSent": "A private link to this question was sent to your email. You can also use the link below to view the question, receive replies, and follow up.", + "success.saveLink": "Please save the private link below! Since you didn't leave an email, this link (including the token) is your only credential to view the question, receive replies, and follow up. If you lose it, it cannot be recovered.", + "success.privateLink": "Your private link (click to copy)", + "success.copy": "Copy", + "success.copied": "Copied ✓", + "success.copyFailed": "Copy failed", + "success.token": "Token: %s (the asker uses this token to access the private link)", + "success.viewQuestion": "View my question", + "success.backToBox": "Back to %s's box", + "success.pageTitle": "Question Sent - %s", + + // Deactivate page + "deactivate.title": "Deactivate account", + "deactivate.desc": "After deactivation your question box will be inaccessible and all data will be deleted. This cannot be undone!", + "deactivate.confirm": "I confirm I want to deactivate my account", + "deactivate.submit": "Deactivate account", + + // Anonymous voting + "nav.votes": "Polls", + + "common.back": "Back", + + "vote.listTitle": "Poll Management", + "vote.newTitle": "New Poll", + "vote.editTitle": "Edit Poll", + "vote.resultsTitle": "Poll Results", + "vote.statsTotal": "Total Polls", + "vote.statsPublished": "Active", + "vote.createNew": "New Poll", + "vote.typeSingle": "Single choice", + "vote.typeMultiple": "Multiple choice", + "vote.typeRating": "Rating", + "vote.typeRank": "Ranking", + "vote.typeForm": "Form", + "vote.statusNotStarted": "Not started", + "vote.statusDraft": "Draft", + "vote.statusPublished": "Active", + "vote.statusEnded": "Ended", + "vote.statusArchived": "Archived", + "vote.participants": "Participants", + "vote.remainLabel": "Remaining", + "vote.perpetual": "No deadline", + "vote.durationDay": "d", + "vote.durationHour": "h", + "vote.durationMinute": "m", + "vote.createdAt": "Created", + "vote.edit": "Edit", + "vote.results": "Results", + "vote.preview": "Preview", + "vote.page.mustComplete": "Please complete", + "vote.page.rankHintRequired": "Rank 1-N (required)", + "vote.page.rankHintOptional": "Rank 1-N (optional, partial OK)", + "vote.page.previewHint": "Preview mode: this is a sample of the live page; submitting is disabled", + "vote.page.previewSubmitHint": "Preview mode; submitting is enabled after publish", + "vote.publish": "Publish", + "vote.close": "End", + "vote.share": "Copy link", + "vote.copied": "Copied", + "vote.shareURL": "Poll share link", + "vote.confirmPublish": "Publish this poll? A shareable link will be generated.", + "vote.confirmClose": "End this poll? Participants will no longer be able to vote.", + "vote.confirmDelete": "Delete this poll? All vote data will be removed and cannot be recovered!", + "vote.manageEntry": "Manage polls", + + "vote.manageTitle": "Manage polls", + "vote.manageDesc": "Create and manage your anonymous polls", "vote.empty": "No polls yet. Click \"New Poll\" in the top right to get started.", + "vote.formLockedHint": "This poll is live. Only basic info can be edited; type and options are locked to protect collected votes.", + "vote.formBasic": "Basic Settings", + "vote.formTitle": "Poll Title", + "vote.formTitlePlaceholder": "e.g. What should we eat today?", + "vote.formDescription": "Description", + "vote.formDescriptionPlaceholder": "Optional details", + "vote.formType": "Poll Type", + "vote.formVisibility": "Visibility", + "vote.formVisibilityPublic": "Public (Explore + question box)", + "vote.formVisibilityLinkOnly": "Link only", + "vote.formVoterScope": "Voting Scope", + "vote.formVoterScopeAnyone": "Anyone (including anonymous)", + "vote.formVoterScopeRegistered": "Registered users only", + "vote.formShowResult": "Result Visibility", + "vote.formShowResultAfterVote": "Visible right after voting", + "vote.formShowResultAfterEnd": "Visible after the poll ends", + "vote.formShowResultOwnerOnly": "Owner only", + "vote.formStartAt": "Start time (empty = now)", + "vote.formEndAt": "End time (empty = no limit)", + "vote.formMaxChoices": "Max choices", + "vote.formMaxVotesPerFingerprint": "One vote per device per poll; repeated submissions from the same browser are blocked.", + "vote.formMaxVotesPerAccount": "One vote per registered account per poll; repeated submissions from the same account are blocked.", + "vote.formAllowCustom": "Allow participants to add custom options", + "vote.formRequireCaptcha": "Require captcha for anonymous voting", + "vote.formOptions": "Poll Options", + "vote.formRatingHint": "Rating polls need no options (1-10).", + "vote.addOption": "Add option", + "vote.optionPlaceholder": "Option text", + "vote.formFields": "Form Fields", + "vote.addField": "Add field", + "vote.field": "Field", + "vote.formFieldType": "Field Type", + "vote.fieldTypeText": "Single-line text", + "vote.fieldTypeTextarea": "Multi-line text", + "vote.fieldTypeSelect": "Dropdown select", + "vote.fieldTypeRadio": "Single choice", + "vote.fieldTypeCheckbox": "Multiple choice", + "vote.fieldTypeNumber": "Number", + "vote.fieldTypeRank": "Ranking", + "vote.page.selectPlaceholder": "Select...", + "vote.page.avgNumber": "Average", + "vote.page.fieldFilled": "Filled", + "vote.fieldTypeRating": "Rating", + "vote.formFieldLabel": "Field Label", + "vote.formFieldRequired": "Required", + "vote.formFieldMaxLength": "Max length (0 = unlimited)", + "vote.formFieldOptions": "Options", + "vote.formFieldOptionsHint": "Click \"Add option\" to add each option; no comma needed", + "vote.fieldAllowCustom": "Allow participants to add a custom option", + "vote.formFieldOptionsPlaceholder": "e.g. Great,Okay,Poor", + "vote.createDraft": "Save draft", + "vote.builderHintOptions": "At least 2 options are required", + "vote.builderHintFields": "Add at least 1 field", + "vote.builderHintFieldOptions": "Choice/rank fields need options (rank needs at least 2)", + "vote.resultsAnswered": "Answered", + "vote.page.rankedTimes": "Ranked", + "vote.resultsTotal": "Total participants", + "vote.resultsSubmissions": "Form responses", + "vote.resultsViewTexts": "View text responses", + "vote.resultsToggleHint": "Click to expand or collapse text responses", + "vote.resultsOptions": "Poll results", + "vote.resultsVotes": "votes", + "vote.export": "Export CSV", + "vote.resultsEmpty": "No participation yet. Share the link!", + + // Poll participation page + "vote.inlineTitle": "Polls", + "vote.page.by": "poll", + "vote.page.goVote": "Vote", + "vote.page.notStarted": "Not started", + "vote.page.notStartedHint": "This poll has not started yet.", + "vote.page.ended": "Ended", + "vote.page.endedHint": "This poll has ended.", + "vote.page.active": "Active", + "vote.page.participated": "Participated", + "vote.page.loginRequired": "This poll is limited to registered users. Please log in first.", + "vote.page.anonymousHint": "Anonymous participation is allowed and your identity is not recorded (max 1 per device).", + "vote.page.submit": "Submit vote", + "vote.page.alreadyVoted": "You have already participated in this poll. Thanks!", + "vote.page.resultsTitle": "Poll Results", + "vote.page.totalVotes": "Total", + "vote.page.avgRating": "Average", + "vote.page.avgRank": "Avg rank", + "vote.page.optionColumn": "Option", + "vote.page.ratingLabel": "Rate", + "vote.page.ratingUnit": "pts", + "vote.page.rankHint": "Rank each option 1-N (smaller = higher, no duplicates)", + "vote.page.rankPlaceholder": "Rank", + "vote.page.multipleHint": "Multiple choice", + "vote.page.customOption": "Custom option (optional)", + "vote.page.customPlaceholder": "Type your own option", + "vote.page.customOther": "Other", + "vote.page.customFieldPlaceholder": "Type a custom option...", + "vote.page.customStats": "Custom options", + "vote.page.formCount": "Responses received", + "vote.page.ownerManage": "Manage this poll (results visible only to you)", + + // Per-poll quota collection + "vote.formQuotaLimit": "Collection quota (responses)", + "vote.formQuotaHint": "0 means unlimited; the poll ends automatically once the quota is reached.", + "vote.flash.notFound": "This poll does not exist or is no longer available", + "vote.flash.notPublished": "This poll has not been published yet", + "vote.flash.archived": "This poll has been archived and is closed", + "vote.flash.ended": "This poll has ended", + "vote.flash.notStarted": "This poll has not started yet", + "vote.flash.success": "Vote submitted. Thanks for participating!", + "vote.err.noChoice": "Please select at least one option", + "vote.err.tooManyChoices": "You can select at most %d options", + "vote.err.pickOne": "Please select an option", + "vote.err.invalidOption": "Invalid option", + "vote.err.optionDuplicate": "Options cannot be duplicated", + "vote.err.ratingRequired": "Please provide a rating from 1 to 10", + "vote.err.rankRequired": "Please rank every option from 1 to %d", + "vote.err.rankDuplicate": "Rankings must not repeat", + "vote.err.fieldRequired": "Please fill in \"%s\"", + "vote.err.fieldCustomRequired": "Please fill in the custom option for \"%s\"", + "vote.err.fieldCustomTooLong": "The custom option for \"%s\" must be at most %d characters", + "vote.err.fieldInvalidOption": "Invalid option for \"%s\"", + "vote.err.fieldConfigError": "Misconfigured options for \"%s\"", + "vote.err.fieldRankIncomplete": "Please provide a complete ranking for \"%s\"", + "vote.err.fieldRankRange": "The ranking for \"%s\" must be a number between 1 and %d", + "vote.err.fieldRankDuplicate": "Rankings for \"%s\" must not repeat", + "vote.err.fieldTooLong": "\"%s\" exceeds the length limit (max %d characters)", + "vote.err.fieldNotNumber": "\"%s\" must be a number", + "vote.err.fieldRating": "\"%s\" requires a rating from 1 to 10", + "vote.err.unknownType": "Unknown poll type", + "vote.err.customTooLong": "The custom option must be at most %d characters", + "vote.err.blockWords": "Your submission contains a blocked word set by the poll creator and could not be submitted", + "vote.err.serialize": "Failed to serialize the submission", + "captcha.error": "Captcha verification failed", + "captcha.errEmpty": "Captcha cannot be empty", + "captcha.errFormat": "Invalid captcha format, please refresh and try again", + "captcha.errAnswerFormat": "Invalid captcha answer format", + "captcha.errExpired": "Captcha expired, please refresh and try again", + "captcha.errService": "Captcha service error, please try again later", + "captcha.errAnswerWrong": "Incorrect captcha answer", + "censor.unavailable": "The content moderation service is temporarily unavailable. Please try again later.", + + // Feature management: switch / schedule / quota for questions, chats and polls + "admin.tabAccount": "Settings", + "admin.featuresHint": "Manage the switch, opening hours and collection quota of each feature on the Questions / Chats / Polls panels. A feature closes automatically once its quota is reached.", + "admin.featuresEntry": "Settings", + "admin.featureHint.question": "Visitors cannot submit new questions while closed; collection stops automatically once the quota is reached (private questions included).", + "admin.featureHint.chat": "Visitors cannot start new chats while closed; existing conversations are unaffected.", + "admin.featureHint.vote": "Your polls are hidden from your box page and cannot be answered while closed. Each poll can also define its own quota on the edit page.", + "admin.featureEnabled": "Enable this feature", + "admin.featureOpenAt": "Open at", + "admin.featureCloseAt": "Close at", + "admin.featureTimeHint": "Leave blank for no limit; the feature is unavailable before the open time and after the close time.", + "admin.featureSchedule": "Recurring schedule (weekly)", + "admin.featureScheduleStart": "Daily start", + "admin.featureScheduleEnd": "Daily end", + "admin.featureScheduleHint": "Select the weekdays and a daily time window to open every week. Leave all empty to disable. Days without a time window open all day; a time window with no weekday selected opens every day.", + "admin.featureMode": "Schedule mode", + "admin.featureModeAlways": "Always open", + "admin.featureModeWindow": "One-time window", + "admin.featureModeRecurring": "Weekly schedule", + "admin.featureModeHint": "Always open: no time limit until manually disabled. One-time window: a single open/close time window. Weekly schedule: recurring weekly open days and hours. Modes are mutually exclusive; settings of unselected modes are cleared on save.", + "admin.featureQuotaLimit": "Collection quota (items)", + "admin.featureQuotaHint": "0 means unlimited; the feature closes automatically once the quota is reached. Reset the counter to start a new round.", + "admin.featureQuotaCount": "Collected", + "admin.featureQuotaUnlimited": "Unlimited", + "admin.featureQuotaResetAt": "Last reset: ", + "admin.featureResetQuota": "Reset counter", + "admin.featureSave": "Save this feature", + + // Feature management: states and messages + "feature.name.question": "Questions", + "feature.name.chat": "Chats", + "feature.name.vote": "Polls", + "feature.statusOpen": "Open", + "feature.status.disabled": "Closed", + "feature.status.not_started": "Not started", + "feature.status.ended": "Ended", + "feature.status.quota_reached": "Quota reached", + "feature.saved": "Feature settings saved", + "feature.errTime": "Invalid date for %s, please use the date-time picker", + "feature.errTimeRange": "The close time of %s must be later than the open time", + "feature.errQuota": "The collection quota of %s must be an integer between 0 and 1000000", + "feature.errInvalid": "Unknown feature", + "feature.quotaReset": "The collection counter of %s has been reset", + "feature.errScheduleHalf": "The recurring start and end times of %s must be filled in together", + "feature.errScheduleTime": "Invalid recurring time for %s, please use the time picker", + "feature.errScheduleRange": "The recurring end time of %s must be later than the start time", + + // Messages shown to visitors when a feature is closed + "feature.disabled.question": "The box owner has closed questions", + "feature.disabled.chat": "This box does not accept chats", + "feature.disabled.vote": "This box has closed polls", + "feature.not_started.question": "Questions are not open yet", + "feature.not_started.chat": "Chats are not open yet", + "feature.not_started.vote": "Polls are not open yet", + "feature.ended.question": "Question collection has ended", + "feature.ended.chat": "Chats have ended", + "feature.ended.vote": "Polls have ended", + "feature.quota_reached.question": "The question quota has been reached", + "feature.quota_reached.chat": "The chat quota has been reached", + "feature.quota_reached.vote": "The poll quota has been reached", + + // Auth: visitor-visible messages (P0) + "auth.errBadCredential": "Incorrect email or password", + "auth.errUserNotFound": "User does not exist", + "auth.errEmailFrequent": "Emails are sent too frequently, please try again later", + "auth.errEmailFailed": "Failed to send email, please try again later", + "auth.errCodeExpired": "The verification code has expired", + "auth.errPasswordChanged": "Password changed successfully", + "auth.errLoginRequired": "Please log in first", + "auth.errDuplicateEmail": "This email is already registered", + "auth.errDuplicateDomain": "This custom domain is already taken", + + // Question box page: visitor-visible (P0) + "question.errWrongPassword": "Wrong password", + "question.errAskPasswordWrong": "Wrong ask password", + "question.errLoginRequired": "The owner only allows registered users to ask questions. Please log in first.", + "question.errSelfChat": "You cannot start a chat with yourself", + "question.errBlockedChat": "You have been blocked by the other party and cannot start a chat", + "question.errChatDailyLimit": "You have reached today's message limit (%d). Please try again tomorrow", + "question.errDuplicateSubmit": "Duplicate submission detected, please try again later", + "question.errImageTooLarge": "Image file size cannot exceed 5Mb", + "question.errUploadImageFailed": "Failed to upload image", + "question.errBlockWords": "The question contains a blocked word set by the box owner, and could not be sent", + "question.errAnsweredLocked": "An answered question cannot be marked as unread", + "question.flash.chatSent": "Chat request sent! You can view the conversation via this link: %s", + "question.flash.answered": "Answer published successfully!", + "question.flash.operated": "Operation successful", + "question.flash.markedRead": "Marked as read", + "question.flash.markedUnread": "Marked as unread", + + // Follow-ups: visitor/owner visible (P0) + "followup.errNoPermission": "Permission denied", + "followup.errNotAnswered": "This question has not been answered yet, so you cannot follow up", + "followup.errLimit": "Each question allows at most %d follow-ups, and the limit has been reached", + "followup.errWaitReply": "Please wait for the owner to reply to your previous follow-up before continuing", + "followup.errNotFound": "The follow-up does not exist", + "followup.flash.sent": "Follow-up sent successfully!", + "followup.flash.answered": "Answer posted successfully!", + + // Admin settings: owner visible (P1) + "admin.flash.profileUpdated": "Profile updated successfully", + "admin.flash.chatUpdated": "Chat settings updated successfully", + "admin.flash.pagePwdOff": "Page password access disabled", + "admin.flash.pagePwdUpdated": "Page access password updated", + "admin.flash.askPwdOff": "Ask password disabled", + "admin.flash.askPwdUpdated": "Ask password updated", + "admin.flash.tagsTooMany": "You can have at most 5 tags", + "admin.flash.tagsUpdated": "Tags updated successfully", + "admin.flash.tagTooLong": "Each tag cannot exceed 5 characters: %s", + "admin.flash.blockWordsTooMany": "You can have at most 10 blocked words", + "admin.flash.blockWordTooLong": "A blocked word cannot exceed 10 characters: %s", + "admin.flash.harassmentUpdated": "Anti-harassment settings updated successfully", + "admin.flash.blockWordsUpdated": "Blocked words updated", + "admin.flash.deactivated": "Your account has been deactivated. Thank you for using Wolf's Question Box. We hope to see you again 👋🏻", + "admin.export.errUser": "Export failed: could not get user information", + "admin.export.errQuestion": "Export failed: could not get question information", + + // Vote management: owner visible (P1) + "vote.err.invalidID": "Invalid vote ID", + "vote.err.notExist": "The vote does not exist", + "vote.err.noPermission": "You are not allowed to operate this vote", + "vote.err.type": "Unknown poll type", + "vote.err.titleRequired": "Please fill in the poll title", + "vote.err.titleTooLong": "The poll title cannot exceed 100 characters", + "vote.err.visibility": "Unknown visibility setting", + "vote.err.voterScope": "Unknown voting scope setting", + "vote.err.showResult": "Unknown result visibility setting", + "vote.err.timeRange": "The end time must be later than the start time", + "vote.err.quota": "The collection quota must be an integer between 0 and 1000000", + "vote.err.optionsTooFew": "Please add at least 2 options", + "vote.err.optionsFormat": "Invalid options data format", + "vote.err.optionTooLong": "A single option cannot exceed %d characters", + "vote.err.maxChoicesExceed": "The max choices cannot exceed the total number of options", + "vote.err.fieldsTooFew": "Please add at least 1 form field", + "vote.err.fieldsFormat": "Invalid form fields data format", + "vote.err.fieldsTooMany": "You can have at most 50 form fields", + "vote.err.fieldType": "Unknown form field type", + "vote.err.fieldLabelMissing": "Field #%d is missing a label", + "vote.err.fieldLabelTooLong": "Field #%d label cannot exceed 100 characters", + "vote.err.fieldLabelDuplicate": "The field label \"%s\" is duplicated, please use a different label", + "vote.err.fieldMaxLength": "Field #%d max length must be between 0 and 2000", + "vote.err.fieldReservedOption": "Field #%d (%s) contains a reserved option value, please change it", + "vote.err.fieldOptionsTooFew": "Field #%d (%s) needs at least 1 option", + "vote.err.fieldRankTooFew": "Field #%d (%s) ranking questions need at least 2 options", + "vote.err.fieldSerialize": "Failed to serialize field options", + "vote.err.editClosed": "Votes that are ended or archived cannot be edited", + "vote.err.publishDraftOnly": "Only draft polls can be published", + "vote.err.closePublishedOnly": "Only active polls can be closed", + "vote.err.publishTitleRequired": "Please fill in the poll title before publishing", + "vote.err.publishFormFieldsRequired": "Form polls need at least 1 field", + "vote.err.publishOptionsRequired": "Choice polls need at least 2 options", + "vote.err.optionUpdateFailed": "Failed to update options, please retry", + "vote.err.fieldUpdateFailed": "Failed to update form fields, please retry", + "vote.flash.published": "Poll published! Share link: %s", + "vote.flash.updated": "Poll info updated (active polls cannot change type or options)", + "vote.flash.draftSaved": "Saved to draft", + "vote.flash.closed": "Poll ended", + "vote.flash.deleted": "Poll deleted", + "vote.err.timeFormat": "Invalid time format, please use the datetime picker", + "vote.err.maxChoicesLimit": "Maximum number of choices cannot exceed 20", + "vote.err.descriptionTooLong": "Vote description cannot exceed 5000 characters", + "profile.err.avatarTooLarge": "Avatar file is too large, maximum 2MB", + "profile.err.backgroundTooLarge": "Background image is too large, maximum 2MB", + "profile.err.newPasswordTooShort": "New password must be at least 8 characters", + "profile.err.badOldPassword": "Incorrect old password", + "admin.export.errCreateExcel": "Export failed: could not create Excel file", + "admin.export.errWriteExcel": "Export failed: could not write Excel file", + + // Profile page UI rework: card sections / avatar & background cropping / force re-login after password change + "profile.card.basic": "Basic info", + "profile.card.avatarBg": "Avatar & background", + "profile.card.qr": "QR code style", + "profile.card.password": "Change password", + "profile.avatarCropHint": "Crop frame is locked to 1:1 (square)", + "profile.backgroundCropHint": "Crop frame is locked to 16:9", + "profile.cropTitle": "Crop image", + "profile.cropConfirm": "Apply crop", + "profile.err.avatarRatio": "Avatar image must be a 1:1 square. Please crop it and upload again.", + "profile.err.backgroundRatio": "Background image must have a 16:9 aspect ratio. Please crop it and upload again.", + "profile.flash.passwordChanged": "Password changed. You have been signed out; please sign in again with your new password.", + "profile.pwdNote": "After saving, your current session will end immediately and you will need to sign in again with the new password.", + "profile.pickAvatar": "Change avatar", + "profile.pickBackground": "Change background", + "profile.saveBasic": "Save basic info", + "profile.saveMedia": "Save avatar & background", + "profile.savePassword": "Update password", + "profile.saveQR": "Save QR code style", + "profile.saveSocial": "Save social links", + "profile.err.cropLibUnavailable": "The image cropper failed to load. Please refresh the page and try again.", + + // Captcha JSON endpoint: consumed by frontend (P2) + "captcha.json.badRequest": "Invalid request format", + "captcha.json.idRequired": "Captcha ID cannot be empty", + "captcha.json.genFailed": "Failed to generate captcha", + "chat.errDeletedByOwner": "This private conversation has been deleted by the other party.", + "chat.errBlockedView": "You have been blocked by the other party and cannot view this chat", + "chat.errEmpty": "Message cannot be empty", + "chat.errTooLong": "Message is too long, please keep it within %d characters", + "chat.errConvDeletedSend": "This conversation has been deleted and messages cannot be sent", + "chat.errBlockedSend": "You have been blocked by the other party and cannot send messages", + "chat.errBlockWords": "Your message contains a blocked word set by the box owner and could not be sent", + "chat.errDailyLimit": "You have reached today's message limit (%d), please try again tomorrow", + "chat.errLimitReached": "The conversation has reached its limit and no new messages can be sent", + "chat.errChatClosed": "The box owner has disabled private chat and messages cannot be sent", + "chat.errImageTooLarge": "Image size cannot exceed %dMB", + "chat.errUploadFailed": "Image upload failed, please try again later", + "chat.errNoPermission": "You are not authorized to perform this action", + "chat.flash.sent": "Message sent successfully", + "chat.flash.deleted": "Private conversation deleted", + "chat.flash.operated": "Operation successful", + "image.errTooLarge": "Image is too large, maximum supported size is %d×%d pixels, please compress and re-upload", + "internal.errFlash": "Internal server error, please try again later.", + "internal.errServer": "Internal server error", + "home.errStats": "Failed to retrieve statistics", + "pixel.errPath": "Invalid request path", + "proxy.errNotFound": "Page not found", + "proxy.errInternal": "Service gateway internal error", + "explore.errRandomUser": "Failed to retrieve random users", + // 表单校验 + "form.answer.content": "Answer content is required", + "form.answer.contentTooLong": "Answer content must be within %d characters", + "form.email.required": "Please enter a valid email address", + "form.followup.answer": "Follow-up answer is required", + "form.followup.answerTooLong": "Follow-up answer must be within %d characters", + "form.followup.content": "Follow-up content is required", + "form.followup.contentTooLong": "Follow-up content must be within %d characters", + "form.login.password": "Please enter your password", + "form.profile.backgroundimagealpha": "Please enter the QR code background opacity", + "form.profile.colorHex": "Please enter a 7-character hex color code (including #)", + "form.profile.dotscale": "Please enter the QR code dot size", + "form.profile.intro": "Bio is required and must be at most 100 characters", + "form.profile.linkMax": "Profile link must be at most 30 characters", + "form.profile.name": "Nickname is required and must be at most 20 characters", + "form.profile.newPassword": "New password must be at most 30 characters", + "form.profile.passwordMax": "Password must be at most 30 characters", + "form.question.content": "Question content is required", + "form.question.contentTooLong": "Question content must be within %d characters", + "form.question.receiveReplyEmail": "Please enter a valid email address to receive replies", + "form.recaptcha": "Please complete the CAPTCHA verification", + "form.recover.newPassword": "Please set a new password of 8–30 characters", + "form.recover.repeatPassword": "The two new passwords do not match", + "form.register.domain": "The custom domain may only contain letters, digits and underscores, and must be 3–20 characters long", + "form.register.email": "Please enter a valid email address (max 100 characters)", + "form.register.name": "Nickname is required and must be at most 20 characters", + "form.register.password": "Please set a password of 8–30 characters", + "form.register.recaptcha": "Unable to load the CAPTCHA. Please refresh the page or switch your network and try again", + "form.register.repeatPassword": "The two passwords do not match", +} diff --git a/.workbuddy/backup/remove-vercount-20260906/dict_ja.go b/.workbuddy/backup/remove-vercount-20260906/dict_ja.go new file mode 100644 index 0000000..bc96681 --- /dev/null +++ b/.workbuddy/backup/remove-vercount-20260906/dict_ja.go @@ -0,0 +1,842 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package i18n + +// jaDict 日本語文案。 +var jaDict = map[string]string{ + // ナビゲーション + "nav.explore": "探索", + "nav.mine": "マイ", + "nav.register": "登録", + "nav.login": "ログイン", + "nav.ask": "質問", + "nav.settings": "設定", + "nav.lang": "言語", + + // 共通 + "common.login": "ログイン", + "common.forgot": "パスワードを忘れた", + "common.submit": "送信", + "common.cancel": "キャンセル", + "common.save": "保存", + "common.close": "閉じる", + "common.delete": "削除", + "common.moveUp": "上へ移動", + "common.moveDown": "下へ移動", + "common.share": "共有", + "common.verifying": "認証中...", + "common.submitting": "送信中...", + "common.uploading": "アップロード中...", + "common.lang": "言語", + "common.menu": "メニュー", + + "common.pleaseWait": "お待ちください...", + "common.backHome": "ホームに戻る", + "common.theme": "ダーク/ライトモード切替", + + // サイト + "site.title": "狼の質問箱 | 匿名質問箱", + "site.description": "狼の質問箱は登録不要で使える匿名質問箱。誰でも匿名で質問でき、安心してやり取りできる場所です。", + "site.keywords": "匿名質問箱,質問箱,匿名質問,狼の質問箱,匿名で質問,匿名Q&A", + "site.footer.visitor": "あなたは %s 人目の訪問者です", + "site.footer.pageview": "このページは %s 回閲覧されました", + "site.footer.runtime": "質問箱は稼働中", + "site.footer.admin": "管理者へ", + "site.footer.notice": "お知らせ", + "site.footer.chat": "チャット", + "site.footer.drive": "ドライブ", + "site.footer.status": "ステータス", + "site.footer.nav": "リンク", + "site.maintenance": "メンテナンス中です。しばらくお待ちください~", + + // 認証 + "auth.login.title": "ログイン", + "auth.login.email": "メールアドレス", + "auth.login.password": "パスワード", + "auth.login.submit": "ログイン", + "auth.login.forgot": "パスワードを忘れた", + "auth.register.title": "ユーザー登録", + "auth.register.name": "ニックネーム", + "auth.register.email": "メールアドレス", + "auth.register.password": "パスワード", + "auth.register.submit": "登録", + "auth.forgot.title": "パスワードを忘れた", + "auth.forgot.email": "メールアドレス", + "auth.forgot.submit": "再設定メールを送信", + "auth.forgot.submitBtn": "パスワードを再取得", + "auth.forgot.sent": "%s にメールを送信しました。ご確認ください。", + "auth.recover.title": "パスワード再設定", + "auth.recover.greeting": "%s さん、パスワードを再設定しています:", + "auth.recover.password": "新しいパスワード", + "auth.recover.confirm": "パスワード(確認)", + "auth.recover.submit": "パスワードを再設定", + + // 探索ページ + "explore.title": "ユーザータグを探索", + "explore.notice": "ここでは「ホームでタグを表示」を有効にしたユーザーを紹介しています。この機能は初期状態でオフです。自分の質問箱を見つけてもらいたい場合は 個人設定 から有効にしてください。", + "explore.shuffle": "シャッフル", + "explore.empty": "表示できるユーザーがいません。有効にしてみましょう~", + "explore.hotVotes": "人気の投票", + "explore.questionsTab": "質問", + "explore.votesTab": "投票", + "explore.votesTitle": "公開投票", + "explore.votesDesc": "開催中の公開投票を見て、興味のあるテーマに参加できます。", + "explore.randomVote": "ランダムおすすめ", + "explore.allVotes": "すべての投票", + "explore.noVotes": "現在、参加できる公開投票はありません。", + + // 質問ページ + "ask.scan": "QRコードで@%sに質問", + "ask.anonymous": "誰でも匿名で質問できます", + "ask.registerOnly": "登録ユーザーのみ質問できます", + "ask.nextOpenAt": "次回開放:%s", + "ask.lastCloseAt": "前回終了:%s", + "weekday.0": "日", + "weekday.1": "月", + "weekday.2": "火", + "weekday.3": "水", + "weekday.4": "木", + "weekday.5": "金", + "weekday.6": "土", + "ask.pinned": "ピン留め済み", + "ask.share": "質問箱を共有", + "ask.placeholder": "ここに質問を書いてください...", + "ask.chatPlaceholder": "ここにチャットメッセージを書いてください...", + "ask.addImage": "画像を追加", + "ask.private": "返信後に公開しない", + "ask.notify": "通知を受け取る", + "ask.emailPlaceholder": "メールアドレスを入力してください", + "ask.submit": "質問を送信", + "ask.chat": "チャットを開始", + "ask.chatDisabled": "この質問箱ではチャットが無効です", + "ask.chatLimit": "メッセージ上限:%d件", + "ask.history": "@%s が以前回答した質問", + "ask.loginRequired": "ログインが必要", + "ask.loginRequiredChat": "チャットを開始するにはログインが必要です", + "ask.goLogin": "ログインへ", + "ask.needPassword": "この質問箱にはパスワードが必要です", + "ask.needLogin": "質問箱の所有者は登録ユーザーのみ質問できるように設定しています。先にログインしてください。", + "ask.pleaseEmail": "通知を受け取るメールアドレスを入力してください", + "ask.generating": "共有カードを生成中…", + "ask.genFailed": "共有カードの生成に失敗しました。しばらくしてからお試しください", + "ask.networkError": "ネットワークエラー", + "ask.shareFilename": "share.png", + + // 質問アイテム + "qitem.answer": "回答", + "qitem.delete": "削除", + "qitem.private": "非公開にする", + "qitem.public": "公開にする", + "qitem.asked": "質問", + "qitem.pending": "回答待ち", + "qitem.answeredBy": "@%s による %s の回答", + "qitem.danger": "危険!", + "qitem.deleteConfirm": "この質問を削除してもよろしいですか?この操作は取り消せません。", + "qitem.deleteConfirmBtn": "削除する", + "qitem.backToBox": "%sの質問箱に戻る", + "qitem.answerTitle": "質問に回答する", + "qitem.answerPlaceholder": "ここに回答を入力...", + "qitem.emailNotifyHint": "質問者はメールアドレスを残しています。最初に回答すると、質問者にメール通知が送信されます。", + "qitem.submitAnswer": "回答", + "qitem.updateAnswer": "回答を更新", + "qitem.askMore": "ほかの質問は?", + "qitem.markRead": "既読にする", + "qitem.markUnread": "未読にする", + "qitem.readLocked": "回答済みのため既読に固定", + + // 個人設定ページ + "admin.profile": "プロフィール", + "admin.lang": "表示言語", + "admin.langHint": "訪問者があなたの質問箱を開いたときに表示する言語を選択します(管理画面もこの設定に従います)", + "admin.email": "メールアドレス", + "admin.name": "ニックネーム", + "admin.nameColor": "ニックネームの色", + "admin.oldPassword": "現在のパスワード", + "admin.newPassword": "新しいパスワード", + "admin.notify": "新着質問の通知", + "admin.personalize": "カスタマイズ", + "admin.intro": "質問箱の紹介文", + "admin.introColor": "紹介文の色", + "admin.qrBgColor": "QRコードの背景色(明るい部分)", + "admin.qrPdColor": "QRコードのファインダーパターン色(角の四角)", + "admin.qrFgColor": "QRコードの前景色", + "admin.qrDotSize": "QRコードのドットサイズ (←小 大→)", + "admin.qrBgAlpha": "QRコードの背景透明度 (←不透明 透明→)", + "admin.avatar": "アバター", + "admin.background": "質問箱の背景", + "admin.qrBackground": "QRコードの背景画像", + "admin.social": "ソーシャルリンク", + "admin.harassment": "迷惑行為対策", + "admin.askLimit": "質問制限", + "admin.blockWords": "ブロックワード設定(Enter またはカンマ区切り、最大10個、各10文字まで)", + "admin.chat": "チャット設定", + "admin.chatMaxMessages": "チャットのメッセージ上限", + "admin.chatDailyLimit": "1ユーザーあたりの1日のメッセージ上限", + "admin.tags": "タグ設定", + "admin.tagsHint": "タグ(最大5個、各5文字まで、Enter またはカンマ区切り)", + "admin.tagsPlaceholder": "例:アニメ,音楽,ゲーム", + "admin.tagInputHint": "入力して Enter またはカンマで追加", + "admin.tagInputDuplicate": "既に存在するため無視しました", + "admin.pagePassword": "ページアクセスパスワード", + "admin.pagePasswordHint": "アクセスパスワードを設定(空欄で無効)", + "admin.askPassword": "質問パスワード", + "admin.askPasswordHint": "質問用パスワードを設定(空欄で無効)", + "admin.saveProfile": "変更を保存", + "admin.updated": "プロフィールを更新しました", + "admin.logout": "ログアウト", + "admin.export": "データをエクスポート", + + // 管理画面設定(追加) + "admin.oldPasswordHint": "パスワード変更時のみ使用。空欄のままなら変更されません", + "admin.newPasswordHint": "6〜64文字。空欄のままなら変更されません", + "admin.notifyEmail": "メール", + "admin.useCustomFg": "カスタム前景色を使用(それ以外は自動マッチ)", + "admin.customFgHint": "有効時のみ適用されます。それ以外は自動生成されます", + "admin.avatarPlaceholder": "アバターをアップロード(1:1 以外は縦横比が崩れます)", + "admin.backgroundPlaceholder": "質問箱の背景をアップロード", + "admin.qrBackgroundPlaceholder": "QRコードの背景画像をアップロード(暗すぎる背景はQRコードが読み取れなくなることがあります)", + "admin.qrPreviewHint": "画像を選択するとプレビューが即時更新されます", + "admin.preview": "ライブプレビュー", + "admin.themePreset": "プリセットテーマ", + "admin.themeDefault": "デフォルト", + "admin.themeDark": "ダーク", + "admin.themeOcean": "オーシャン", + "admin.themeSunset": "サンセット", + "admin.resetDefaults": "🔄 デフォルトに戻す", + "admin.previewHint": "調整はプレビューのみです。「変更を保存」をクリックすると反映されます", + "admin.socialHint": "チェックを入れてプロフィールURLを入力してください(https:// は不要)。チェックのない項目は表示されません。", + "admin.enableAcfun": "AcFun を有効にする", + "admin.enableBili": "Bilibili を有効にする", + "admin.enableWeibo": "Weibo を有効にする", + "admin.enableXiaohongshu": "小紅書 を有効にする", + "admin.enableBlog": "個人ブログを有効にする", + "admin.registerOnly": "登録ユーザーのみ質問を許可", + "admin.updateHarassment": "迷惑行為対策を更新", + "admin.globalBlockWords": "共通ブロックワード", + "admin.globalBlockWordsHint": "ブロックワードは質問・チャット(相手からあなたへのメッセージ)・投票の投稿内容に適用されます。この設定は質問/チャット/投票の3つのタブで共有され、どこで変更してもすぐに反映されます。", + "admin.updateBlockWords": "ブロックワードを保存", + "admin.allowChat": "登録ユーザーからのチャットを許可", + "admin.dailyLimitHint": "0 は無制限", + "admin.updateChat": "チャット設定を更新", + "admin.showInHome": "ホームページでタグを表示(タグで検索されることを許可)", + "admin.updateTags": "タグを更新", + "admin.updatePagePassword": "ページパスワードを更新", + "admin.pagePasswordPlaceholder": "ページアクセスパスワードを入力", + "admin.updateAskPassword": "質問パスワードを更新", + "admin.askPasswordPlaceholder": "質問パスワードを入力", + "admin.account": "アカウント設定", + "admin.exportHint": "%s のすべての個人データ(基本情報、受け取った質問と回答を含む)をエクスポートできます。", + "admin.exportJSON": "全データをエクスポート(JSON)", + "admin.exportJSONHint": "質問・回答・追加質問・チャットを含む完全バックアップ。", + "admin.deactivate": "アカウントを停止", + "admin.deactivateHint": "いつでもアカウントを停止できます。停止後はログインできなくなり、質問箱のページや質問にもアクセスできなくなります。新しい質問も受け付けられません。この操作は取り消せません。ご注意ください!", + "admin.socialRequired": "リンクを入力するか、チェックを外してください", + + // 質問管理ページ + "qlist.title": "マイ質問", + "qlist.answered": "回答済み", + "qlist.pending": "回答待ち", + "qlist.private": "非公開", + "qlist.empty": "質問はまだありません。質問箱を共有しましょう~", + "qlist.action": "操作", + "qlist.answerNow": "回答する", + "qlist.sort": "並び替え", + "qlist.status": "状態", + "qlist.type": "種類", + "qlist.latest": "最新", + "qlist.oldest": "最古", + "qlist.all": "すべて", + "qlist.public": "通常の質問", + "qlist.privateQuestion": "非公開の質問", + "qlist.received": "受け取った質問", + "qlist.myChats": "開始したチャット", + "qlist.statsTotal": "質問総数", + "qlist.statsAnswered": "回答済み", + "qlist.statsUnanswered": "未回答", + "qlist.statsPrivate": "非公開質問", + "qlist.statsPinned": "ピン留め", + "qlist.statsChats": "チャット", + "qlist.searchPlaceholder": "質問や回答を検索...", + "qlist.searchBtn": "検索", + "qlist.searchClear": "クリア", + "qlist.questionsTab": "質問", + "qlist.votesTab": "投票", + "qlist.chatsTab": "チャット", + "qlist.receivedChats": "受け取ったチャット", + "qlist.chatEmpty": "まだチャットがありません。質問箱を共有してチャットを始めましょう!", + "qlist.pinnedShort": "ピン", + "qlist.privateShort": "非公開", + "qlist.chatStatsTotal": "チャット総数", + "qlist.chatStatsReceived": "受け取った", + "qlist.chatStatsInitiated": "開始した", + "qlist.chatStatsClosed": "終了", + "qlist.unansweredShort": "未答", + "qlist.readShort": "既読", + "qlist.unreadShort": "未読", + "qitem.markReadShort": "既読に", + "qlist.pinShort": "ピン", + "qlist.unpinShort": "解除", + "qlist.myVotes": "作成した投票", + "qlist.loadMore": "もっと読み込む", + "qlist.newVote": "投票を作成", + "qlist.edit": "編集", + "qlist.untitledVote": "無題の投票", + "qlist.blocked": "ブロック済み", + "qlist.unanswered": "未回答", + + // サイトロゴの接尾辞 + "site.logoSuffix": "の質問箱", + "site.stats": "質問箱の統計", + + // キャプチャモーダル + "captcha.title": "人機認証", + "captcha.hint": "以下の計算問題を解いて、ロボットでないことを証明してください", + "captcha.refresh": "別の問題", + "captcha.submit": "認証して送信", + "captcha.loading": "読み込み中...", + "captcha.loadFailed": "読み込み失敗", + "captcha.loadRetry": "読み込み失敗、再試行してください", + "captcha.inputAnswer": "答えを入力してください", + "captcha.wrongAnswer": "答えが違います。もう一度計算してください", + "captcha.verifyFailed": "認証失敗、再試行してください", + + // 登録ページ補足 + "auth.register.domain.prefix": "カスタムドメイン(あなたの質問箱URLは %s + ", + "auth.register.domain.suffix": " + 下記に入力した内容になります)", + "auth.register.confirm": "パスワード(確認)", + "auth.register.language": "表示言語", + "auth.register.languageDefault": "サイト既定に従う", + "auth.register.success": "登録が完了しました。狼の質問箱へようこそ!", + + // 探索ページ補足 + "explore.recommend": "ランダムおすすめ", + "explore.search": "タグを検索...", + "explore.sortLatest": "新着順", + "explore.sortOldest": "古い順", + "explore.noTags": "タグなし", + "explore.noRecommend": "おすすめユーザーはいません", + "explore.hotTags": "人気タグ", + "explore.hotQuestions": "人気質問", + "explore.noResult": "条件に一致するユーザーはいません。", + "explore.lazy": "このユーザーは何も書いていません~", + "explore.prevPage": "前へ", + "explore.nextPage": "次へ", + "explore.loading": "読み込み中...", + "explore.loadFailed": "読み込み失敗", + + // 質問箱パスワードページ + "password.title": "この質問箱はパスワード保護されています", + "password.desc": "この質問箱はパスワード保護されています。パスワードを入力して内容を表示してください", + "password.input": "アクセスパスワードを入力してください", + "password.enter": "認証して入る", + "password.submit": "確認", + + // 質問が見つかりません + "qitem.notFound": "質問が見つからないか、削除されました", + + // チャットページ + "chat.title": "チャット", + "chat.input": "メッセージを入力...", + "chat.send": "送信", + "chat.delete": "会話を削除", + "chat.block": "相手をブロック", + "chat.unblock": "ブロック解除", + "chat.empty": "メッセージはまだありません。何か書いてみましょう~", + "chat.withAsker": "質問者とのチャット", + "chat.withUser": "%s とのチャット", + "chat.closed": "会話は終了しました", + "chat.closedNoSend": "会話は終了したため、新しいメッセージを送信できません", + "chat.remaining": "残りメッセージ:%d 件(全 %d 件)", + "chat.me": "自分", + "chat.other": "相手", + "chat.userBlocked": "このユーザーはブロックされています", + "chat.addImage": "画像を追加(任意、最大5MB)", + "chat.confirm": "確認", + "chat.confirmBlock": "このユーザーをブロックしますか?ブロック後はメッセージを送信できなくなります。", + "chat.confirmUnblock": "このユーザーのブロックを解除しますか?再度メッセージを送信できるようになります。", + "chat.deleteConfirm": "このチャットを削除しますか?相手はこの会話を見られなくなり、この操作は取り消せません。", + "maintenance.title": "NekoBox メンテナンス中...", + "maintenance.desc": "NekoBox はメンテナンス中のため、一時的にご利用いただけません。また後でお越しください~", + + // 質問の個別シェア(v4) + "qitem.shareCard": "この質問をシェア", + + // 追加質問(v4) + "followup.title": "追加質問", + "followup.content": "追加質問:", + "followup.answerPlaceholder": "この追加質問に回答...", + "followup.answerBtn": "回答する", + "followup.waiting": "回答待ち...", + "followup.askMore": "追加で質問する", + "followup.remaining": "追加質問可能: %d / %d 回", + "followup.contentPlaceholder": "質問を補足...", + "followup.submit": "送信", + "followup.waitingReply": "追記を送信しました。ボックス所有者の返信をお待ちください...", + + // ピン留め(v4) + "qlist.pinned": "ピン留め中", + "qlist.pin": "ピン留め", + "qlist.unpin": "ピン留め解除", + "qlist.readStatus": "既読ステータス", + "qlist.read": "既読", + "qlist.unread": "未読", + "qlist.statsRead": "既読", + "qlist.statsUnread": "未読", + + // 質問送信完了ページ(v4) + "success.title": "質問を送信しました!", + "success.yourQuestion": "あなたの質問:", + "success.emailSent": "この質問のプライベートリンクをメールで送信しました。以下のリンクからいつでも質問の確認、回答の受信、追加質問ができます。", + "success.saveLink": "以下のプライベートリンクを必ず保存してください!メールアドレスを入力しなかったため、このリンク(トークンを含む)が質問の確認・回答の受信・追加質問のための唯一の証拠です。失くすと復元できません。", + "success.privateLink": "あなたのプライベートリンク(クリックしてコピー)", + "success.copy": "コピー", + "success.copied": "コピーしました ✓", + "success.copyFailed": "コピーに失敗", + "success.token": "トークン: %s(質問者はこのトークンでプライベートリンクにアクセス)", + "success.viewQuestion": "質問を確認する", + "success.backToBox": "%sの質問箱に戻る", + "success.pageTitle": "質問送信完了 - %s", + + // アカウント停止ページ + "deactivate.title": "アカウント停止", + "deactivate.desc": "停止後、あなたの質問箱にはアクセスできなくなり、すべてのデータが削除されます。この操作は取り消せません!", + "deactivate.confirm": "アカウントを停止することに同意します", + "deactivate.submit": "アカウントを停止", + + // 匿名投票 + "nav.votes": "投票", + + "common.back": "戻る", + + "vote.listTitle": "投票管理", + "vote.newTitle": "投票を作成", + "vote.editTitle": "投票を編集", + "vote.resultsTitle": "投票結果", + "vote.statsTotal": "投票総数", + "vote.statsPublished": "進行中", + "vote.createNew": "投票を作成", + "vote.typeSingle": "単一選択", + "vote.typeMultiple": "複数選択", + "vote.typeRating": "評価", + "vote.typeRank": "順位付け", + "vote.typeForm": "フォーム", + "vote.statusNotStarted": "未開始", + "vote.statusDraft": "下書き", + "vote.statusPublished": "進行中", + "vote.statusEnded": "終了", + "vote.statusArchived": "アーカイブ", + "vote.participants": "参加者", + "vote.remainLabel": "残り", + "vote.perpetual": "期限なし", + "vote.durationDay": "日", + "vote.durationHour": "時間", + "vote.durationMinute": "分", + "vote.createdAt": "作成日時", + "vote.edit": "編集", + "vote.results": "結果", + "vote.preview": "プレビュー", + "vote.page.mustComplete": "入力してください", + "vote.page.rankHintRequired": "順位 1-N(必須)", + "vote.page.rankHintOptional": "順位 1-N(任意、一部のみ可)", + "vote.page.previewHint": "プレビューモード:公開前のサンプルです。送信は無効です", + "vote.page.previewSubmitHint": "プレビューモード。公開後に送信できます", + "vote.publish": "公開", + "vote.close": "終了", + "vote.share": "リンクをコピー", + "vote.copied": "コピーしました", + "vote.shareURL": "投票の共有リンク", + "vote.confirmPublish": "この投票を公開しますか?公開後、共有リンクが生成されます。", + "vote.confirmClose": "この投票を終了しますか?終了後、参加者は投票できなくなります。", + "vote.confirmDelete": "この投票を削除しますか?投票データもすべて削除され、元に戻せません!", + "vote.manageEntry": "投票を管理", + + "vote.manageTitle": "投票管理", + "vote.manageDesc": "匿名投票の作成と管理", "vote.empty": "投票はまだありません。右上の\"投票を作成\"から始めましょう。", + "vote.formLockedHint": "この投票は公開中です。基本情報のみ編集可能です(収集済みデータを守るため、タイプと選択肢はロックされています)", + "vote.formBasic": "基本設定", + "vote.formTitle": "投票タイトル", + "vote.formTitlePlaceholder": "例:今日の昼ごはんは?", + "vote.formDescription": "説明", + "vote.formDescriptionPlaceholder": "補足説明(任意)", + "vote.formType": "投票タイプ", + "vote.formVisibility": "表示方法", + "vote.formVisibilityPublic": "公開(探索ページ + 質問箱ページ)", + "vote.formVisibilityLinkOnly": "リンクのみ", + "vote.formVoterScope": "投票範囲", + "vote.formVoterScopeAnyone": "誰でも(匿名含む)", + "vote.formVoterScopeRegistered": "登録ユーザーのみ", + "vote.formShowResult": "結果の表示タイミング", + "vote.formShowResultAfterVote": "投票後すぐに表示", + "vote.formShowResultAfterEnd": "終了後に表示", + "vote.formShowResultOwnerOnly": "本人のみ", + "vote.formStartAt": "開始時間(空欄=すぐ開始)", + "vote.formEndAt": "終了時間(空欄=制限なし)", + "vote.formMaxChoices": "最大選択数", + "vote.formMaxVotesPerFingerprint": "投票ごとに1台の端末につき1回まで。同じブラウザからの再送信は拒否されます。", + "vote.formMaxVotesPerAccount": "投票ごとに1つの登録アカウントにつき1回まで。同じアカウントからの再送信は拒否されます。", + "vote.formAllowCustom": "参加者がカスタム選択肢を追加できる", + "vote.formRequireCaptcha": "匿名投票にキャプチャを要求", + "vote.formOptions": "投票の選択肢", + "vote.formRatingHint": "評価投票は選択肢不要(1-10点)", + "vote.addOption": "選択肢を追加", + "vote.optionPlaceholder": "選択肢の内容", + "vote.formFields": "フォーム項目", + "vote.addField": "項目を追加", + "vote.field": "項目", + "vote.formFieldType": "項目タイプ", + "vote.fieldTypeText": "一行テキスト", + "vote.fieldTypeTextarea": "複数行テキスト", + "vote.fieldTypeSelect": "ドロップダウン選択", + "vote.fieldTypeRadio": "単一選択", + "vote.fieldTypeCheckbox": "複数選択", + "vote.fieldTypeNumber": "数値", + "vote.fieldTypeRank": "順位", + "vote.page.selectPlaceholder": "選択してください", + "vote.page.avgNumber": "平均", + "vote.page.fieldFilled": "回答数", + "vote.fieldTypeRating": "評価", + "vote.formFieldLabel": "項目ラベル", + "vote.formFieldRequired": "必須", + "vote.formFieldMaxLength": "文字数上限(0=制限なし)", + "vote.formFieldOptions": "選択肢", + "vote.formFieldOptionsHint": "下の「選択肢を追加」で一つずつ追加してください(カンマ不要)", + "vote.fieldAllowCustom": "参加者がカスタム選択肢を追加できる", + "vote.formFieldOptionsPlaceholder": "例:良い,普通,悪い", + "vote.createDraft": "下書きを保存", + "vote.builderHintOptions": "選択肢は最低 2 つ必要です", + "vote.builderHintFields": "フィールドを最低 1 つ追加してください", + "vote.builderHintFieldOptions": "選択・順位題には選択肢が必要です(順位は最低 2 つ)", + "vote.resultsAnswered": "回答数", + "vote.page.rankedTimes": "順位付け数", + "vote.resultsTotal": "総参加人数", + "vote.resultsSubmissions": "フォームの回答", + "vote.resultsViewTexts": "テキスト回答を表示", + "vote.resultsToggleHint": "クリックでテキスト回答の表示・非表示を切り替え", + "vote.resultsOptions": "投票結果", + "vote.resultsVotes": "票", + "vote.export": "CSV エクスポート", + "vote.resultsEmpty": "まだ参加者がいません。リンクを共有しましょう!", + + // 投票参加ページ + "vote.inlineTitle": "投票", + "vote.page.by": "の投票", + "vote.page.goVote": "投票する", + "vote.page.notStarted": "未開始", + "vote.page.notStartedHint": "この投票はまだ始まっていません。", + "vote.page.ended": "終了", + "vote.page.endedHint": "この投票は終了しました。", + "vote.page.active": "進行中", + "vote.page.participated": "参加済み", + "vote.page.loginRequired": "この投票は登録ユーザーのみ参加できます。ログインしてください。", + "vote.page.anonymousHint": "匿名での参加が可能で、あなたの身元は記録されません(同一端末で最大1回)。", + "vote.page.submit": "投票する", + "vote.page.alreadyVoted": "この投票にはすでに参加済みです。ありがとうございます!", + "vote.page.resultsTitle": "投票結果", + "vote.page.totalVotes": "総参加", + "vote.page.avgRating": "平均点", + "vote.page.avgRank": "平均順位", + "vote.page.optionColumn": "選択肢", + "vote.page.ratingLabel": "評価", + "vote.page.ratingUnit": "点", + "vote.page.rankHint": "各選択肢に 1-N の順位を入力してください(小さいほど上位、重複不可)", + "vote.page.rankPlaceholder": "順位", + "vote.page.multipleHint": "複数選択可", + "vote.page.customOption": "カスタム選択肢(任意)", + "vote.page.customPlaceholder": "あなたの選択肢を入力", + "vote.page.customOther": "その他", + "vote.page.customFieldPlaceholder": "カスタム選択肢を入力…", + "vote.page.customStats": "カスタム選択肢", + "vote.page.formCount": "回答受付数", + "vote.page.ownerManage": "この投票を管理(結果は本人のみ閲覧可能)", + + // 投票ごとの定量収集 + "vote.formQuotaLimit": "収集上限(件)", + "vote.formQuotaHint": "0 は無制限。指定件数に達すると自動的に投票を終了します。", + "vote.flash.notFound": "この投票は存在しないか、既に無効です", + "vote.flash.notPublished": "この投票はまだ公開されていません", + "vote.flash.archived": "この投票はアーカイブ済みのため参加できません", + "vote.flash.ended": "この投票は終了しました", + "vote.flash.notStarted": "この投票はまだ開始していません", + "vote.flash.success": "投票が完了しました。ご参加ありがとうございます!", + "vote.err.noChoice": "少なくとも 1 つの選択肢を選んでください", + "vote.err.tooManyChoices": "選択できるのは最大 %d 個までです", + "vote.err.pickOne": "選択肢を 1 つ選んでください", + "vote.err.invalidOption": "無効な選択肢です", + "vote.err.optionDuplicate": "選択肢は重複できません", + "vote.err.ratingRequired": "1〜10 点の評価を入力してください", + "vote.err.rankRequired": "すべての選択肢に 1〜%d の順位を入力してください", + "vote.err.rankDuplicate": "順位が重複しています", + "vote.err.fieldRequired": "「%s」を入力してください", + "vote.err.fieldCustomRequired": "「%s」の自由記入欄を入力してください", + "vote.err.fieldCustomTooLong": "「%s」の自由記入は %d 字以内にしてください", + "vote.err.fieldInvalidOption": "「%s」の選択肢が無効です", + "vote.err.fieldConfigError": "「%s」の選択肢の設定に誤りがあります", + "vote.err.fieldRankIncomplete": "「%s」の順位をすべて入力してください", + "vote.err.fieldRankRange": "「%s」の順位は 1〜%d の数字で入力してください", + "vote.err.fieldRankDuplicate": "「%s」の順位が重複しています", + "vote.err.fieldTooLong": "「%s」が文字数上限(最大 %d 字)を超えています", + "vote.err.fieldNotNumber": "「%s」は数値で入力してください", + "vote.err.fieldRating": "「%s」は 1〜10 点で評価してください", + "vote.err.unknownType": "不明な投票タイプです", + "vote.err.customTooLong": "自由記入オプションは %d 字以内にしてください", + "vote.err.blockWords": "投稿内容に投票作成者が設定したブロックワードが含まれているため、送信できませんでした", + "vote.err.serialize": "送信内容の保存に失敗しました", + "captcha.error": "認証コードが正しくありません", + "captcha.errEmpty": "認証コードを入力してください", + "captcha.errFormat": "認証コードの形式が正しくありません。再読み込みしてお試しください", + "captcha.errAnswerFormat": "認証コードの回答形式が正しくありません", + "captcha.errExpired": "認証コードの有効期限が切れました。再読み込みしてお試しください", + "captcha.errService": "認証コードサービスでエラーが発生しました。後ほどお試しください", + "captcha.errAnswerWrong": "認証コードの回答が正しくありません", + "censor.unavailable": "コンテンツ審査サービスが一時的に利用できません。後ほどお試しください", + + // 機能管理:質問 / チャット / 投票 の ON・OFF、期間指定、定量収集 + "admin.tabAccount": "ユーザー設定", + "admin.featuresHint": "「質問 / チャット / 投票」パネルで各機能の ON/OFF、公開期間、収集上限を管理します。上限に達すると対象機能は自動的に閉じられます。", + "admin.featuresEntry": "設定", + "admin.featureHint.question": "OFF にすると新しい質問を投稿できません。上限に達すると自動的に受付を停止します(非公開質問を含む)。", + "admin.featureHint.chat": "OFF にすると新しいチャットを開始できません。既存の会話には影響しません。", + "admin.featureHint.vote": "OFF にすると質問箱ページに投票が表示されず、回答もできなくなります。投票ごとの上限は編集ページで設定できます。", + "admin.featureEnabled": "この機能を有効にする", + "admin.featureOpenAt": "公開開始", + "admin.featureCloseAt": "公開終了", + "admin.featureTimeHint": "空欄は制限なし。開始前と終了後はその機能を利用できません。", + "admin.featureSchedule": "定期公開(毎週)", + "admin.featureScheduleStart": "毎日の開始", + "admin.featureScheduleEnd": "毎日の終了", + "admin.featureScheduleHint": "毎週の公開曜日と毎日の時間帯を設定すると、毎週繰り返し公開されます。すべて空欄で無効。曜日のみ(時間なし)は終日公開、時間のみ(曜日なし)は毎日その時間帯に公開。", + "admin.featureMode": "収集モード", + "admin.featureModeAlways": "常時開放", + "admin.featureModeWindow": "期間限定", + "admin.featureModeRecurring": "曜日スケジュール", + "admin.featureModeHint": "常時開放:手動でオフにするまで開放し続けます。期間限定:一回限りの開始/終了時刻で開放します。曜日スケジュール:毎週の開放日と時間帯を繰り返し適用します。モードは保存時に排他となり、未選択モードの設定はクリアされます。", + "admin.featureQuotaLimit": "収集上限(件)", + "admin.featureQuotaHint": "0 は無制限。上限に達すると自動的に閉じられます。カウントをリセットすると次の回を開始できます。", + "admin.featureQuotaCount": "収集済み", + "admin.featureQuotaUnlimited": "無制限", + "admin.featureQuotaResetAt": "最終リセット:", + "admin.featureResetQuota": "カウントをリセット", + "admin.featureSave": "この機能を保存", + + // 機能管理:状態とメッセージ + "feature.name.question": "質問", + "feature.name.chat": "チャット", + "feature.name.vote": "投票", + "feature.statusOpen": "受付中", + "feature.status.disabled": "停止中", + "feature.status.not_started": "未開始", + "feature.status.ended": "終了", + "feature.status.quota_reached": "上限到達", + "feature.saved": "機能設定を保存しました", + "feature.errTime": "%s の日時形式が正しくありません。日時選択ツールを使用してください", + "feature.errTimeRange": "%s の公開終了時刻は公開開始時刻より後にしてください", + "feature.errQuota": "%s の収集上限は 0〜1000000 の整数で入力してください", + "feature.errInvalid": "不明な機能です", + "feature.quotaReset": "%s の収集カウントをリセットしました", + "feature.errScheduleHalf": "%s の定期公開の開始時間と終了時間は両方入力してください", + "feature.errScheduleTime": "%s の定期公開の時刻形式が正しくありません。時刻選択ツールを使用してください", + "feature.errScheduleRange": "%s の定期公開の終了時刻は開始時刻より後にしてください", + + // 機能が無効なときに訪問者へ表示するメッセージ + "feature.disabled.question": "この質問箱の管理者は質問の受付を停止しています", + "feature.disabled.chat": "この質問箱ではチャットを受け付けていません", + "feature.disabled.vote": "この質問箱では投票を受け付けていません", + "feature.not_started.question": "質問の受付はまだ開始していません", + "feature.not_started.chat": "チャットの受付はまだ開始していません", + "feature.not_started.vote": "投票の受付はまだ開始していません", + "feature.ended.question": "質問の受付は終了しました", + "feature.ended.chat": "チャットの受付は終了しました", + "feature.ended.vote": "投票の受付は終了しました", + "feature.quota_reached.question": "質問の収集上限に達しました", + "feature.quota_reached.chat": "チャットの収集上限に達しました", + "feature.quota_reached.vote": "投票の収集上限に達しました", + + // 認証:訪問者に表示されるメッセージ(P0) + "auth.errBadCredential": "メールアドレスまたはパスワードが正しくありません", + "auth.errUserNotFound": "ユーザーが存在しません", + "auth.errEmailFrequent": "メールの送信頻度が高すぎます。しばらくしてからお試しください", + "auth.errEmailFailed": "メールの送信に失敗しました。しばらくしてからお試しください", + "auth.errCodeExpired": "認証コードの有効期限が切れました", + "auth.errPasswordChanged": "パスワードを変更しました", + "auth.errLoginRequired": "ログインしてください", + "auth.errDuplicateEmail": "このメールアドレスは既に登録されています", + "auth.errDuplicateDomain": "このカスタムドメインは既に使用されています", + + // 質問箱ページ:訪問者に表示(P0) + "question.errWrongPassword": "パスワードが正しくありません", + "question.errAskPasswordWrong": "質問用パスワードが正しくありません", + "question.errLoginRequired": "質問箱の所有者は登録ユーザーのみ質問できるように設定しています。先にログインしてください。", + "question.errSelfChat": "自分自身とのチャットは開始できません", + "question.errBlockedChat": "相手にブロックされているため、チャットを開始できません", + "question.errChatDailyLimit": "本日の送信上限(%d件)に達しました。明日お試しください", + "question.errDuplicateSubmit": "重複送信が検出されました。しばらくしてからお試しください", + "question.errImageTooLarge": "画像ファイルのサイズは 5Mb 以下である必要があります", + "question.errUploadImageFailed": "画像のアップロードに失敗しました", + "question.errBlockWords": "質問に所有者が設定したブロックワードが含まれているため、送信できませんでした", + "question.errAnsweredLocked": "回答済みの質問は未読にできません", + "question.flash.chatSent": "チャットリクエストを送信しました!以下のリンクから会話を確認できます:%s", + "question.flash.answered": "回答を公開しました!", + "question.flash.operated": "操作が完了しました", + "question.flash.markedRead": "既読にしました", + "question.flash.markedUnread": "未読にしました", + + // 追加質問:訪問者/所有者に表示(P0) + "followup.errNoPermission": "権限がありません", + "followup.errNotAnswered": "この質問にはまだ回答がありません。追加質問はできません", + "followup.errLimit": "各質問の追加質問は最大 %d 回までで、上限に達しました", + "followup.errWaitReply": "前の追加質問への返信を待ってから続けてください", + "followup.errNotFound": "追加質問が存在しません", + "followup.flash.sent": "追加質問を送信しました!", + "followup.flash.answered": "回答を投稿しました!", + + // 管理設定:所有者に表示(P1) + "admin.flash.profileUpdated": "プロフィールを更新しました", + "admin.flash.chatUpdated": "チャット設定を更新しました", + "admin.flash.pagePwdOff": "ページパスワード認証を無効にしました", + "admin.flash.pagePwdUpdated": "ページアクセスパスワードを更新しました", + "admin.flash.askPwdOff": "質問パスワードを無効にしました", + "admin.flash.askPwdUpdated": "質問パスワードを更新しました", + "admin.flash.tagsTooMany": "タグは最大 5 個までです", + "admin.flash.tagsUpdated": "タグを更新しました", + "admin.flash.tagTooLong": "各タグは 5 文字以内である必要があります:%s", + "admin.flash.blockWordsTooMany": "ブロックワードは最大 10 個までです", + "admin.flash.blockWordTooLong": "ブロックワードの長さは 10 文字以内である必要があります:%s", + "admin.flash.harassmentUpdated": "迷惑行為対策を更新しました", + "admin.flash.blockWordsUpdated": "ブロックワードを更新しました", + "admin.flash.deactivated": "アカウントを停止しました。狼の質問箱をご利用いただきありがとうございます。またのお越しをお待ちしています 👋🏻", + "admin.export.errUser": "エクスポート失敗:ユーザー情報の取得に失敗しました", + "admin.export.errQuestion": "エクスポート失敗:質問情報の取得に失敗しました", + + // 投票管理:所有者に表示(P1) + "vote.err.invalidID": "無効な投票 ID", + "vote.err.notExist": "投票が存在しません", + "vote.err.noPermission": "この投票を操作する権限がありません", + "vote.err.type": "不明な投票タイプです", + "vote.err.titleRequired": "投票のタイトルを入力してください", + "vote.err.titleTooLong": "投票のタイトルは 100 文字以内である必要があります", + "vote.err.visibility": "不明な表示設定です", + "vote.err.voterScope": "不明な投票範囲設定です", + "vote.err.showResult": "不明な結果表示設定です", + "vote.err.timeRange": "終了時刻は開始時刻より後にしてください", + "vote.err.quota": "収集上限は 0〜1000000 の整数で入力してください", + "vote.err.optionsTooFew": "選択肢を最低 2 つ追加してください", + "vote.err.optionsFormat": "選択肢データの形式が正しくありません", + "vote.err.optionTooLong": "1 つの選択肢は %d 文字以内である必要があります", + "vote.err.maxChoicesExceed": "最大選択数は選択肢の総数を超えられません", + "vote.err.fieldsTooFew": "フォーム項目を最低 1 つ追加してください", + "vote.err.fieldsFormat": "フォーム項目データの形式が正しくありません", + "vote.err.fieldsTooMany": "フォーム項目は最大 50 個までです", + "vote.err.fieldType": "不明なフォーム項目タイプです", + "vote.err.fieldLabelMissing": "%d 番目の項目にラベルがありません", + "vote.err.fieldLabelTooLong": "%d 番目の項目のラベルは 100 文字以内である必要があります", + "vote.err.fieldLabelDuplicate": "項目ラベル「%s」が重複しています。別のラベルを使用してください", + "vote.err.fieldMaxLength": "%d 番目の項目の文字数上限は 0〜2000 の間である必要があります", + "vote.err.fieldReservedOption": "%d 番目の項目(%s)の選択肢に予約値が含まれています。変更してください", + "vote.err.fieldOptionsTooFew": "%d 番目の項目(%s)は選択肢を最低 1 つ入力してください", + "vote.err.fieldRankTooFew": "%d 番目の項目(%s)の順位付けには最低 2 つの選択肢が必要です", + "vote.err.fieldSerialize": "項目の選択肢のシリアライズに失敗しました", + "vote.err.editClosed": "終了またはアーカイブされた投票は編集できません", + "vote.err.publishDraftOnly": "草稿状態の投票のみ公開できます", + "vote.err.closePublishedOnly": "進行中の投票のみ終了できます", + "vote.err.publishTitleRequired": "公開前に投票のタイトルを入力してください", + "vote.err.publishFormFieldsRequired": "フォーム型投票には最低 1 つの項目が必要です", + "vote.err.publishOptionsRequired": "選択型投票には最低 2 つの選択肢が必要です", + "vote.err.optionUpdateFailed": "選択肢の更新に失敗しました。再試行してください", + "vote.err.fieldUpdateFailed": "フォーム項目の更新に失敗しました。再試行してください", + "vote.flash.published": "投票を公開しました!共有リンク:%s", + "vote.flash.updated": "投票情報を更新しました(進行中の投票はタイプと選択肢を変更できません)", + "vote.flash.draftSaved": "下書きに保存しました", + "vote.flash.closed": "投票を終了しました", + "vote.flash.deleted": "投票を削除しました", + "vote.err.timeFormat": "日時の形式が正しくありません。日時選択器を使用してください", + "vote.err.maxChoicesLimit": "選択可能数は20を超えられません", + "vote.err.descriptionTooLong": "投票の説明は5000文字を超えられません", + "profile.err.avatarTooLarge": "アイコンファイルが大きすぎます。最大2MB", + "profile.err.backgroundTooLarge": "背景画像が大きすぎます。最大2MB", + "profile.err.newPasswordTooShort": "新しいパスワードは8文字以上である必要があります", + "profile.err.badOldPassword": "古いパスワードが間違っています", + "admin.export.errCreateExcel": "エクスポート失敗:Excelファイルの作成に失敗しました", + "admin.export.errWriteExcel": "エクスポート失敗:Excelファイルの書き込みに失敗しました", + + // プロフィール設定ページ UI リニューアル:カード区切り/アイコン・背景の切り取り/パスワード変更後の強制ログアウト + "profile.card.basic": "基本情報", + "profile.card.avatarBg": "アイコンと背景", + "profile.card.qr": "QRコードのスタイル", + "profile.card.password": "パスワード変更", + "profile.avatarCropHint": "切り取り枠は 1:1(正方形)に固定されています", + "profile.backgroundCropHint": "切り取り枠は 16:9 に固定されています", + "profile.cropTitle": "画像を切り取る", + "profile.cropConfirm": "切り取りを確定", + "profile.err.avatarRatio": "アイコン画像は 1:1 の正方形である必要があります。切り取ってから再アップロードしてください", + "profile.err.backgroundRatio": "背景画像は 16:9 の縦横比である必要があります。切り取ってから再アップロードしてください", + "profile.flash.passwordChanged": "パスワードを変更しました。ログアウトしましたので、新しいパスワードで再度ログインしてください", + "profile.pwdNote": "保存後、現在のセッションはすぐに無効になり、新しいパスワードで再ログインする必要があります", + "profile.pickAvatar": "アイコンを変更", + "profile.pickBackground": "背景を変更", + "profile.saveBasic": "基本情報を保存", + "profile.saveMedia": "アイコンと背景を保存", + "profile.savePassword": "パスワードを更新", + "profile.saveQR": "QRコードのスタイルを保存", + "profile.saveSocial": "SNSリンクを保存", + "profile.err.cropLibUnavailable": "画像切り取り機能の読み込みに失敗しました。ページを更新してもう一度お試しください", + + // 認証コード JSON インターフェース:フロントエンドが消費(P2) + "captcha.json.badRequest": "リクエスト形式が正しくありません", + "captcha.json.idRequired": "認証コード ID を入力してください", + "captcha.json.genFailed": "認証コードの生成に失敗しました", + "chat.errDeletedByOwner": "このプライベート会話は相手によって削除されました。", + "chat.errBlockedView": "あなたは相手にブロックされ、このチャットを表示できません", + "chat.errEmpty": "メッセージを入力してください", + "chat.errTooLong": "メッセージが長すぎます。%d文字以内でお願いします", + "chat.errConvDeletedSend": "この会話は削除されたため、メッセージを送信できません", + "chat.errBlockedSend": "あなたは相手にブロックされ、メッセージを送信できません", + "chat.errBlockWords": "メッセージにボックス所有者が設定したブロックワードが含まれているため、送信できませんでした", + "chat.errDailyLimit": "本日の送信上限(%d件)に達しました。明日再度お試しください", + "chat.errLimitReached": "会話が上限に達したため、新しいメッセージを送信できません", + "chat.errChatClosed": "箱の所有者がプライベートチャットを無効にしたため、メッセージを送信できません", + "chat.errImageTooLarge": "画像サイズは%dMBを超えることはできません", + "chat.errUploadFailed": "画像のアップロードに失敗しました。後でもう一度お試しください", + "chat.errNoPermission": "この操作を実行する権限がありません", + "chat.flash.sent": "メッセージを送信しました", + "chat.flash.deleted": "プライベート会話を削除しました", + "chat.flash.operated": "操作が完了しました", + "image.errTooLarge": "画像が大きすぎます。最大%d×%dピクセルまで対応しています。圧縮して再アップロードしてください", + "internal.errFlash": "サーバー内部エラーが発生しました。後でもう一度お試しください。", + "internal.errServer": "サーバー内部エラー", + "home.errStats": "統計情報の取得に失敗しました", + "pixel.errPath": "不正なリクエストパス", + "proxy.errNotFound": "ページが見つかりません", + "proxy.errInternal": "サービスゲートウェイ内部エラー", + "explore.errRandomUser": "ランダムユーザーの取得に失敗しました", + // 表单校验 + "form.answer.content": "回答内容を入力してください", + "form.answer.contentTooLong": "回答内容は%d文字以内にしてください", + "form.email.required": "有効なメールアドレスを入力してください", + "form.followup.answer": "フォローアップの回答を入力してください", + "form.followup.answerTooLong": "フォローアップの回答は%d文字以内にしてください", + "form.followup.content": "フォローアップ内容を入力してください", + "form.followup.contentTooLong": "フォローアップ内容は%d文字以内にしてください", + "form.login.password": "パスワードを入力してください", + "form.profile.backgroundimagealpha": "QRコードの背景の不透明度を入力してください", + "form.profile.colorHex": "7文字の16進数カラーコード(#を含む)を入力してください", + "form.profile.dotscale": "QRコードの点の大きさを入力してください", + "form.profile.intro": "自己紹介は必須で、100文字以内である必要があります", + "form.profile.linkMax": "プロフィールリンクは30文字以内である必要があります", + "form.profile.name": "ニックネームは必須で、20文字以内である必要があります", + "form.profile.newPassword": "新しいパスワードは30文字以内である必要があります", + "form.profile.passwordMax": "パスワードは30文字以内である必要があります", + "form.question.content": "質問内容を入力してください", + "form.question.contentTooLong": "質問内容は%d文字以内にしてください", + "form.question.receiveReplyEmail": "返信を受け取るための有効なメールアドレスを入力してください", + "form.recaptcha": "CAPTCHA認証を完了してください", + "form.recover.newPassword": "8〜30文字の新しいパスワードを設定してください", + "form.recover.repeatPassword": "入力した2つの新しいパスワードが一致しません", + "form.register.domain": "カスタムドメインは半角英数字とアンダースコアのみ使用でき、3〜20文字である必要があります", + "form.register.email": "有効なメールアドレスを入力してください(100文字以内)", + "form.register.name": "ニックネームは必須で、20文字以内である必要があります", + "form.register.password": "8〜30文字のパスワードを設定してください", + "form.register.recaptcha": "CAPTCHAを読み込めません。ページを再読み込みするか、ネットワークを変更してお試しください", + "form.register.repeatPassword": "入力した2つのパスワードが一致しません", +} diff --git a/.workbuddy/backup/remove-vercount-20260906/dict_zh_cn.go b/.workbuddy/backup/remove-vercount-20260906/dict_zh_cn.go new file mode 100644 index 0000000..41e82d0 --- /dev/null +++ b/.workbuddy/backup/remove-vercount-20260906/dict_zh_cn.go @@ -0,0 +1,842 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package i18n + +// zhCNDict 简体中文文案。 +var zhCNDict = map[string]string{ + // 导航 + "nav.explore": "探索", + "nav.mine": "我的", + "nav.register": "注册", + "nav.login": "登录", + "nav.ask": "提问", + "nav.settings": "设置", + "nav.lang": "语言", + + // 通用 + "common.login": "登录", + "common.forgot": "忘记密码", + "common.submit": "提交", + "common.cancel": "取消", + "common.save": "保存", + "common.close": "关闭", + "common.delete": "删除", + "common.moveUp": "上移", + "common.moveDown": "下移", + "common.share": "分享", + "common.verifying": "验证中...", + "common.submitting": "提交中...", + "common.uploading": "上传中...", + "common.lang": "语言", + "common.menu": "菜单", + + "common.pleaseWait": "请稍候...", + "common.backHome": "返回首页", + "common.theme": "切换深色/浅色模式", + + // 站点 + "site.title": "狼的提问箱 | 匿名提问箱", + "site.description": "狼的提问箱——一个无需注册、可匿名提问的匿名提问箱,安全地倾诉与回应。", + "site.keywords": "匿名提问箱,提问箱,匿名提问,狼的提问箱,匿名问答,匿名提问网站", + "site.footer.visitor": "您是本站第 %s 位访客", + "site.footer.pageview": "本页面已被访问 %s 次", + "site.footer.runtime": "提问箱已成功存活", + "site.footer.admin": "找站长", + "site.footer.notice": "公告板", + "site.footer.chat": "聊天室", + "site.footer.drive": "盘", + "site.footer.status": "监控板", + "site.footer.nav": "导航页", + "site.maintenance": "本站正在维护中,请稍后再来~", + + // 认证 + "auth.login.title": "用户登录", + "auth.login.email": "电子邮箱", + "auth.login.password": "密码", + "auth.login.submit": "登录", + "auth.login.forgot": "忘记密码", + "auth.register.title": "用户注册", + "auth.register.name": "昵称", + "auth.register.email": "电子邮箱", + "auth.register.password": "密码", + "auth.register.submit": "注册", + "auth.forgot.title": "忘记密码", + "auth.forgot.email": "电子邮箱", + "auth.forgot.submit": "发送重置邮件", + "auth.forgot.submitBtn": "找回密码", + "auth.forgot.sent": "邮件已发送至 %s,请查收。", + "auth.recover.title": "重置密码", + "auth.recover.greeting": "%s,您正在重置您的密码:", + "auth.recover.password": "新密码", + "auth.recover.confirm": "确认密码", + "auth.recover.submit": "重置密码", + + // 探索页 + "explore.title": "探索用户标签", + "explore.notice": "此处展示已开启“在首页展示我的标签”的用户。该功能默认关闭,若希望自己的提问箱在这里被发现,请前往 个人设置 手动开启。", + "explore.shuffle": "换一批", + "explore.empty": "暂时没有发现可展示的用户,快去开启吧~", + "explore.hotVotes": "热门投票", + "explore.questionsTab": "提问", + "explore.votesTab": "投票", + "explore.votesTitle": "公开投票", + "explore.votesDesc": "浏览正在进行的公开投票,选择你感兴趣的主题参与。", + "explore.randomVote": "随机推荐", + "explore.allVotes": "全部投票", + "explore.noVotes": "暂时没有可参与的公开投票。", + + // 提问页 + "ask.scan": "扫码向@%s提问", + "ask.anonymous": "谁都可以以匿名的形式提问", + "ask.registerOnly": "仅允许注册用户向TA提问", + "ask.nextOpenAt": "下次开放时间:%s", + "ask.lastCloseAt": "上次关闭时间:%s", + "weekday.0": "周日", + "weekday.1": "周一", + "weekday.2": "周二", + "weekday.3": "周三", + "weekday.4": "周四", + "weekday.5": "周五", + "weekday.6": "周六", + "ask.pinned": "已置顶", + "ask.share": "分享提问箱", + "ask.placeholder": "在此处撰写你的问题...", + "ask.chatPlaceholder": "在此处撰写你的私聊消息...", + "ask.addImage": "添加图片", + "ask.private": "回复后不公开", + "ask.notify": "接收通知", + "ask.emailPlaceholder": "请输入你的邮箱地址", + "ask.submit": "发送提问", + "ask.chat": "发起私聊", + "ask.chatDisabled": "该提问箱未开启私聊", + "ask.chatLimit": "消息上限:%d条", + "ask.history": "@%s 以前回答过的问题", + "ask.loginRequired": "需要登录", + "ask.loginRequiredChat": "发起私聊需要登录账号", + "ask.goLogin": "去登录", + "ask.needPassword": "此提问箱需要密码", + "ask.needLogin": "提问箱的主人设置了仅注册用户才能提问,你需要先登录才能向他提问。", + "ask.pleaseEmail": "请填写接收通知的邮箱地址", + "ask.generating": "正在生成分享图…", + "ask.genFailed": "生成分享图失败,请稍后重试", + "ask.networkError": "网络错误", + "ask.shareFilename": "share.png", + + // 问题条目 + "qitem.answer": "回答", + "qitem.delete": "删除", + "qitem.private": "设为私密", + "qitem.public": "设为公开", + "qitem.asked": "提问", + "qitem.pending": "等待回答", + "qitem.answeredBy": "@%s 于 %s 的回答", + "qitem.danger": "危险!", + "qitem.deleteConfirm": "你确定要删除这个提问吗?该操作不可恢复,请谨慎操作。", + "qitem.deleteConfirmBtn": "确认删除", + "qitem.backToBox": "返回%s的提问箱", + "qitem.answerTitle": "回答问题", + "qitem.answerPlaceholder": "在此处撰写你的回答...", + "qitem.emailNotifyHint": "提问人留下了自己的电子邮箱,在你第一次回复该问题后,提问人将会收到一封邮件通知。", + "qitem.submitAnswer": "回答", + "qitem.updateAnswer": "更新回答", + "qitem.askMore": "再问点别的问题?", + "qitem.markRead": "标记为已读", + "qitem.markUnread": "标记为未读", + "qitem.readLocked": "已回答,已锁定为已读", + + // 个人设置页 + "admin.profile": "个人信息", + "admin.lang": "界面语言", + "admin.langHint": "选择访客访问你的提问箱时显示的语言(后台页面跟随此设置)", + "admin.email": "电子邮箱", + "admin.name": "昵称", + "admin.nameColor": "昵称颜色", + "admin.oldPassword": "旧密码", + "admin.newPassword": "新密码", + "admin.notify": "新提问通知", + "admin.personalize": "个性化设置", + "admin.intro": "提问箱介绍", + "admin.introColor": "提问箱介绍颜色", + "admin.qrBgColor": "二维码背景色(亮色部分)", + "admin.qrPdColor": "二维码探测图形颜色(边角方形)", + "admin.qrFgColor": "二维码前景色", + "admin.qrDotSize": "二维码点大小 (←小 大→)", + "admin.qrBgAlpha": "二维码背景透明度 (←不透明 很透明→)", + "admin.avatar": "个人头像", + "admin.background": "提问箱背景", + "admin.qrBackground": "二维码背景图", + "admin.social": "社交信息设置", + "admin.harassment": "防骚扰设置", + "admin.askLimit": "提问限制", + "admin.blockWords": "屏蔽词设置(回车或逗号分隔,最多支持 10 个屏蔽词,每个屏蔽词最大长度为 10)", + "admin.chat": "私聊设置", + "admin.chatMaxMessages": "私聊消息条数上限", + "admin.chatDailyLimit": "单用户每日私信条数上限", + "admin.tags": "标签设置", + "admin.tagsHint": "标签(最多5个,每个最多5字,回车或逗号分隔)", + "admin.tagsPlaceholder": "例如:动漫,音乐,游戏", + "admin.tagInputHint": "输入后按回车或逗号添加", + "admin.tagInputDuplicate": "已存在,已忽略", + "admin.pagePassword": "页面访问密码", + "admin.pagePasswordHint": "设置访问密码(留空则关闭)", + "admin.askPassword": "提问密码", + "admin.askPasswordHint": "设置提问密码(留空则关闭)", + "admin.saveProfile": "保存修改", + "admin.updated": "更新个人信息成功", + "admin.logout": "退出登录", + "admin.export": "导出数据", + + // 后台设置(补充) + "admin.oldPasswordHint": "修改密码使用,留空则不修改", + "admin.newPasswordHint": "6-64 位,留空则不修改", + "admin.notifyEmail": "邮件", + "admin.useCustomFg": "启用自定义前景色(否则自动匹配)", + "admin.customFgHint": "仅在启用时生效,否则颜色由系统自动生成", + "admin.avatarPlaceholder": "上传个人头像(头像比例不为1:1就扁了你哦)", + "admin.backgroundPlaceholder": "上传提问箱背景", + "admin.qrBackgroundPlaceholder": "上传二维码背景(颜色过深的背景会导致二维码无法识别)", + "admin.qrPreviewHint": "选择图片后预览将即时更新", + "admin.preview": "实时预览", + "admin.themePreset": "预设主题", + "admin.themeDefault": "默认", + "admin.themeDark": "暗夜", + "admin.themeOcean": "海洋", + "admin.themeSunset": "日落", + "admin.resetDefaults": "🔄 恢复默认值", + "admin.previewHint": "调整仅用于预览,最终效果点击「保存修改」后生效", + "admin.socialHint": "勾选后填写主页地址(无需 https://),未勾选的项将不会在前台显示。", + "admin.enableAcfun": "启用 AcFun", + "admin.enableBili": "启用 Bilibili", + "admin.enableWeibo": "启用 微博", + "admin.enableXiaohongshu": "启用 小红书", + "admin.enableBlog": "启用 个人博客", + "admin.registerOnly": "仅允许注册用户向我提问", + "admin.updateHarassment": "更新防骚扰设置", + "admin.globalBlockWords": "全局屏蔽词", + "admin.globalBlockWordsHint": "屏蔽词对提问、私聊(对方发给你的消息)与投票提交内容生效;三个设置页同步显示同一份设置,任意一处修改即时生效。", + "admin.updateBlockWords": "保存屏蔽词", + "admin.allowChat": "允许注册用户向我发起私聊", + "admin.dailyLimitHint": "0 表示不限制", + "admin.updateChat": "更新私聊设置", + "admin.showInHome": "在首页展示我的标签(允许其他用户通过标签搜索到我)", + "admin.updateTags": "更新标签", + "admin.updatePagePassword": "更新页面密码", + "admin.pagePasswordPlaceholder": "输入页面访问密码", + "admin.updateAskPassword": "更新提问密码", + "admin.askPasswordPlaceholder": "输入提问密码", + "admin.account": "账号设置", + "admin.exportHint": "您可以导出您在 %s 中的所有个人数据,包括你的基本信息、收到的问题以及回答。", + "admin.exportJSON": "导出全部数据(JSON)", + "admin.exportJSONHint": "包含提问、回答、追问与私聊记录,可完整备份或迁移。", + "admin.deactivate": "停用我的账号", + "admin.deactivateHint": "您随时可以选择停用您的账号。停用后,您的账号将无法登录,您的提问箱页面以及提问将无法访问,其他人也无法再给您发送新的提问。该操作无法撤销!请谨慎操作!", + "admin.socialRequired": "请填写链接或取消勾选", + + // 问题管理页 + "qlist.title": "我的提问", + "qlist.answered": "已回答", + "qlist.pending": "待回答", + "qlist.private": "私密", + "qlist.empty": "还没有提问,快把提问箱分享出去吧~", + "qlist.action": "操作", + "qlist.answerNow": "去回答", + "qlist.sort": "排序", + "qlist.status": "状态", + "qlist.type": "类型", + "qlist.latest": "最新", + "qlist.oldest": "最早", + "qlist.all": "全部", + "qlist.public": "一般提问", + "qlist.privateQuestion": "私密提问", + "qlist.received": "我收到的提问", + "qlist.myChats": "我发起的私聊", + "qlist.statsTotal": "总提问数", + "qlist.statsAnswered": "已回答", + "qlist.statsUnanswered": "未回答", + "qlist.statsPrivate": "私密提问", + "qlist.statsPinned": "置顶", + "qlist.statsChats": "私聊会话", + "qlist.searchPlaceholder": "搜索问题或回答内容...", + "qlist.searchBtn": "搜索", + "qlist.searchClear": "清除搜索", + "qlist.questionsTab": "提问", + "qlist.votesTab": "投票", + "qlist.chatsTab": "私聊", + "qlist.receivedChats": "我收到的私聊", + "qlist.chatEmpty": "还没有私聊,把提问箱分享出去让大家来私聊吧~", + "qlist.pinnedShort": "置顶", + "qlist.privateShort": "私密", + "qlist.chatStatsTotal": "总私聊", + "qlist.chatStatsReceived": "我收到的", + "qlist.chatStatsInitiated": "我发起的", + "qlist.chatStatsClosed": "已关闭", + "qlist.unansweredShort": "待答", + "qlist.readShort": "已读", + "qlist.unreadShort": "未读", + "qitem.markReadShort": "标记", + "qlist.pinShort": "置顶", + "qlist.unpinShort": "取消置顶", + "qlist.myVotes": "我创建的投票", + "qlist.loadMore": "加载更多", + "qlist.newVote": "新建投票", + "qlist.edit": "编辑", + "qlist.untitledVote": "未命名投票", + "qlist.blocked": "已拉黑", + "qlist.unanswered": "未回答", + + // 站点 Logo 后缀(emoji 随机动物 + 后缀组成,如 🐺 的提问箱) + "site.logoSuffix": "的提问箱", + "site.stats": "提问箱信息统计", + + // 验证码弹窗 + "captcha.title": "人机验证", + "captcha.hint": "请计算下方的算术题以验证你不是机器人", + "captcha.refresh": "换一题", + "captcha.submit": "验证并提交", + "captcha.loading": "加载中...", + "captcha.loadFailed": "加载失败", + "captcha.loadRetry": "加载失败,请重试", + "captcha.inputAnswer": "请输入答案", + "captcha.wrongAnswer": "答案错误,请重新计算", + "captcha.verifyFailed": "验证失败,请重试", + + // 注册页补充 + "auth.register.domain.prefix": "个性域名(你的问答箱网址将会是:%s + ", + "auth.register.domain.suffix": " + 你在下面文本框中填写的内容)", + "auth.register.confirm": "确认密码", + "auth.register.language": "界面语言", + "auth.register.languageDefault": "跟随站点默认", + "auth.register.success": "注册成功,欢迎来到 狼的提问箱!", + + // 探索页补充 + "explore.recommend": "随机推荐", + "explore.search": "搜索标签...", + "explore.sortLatest": "最新加入", + "explore.sortOldest": "最早加入", + "explore.noTags": "无标签", + "explore.noRecommend": "暂无推荐用户", + "explore.hotTags": "热门标签", + "explore.hotQuestions": "热门问题", + "explore.noResult": "暂无符合条件的用户。", + "explore.lazy": "这个人很懒,什么都没写~", + "explore.prevPage": "上一页", + "explore.nextPage": "下一页", + "explore.loading": "加载中...", + "explore.loadFailed": "加载失败", + + // 提问箱密码页 + "password.title": "此提问箱需要密码", + "password.desc": "此提问箱已设置访问密码,请输入密码查看内容", + "password.input": "请输入访问密码", + "password.enter": "验证进入", + "password.submit": "确认", + + // 问题不存在 + "qitem.notFound": "问题不存在或已被删除", + + // 聊天页 + "chat.title": "私聊", + "chat.input": "输入消息...", + "chat.send": "发送", + "chat.delete": "删除对话", + "chat.block": "拉黑对方", + "chat.unblock": "取消拉黑", + "chat.empty": "还没有消息,说点什么吧~", + "chat.withAsker": "与提问者的私聊", + "chat.withUser": "与 %s 的私聊", + "chat.closed": "对话已关闭", + "chat.closedNoSend": "对话已关闭,无法发送新消息", + "chat.remaining": "消息剩余:%d 条(共 %d 条)", + "chat.me": "我", + "chat.other": "对方", + "chat.userBlocked": "该用户已被拉黑", + "chat.addImage": "添加图片(可选,最大5MB)", + "chat.confirm": "确认", + "chat.confirmBlock": "确定要拉黑该用户吗?他将无法再发送私信。", + "chat.confirmUnblock": "确定要取消屏蔽该用户吗?他将可以再次发送私信。", + "chat.deleteConfirm": "确定要删除这条私聊对话吗?对方将无法再看到此对话,且操作不可恢复。", + "maintenance.title": "NekoBox 维护中...", + "maintenance.desc": "NekoBox 正在进行维护,服务暂时不可用。过一会再来吧~", + + // 单题分享(v4) + "qitem.shareCard": "分享此提问", + + // 追问(v4) + "followup.title": "追问记录", + "followup.content": "追问:", + "followup.answerPlaceholder": "回答这条追问...", + "followup.answerBtn": "回答追问", + "followup.waiting": "等待回答中...", + "followup.askMore": "继续追问", + "followup.remaining": "还可追问 %d / %d 次", + "followup.contentPlaceholder": "补充你的问题...", + "followup.waitingReply": "你的追加提问已发出,等待提问箱主人回复中...", + "followup.submit": "提交追问", + + // 置顶(v4) + "qlist.pinned": "置顶中", + "qlist.pin": "置顶", + "qlist.unpin": "取消置顶", + "qlist.readStatus": "阅读状态", + "qlist.read": "已读", + "qlist.unread": "未读", + "qlist.statsRead": "已读", + "qlist.statsUnread": "未读", + + // 提问成功页(v4) + "success.title": "提问发送成功!", + "success.yourQuestion": "你的提问:", + "success.emailSent": "已向你的邮箱发送了该提问的私密链接,也可以使用下方链接随时查看提问、接收回答与继续追问。", + "success.saveLink": "请务必保存下面的私密链接!由于你没有留下邮箱,此链接(含口令 Token)是你查看提问、接收回答与继续追问的唯一凭证,丢失后将无法找回。", + "success.privateLink": "你的提问私密链接(点击复制保存)", + "success.copy": "复制", + "success.copied": "已复制 ✓", + "success.copyFailed": "复制失败", + "success.token": "口令 Token:%s(提问人凭 Token 访问私密链接)", + "success.viewQuestion": "查看我的提问", + "success.backToBox": "返回%s的提问箱", + "success.pageTitle": "提问成功 - %s", + + // 停用页 + "deactivate.title": "账号停用", + "deactivate.desc": "停用后你的提问箱将无法访问,且所有数据将被删除,此操作不可恢复!", + "deactivate.confirm": "我确认要停用账号", + "deactivate.submit": "停用账号", + + // 匿名投票 + "nav.votes": "投票", + + "common.back": "返回", + + "vote.listTitle": "投票管理", + "vote.newTitle": "新建投票", + "vote.editTitle": "编辑投票", + "vote.resultsTitle": "投票结果", + "vote.statsTotal": "投票总数", + "vote.statsPublished": "进行中", + "vote.createNew": "新建投票", + "vote.typeSingle": "单选", + "vote.typeMultiple": "多选", + "vote.typeRating": "评分", + "vote.typeRank": "排序", + "vote.typeForm": "表单收集", + "vote.statusNotStarted": "未开始", + "vote.statusDraft": "草稿", + "vote.statusPublished": "进行中", + "vote.statusEnded": "已结束", + "vote.statusArchived": "已归档", + "vote.participants": "参与", + "vote.remainLabel": "剩余", + "vote.perpetual": "无限期", + "vote.durationDay": "天", + "vote.durationHour": "小时", + "vote.durationMinute": "分钟", + "vote.createdAt": "创建于", + "vote.edit": "编辑", + "vote.results": "结果", + "vote.preview": "预览", + "vote.page.mustComplete": "请完成", + "vote.page.rankHintRequired": "排名 1-N(必填)", + "vote.page.rankHintOptional": "排名 1-N(可选,可只排部分)", + "vote.page.previewHint": "预览模式:这是发布前的页面样例,提交已禁用", + "vote.page.previewSubmitHint": "预览模式,发布后即可提交", + "vote.publish": "发布", + "vote.close": "结束", + "vote.share": "复制链接", + "vote.copied": "已复制", + "vote.shareURL": "投票分享链接", + "vote.confirmPublish": "确定发布该投票吗?发布后即生成可分享链接。", + "vote.confirmClose": "确定结束该投票吗?结束后参与者将无法再投票。", + "vote.confirmDelete": "确定删除该投票吗?投票数据将一并删除,不可恢复!", + "vote.manageEntry": "管理投票", + + "vote.manageTitle": "管理投票", + "vote.manageDesc": "创建与管理你的匿名投票", "vote.empty": "还没有投票,点击右上角\"新建投票\"开始吧~", + "vote.formLockedHint": "该投票已发布,仅可修改基本信息;类型与选项已锁定(避免破坏已收集的投票数据)", + "vote.formBasic": "基本设置", + "vote.formTitle": "投票标题", + "vote.formTitlePlaceholder": "例如:今天吃什么?", + "vote.formDescription": "描述 / 说明", + "vote.formDescriptionPlaceholder": "补充说明(可选)", + "vote.formType": "投票类型", + "vote.formVisibility": "展示方式", + "vote.formVisibilityPublic": "公开展示(探索页 + 提问箱页)", + "vote.formVisibilityLinkOnly": "仅链接分享", + "vote.formVoterScope": "投票范围", + "vote.formVoterScopeAnyone": "任何人(含匿名)", + "vote.formVoterScopeRegistered": "仅注册用户", + "vote.formShowResult": "结果可见时机", + "vote.formShowResultAfterVote": "投票后立即可见", + "vote.formShowResultAfterEnd": "结束后可见", + "vote.formShowResultOwnerOnly": "仅我可见", + "vote.formStartAt": "开始时间(留空立即开始)", + "vote.formEndAt": "结束时间(留空不限制)", + "vote.formMaxChoices": "最多可选数量", + "vote.formMaxVotesPerFingerprint": "每个投票每个设备限 1 次,使用同一浏览器重复提交将被拦截。", + "vote.formMaxVotesPerAccount": "每个投票每个注册账号限 1 次,使用同一账号重复提交将被拦截。", + "vote.formAllowCustom": "允许参与者补充自定义选项", + "vote.formRequireCaptcha": "匿名投票需通过验证码", + "vote.formOptions": "投票选项", + "vote.formRatingHint": "评分题无需配置选项(1-10 分)", + "vote.addOption": "添加选项", + "vote.optionPlaceholder": "选项内容", + "vote.formFields": "表单字段", + "vote.addField": "添加字段", + "vote.field": "字段", + "vote.formFieldType": "字段类型", + "vote.fieldTypeText": "单行文本", + "vote.fieldTypeTextarea": "多行文本", + "vote.fieldTypeSelect": "下拉选择", + "vote.fieldTypeRadio": "单选", + "vote.fieldTypeCheckbox": "多选", + "vote.fieldTypeNumber": "数字", + "vote.fieldTypeRank": "排序", + "vote.page.selectPlaceholder": "请选择", + "vote.page.avgNumber": "平均", + "vote.page.fieldFilled": "已填写", + "vote.fieldTypeRating": "评分", + "vote.formFieldLabel": "字段标签", + "vote.formFieldRequired": "必填", + "vote.formFieldMaxLength": "字数上限(0 不限制)", + "vote.formFieldOptions": "选项", + "vote.formFieldOptionsHint": "点击下方「添加选项」逐条添加,无需用逗号分隔", + "vote.fieldAllowCustom": "允许补充自定义选项", + "vote.formFieldOptionsPlaceholder": "如:满意,一般,不满意", + "vote.createDraft": "保存草稿", + "vote.builderHintOptions": "至少需要 2 个选项", + "vote.builderHintFields": "请至少添加 1 个字段", + "vote.builderHintFieldOptions": "选择题/排序题请填写选项(排序题至少 2 个)", + "vote.resultsAnswered": "回答数", + "vote.page.rankedTimes": "被排次数", + "vote.resultsTotal": "总参与人数", + "vote.resultsSubmissions": "表单回复", + "vote.resultsViewTexts": "查看文本提交", + "vote.resultsToggleHint": "点击展开或收起文本回复明细", + "vote.resultsOptions": "投票结果", + "vote.resultsVotes": "票", + "vote.export": "导出 CSV", + "vote.resultsEmpty": "还没有人参与,快来分享吧~", + + // 匿名投票参与页 + "vote.inlineTitle": "投票", + "vote.page.by": "发起的投票", + "vote.page.goVote": "去投票", + "vote.page.notStarted": "未开始", + "vote.page.notStartedHint": "该投票尚未开始,敬请期待~", + "vote.page.ended": "已结束", + "vote.page.endedHint": "该投票已结束", + "vote.page.active": "进行中", + "vote.page.participated": "已参与", + "vote.page.loginRequired": "该投票仅限注册用户参与,请先登录。", + "vote.page.anonymousHint": "该投票允许匿名参与,你的身份不会被记录(同一设备最多可参与 1 次)。", + "vote.page.submit": "提交投票", + "vote.page.alreadyVoted": "你已参与过该投票,感谢参与!", + "vote.page.resultsTitle": "投票结果", + "vote.page.totalVotes": "总参与", + "vote.page.avgRating": "平均分", + "vote.page.avgRank": "平均排名", + "vote.page.optionColumn": "选项", + "vote.page.ratingLabel": "请评分", + "vote.page.ratingUnit": "分", + "vote.page.rankHint": "请为每个选项填写 1-N 的排名(数字越小越靠前,不可重复)", + "vote.page.rankPlaceholder": "排名", + "vote.page.multipleHint": "可多选", + "vote.page.customOption": "补充选项(可选)", + "vote.page.customPlaceholder": "填写你心中的其他选项", + "vote.page.customOther": "其他", + "vote.page.customFieldPlaceholder": "填写自定义选项…", + "vote.page.customStats": "自定义补充选项", + "vote.page.formCount": "已收到回复", + "vote.page.ownerManage": "管理此投票(仅你可见结果)", + + // 单份投票的定量收集 + "vote.formQuotaLimit": "收集上限(份)", + "vote.formQuotaHint": "0 表示不限制;收集到指定份数后自动结束该投票。", + "vote.flash.notFound": "投票不存在或已失效", + "vote.flash.notPublished": "该投票尚未发布", + "vote.flash.archived": "该投票已归档,无法参与", + "vote.flash.ended": "该投票已结束", + "vote.flash.notStarted": "该投票尚未开始", + "vote.flash.success": "投票成功!感谢参与", + "vote.err.noChoice": "请至少选择一个选项", + "vote.err.tooManyChoices": "最多只能选择 %d 个选项", + "vote.err.pickOne": "请选择一个选项", + "vote.err.invalidOption": "存在无效的选项", + "vote.err.optionDuplicate": "选项不能重复选择", + "vote.err.ratingRequired": "请给出 1-10 分的评分", + "vote.err.rankRequired": "请为每个选项填写 1-%d 的排名", + "vote.err.rankDuplicate": "排名不能重复", + "vote.err.fieldRequired": "请填写「%s」", + "vote.err.fieldCustomRequired": "请填写「%s」的自定义选项", + "vote.err.fieldCustomTooLong": "「%s」的自定义选项不能超过 %d 字", + "vote.err.fieldInvalidOption": "「%s」的选项无效", + "vote.err.fieldConfigError": "「%s」选项配置错误", + "vote.err.fieldRankIncomplete": "请填写「%s」的完整排名", + "vote.err.fieldRankRange": "「%s」排名必须是 1-%d 之间的数字", + "vote.err.fieldRankDuplicate": "「%s」排名不能重复", + "vote.err.fieldTooLong": "「%s」超出字数限制(最多 %d 字)", + "vote.err.fieldNotNumber": "「%s」必须是数字", + "vote.err.fieldRating": "「%s」请给出 1-10 分的评分", + "vote.err.unknownType": "未知的投票类型", + "vote.err.customTooLong": "自定义选项不能超过 %d 字", + "vote.err.blockWords": "提交内容中包含了投票发起人设置的屏蔽词,无法提交", + "vote.err.serialize": "提交内容序列化失败", + "captcha.error": "验证码错误", + "captcha.errEmpty": "验证码不能为空", + "captcha.errFormat": "验证码格式错误,请刷新后重试", + "captcha.errAnswerFormat": "验证码答案格式错误", + "captcha.errExpired": "验证码已过期,请刷新后重试", + "captcha.errService": "验证码服务异常,请稍后重试", + "captcha.errAnswerWrong": "验证码答案错误", + "censor.unavailable": "内容审核服务暂时不可用,请稍后再试", + + // 功能管理:提问 / 私聊 / 投票 的开关、定时开关与定量收集 + "admin.tabAccount": "用户设置", + "admin.featuresHint": "在「提问 / 私聊 / 投票」面板中管理各功能的开关、开放时段与收集上限;达到上限后对应功能自动关闭。", + "admin.featuresEntry": "设置", + "admin.featureHint.question": "关闭后访客无法提交新提问;达到收集上限后自动停止接收(含私密提问)。", + "admin.featureHint.chat": "关闭后访客无法发起新的私聊;已有会话不受影响。", + "admin.featureHint.vote": "关闭后提问箱页不再展示投票板块,访客也无法参与你的投票。单份投票可在编辑页单独设置收集上限。", + "admin.featureEnabled": "开启该功能", + "admin.featureOpenAt": "定时开放", + "admin.featureCloseAt": "定时关闭", + "admin.featureTimeHint": "留空表示不限制;开放时间之前、关闭时间之后该功能均不可用。", + "admin.featureSchedule": "循环定时(每周循环)", + "admin.featureScheduleStart": "每日开始", + "admin.featureScheduleEnd": "每日结束", + "admin.featureScheduleHint": "勾选每周固定开放日并设置每日时间段,按周循环生效;全部留空表示不启用。只填开放日(不填时间)表示该天全天开放;只填时间(不勾选任何日)表示每天该时段开放。", + "admin.featureMode": "收集模式", + "admin.featureModeAlways": "长期开放", + "admin.featureModeWindow": "定时收集", + "admin.featureModeRecurring": "循环定时", + "admin.featureModeHint": "长期开放:不限时间,保持开放直到手动关闭;定时收集:一次性开放 / 关闭时间窗口;循环定时:每周固定开放日循环生效。三种模式互斥,保存时未选模式的设置将被清空。", + "admin.featureQuotaLimit": "收集上限(条 / 份)", + "admin.featureQuotaHint": "0 表示不限制;累计收集达到上限后自动关闭,重置计数后可开启下一轮。", + "admin.featureQuotaCount": "已收集", + "admin.featureQuotaUnlimited": "不限制", + "admin.featureQuotaResetAt": "上次重置:", + "admin.featureResetQuota": "重置计数", + "admin.featureSave": "保存该功能设置", + + // 功能管理:状态与提示 + "feature.name.question": "提问", + "feature.name.chat": "私聊", + "feature.name.vote": "投票", + "feature.statusOpen": "进行中", + "feature.status.disabled": "已关闭", + "feature.status.not_started": "未开始", + "feature.status.ended": "已结束", + "feature.status.quota_reached": "已达上限", + "feature.saved": "功能设置已保存", + "feature.errTime": "%s 的时间格式不正确,请使用日期时间选择器", + "feature.errTimeRange": "%s 的定时关闭时间必须晚于定时开放时间", + "feature.errQuota": "%s 的收集上限需为 0 到 1000000 之间的整数", + "feature.errInvalid": "未知的功能类型", + "feature.quotaReset": "%s 的收集计数已重置", + "feature.errScheduleHalf": "%s 的循环定时开始与结束时间必须同时填写", + "feature.errScheduleTime": "%s 的循环定时时间格式不正确,请使用时间选择器", + "feature.errScheduleRange": "%s 的循环定时结束时间必须晚于开始时间", + + // 功能关闭时对访客的提示 + "feature.disabled.question": "提问箱主人已关闭提问功能", + "feature.disabled.chat": "该提问箱未开启私聊功能", + "feature.disabled.vote": "该提问箱已关闭投票功能", + "feature.not_started.question": "提问功能尚未开放", + "feature.not_started.chat": "私聊功能尚未开放", + "feature.not_started.vote": "投票功能尚未开放", + "feature.ended.question": "提问功能已结束收集", + "feature.ended.chat": "私聊功能已结束", + "feature.ended.vote": "投票功能已结束", + "feature.quota_reached.question": "提问功能已达到收集上限", + "feature.quota_reached.chat": "私聊功能已达到收集上限", + "feature.quota_reached.vote": "投票功能已达到收集上限", + + // 认证:访客可见的提示(P0) + "auth.errBadCredential": "邮箱或密码错误", + "auth.errUserNotFound": "用户不存在", + "auth.errEmailFrequent": "邮件发送太频繁,请稍后再试", + "auth.errEmailFailed": "邮件发送失败,请稍后再试", + "auth.errCodeExpired": "验证码已过期", + "auth.errPasswordChanged": "密码修改成功", + "auth.errLoginRequired": "请先登录", + "auth.errDuplicateEmail": "该邮箱已被注册", + "auth.errDuplicateDomain": "该个性域名已被使用", + + // 提问箱页:访客可见(P0) + "question.errWrongPassword": "密码错误", + "question.errAskPasswordWrong": "提问密码错误", + "question.errLoginRequired": "提问箱的主人设置了仅注册用户才能提问,请先登录。", + "question.errSelfChat": "不能给自己发起私聊", + "question.errBlockedChat": "你已被对方拉黑,无法发起私聊", + "question.errChatDailyLimit": "你今日已达发送上限(%d条),请明天再试", + "question.errDuplicateSubmit": "检测到重复提交,请稍后再试", + "question.errImageTooLarge": "图片文件大小不能大于 5Mb", + "question.errUploadImageFailed": "上传图片失败", + "question.errBlockWords": "提问内容中包含了提问箱主人设置的屏蔽词,发送失败", + "question.errAnsweredLocked": "已回答的问题不能标记为未读", + "question.flash.chatSent": "私聊请求已发送!你可以通过以下链接查看对话:%s", + "question.flash.answered": "回答发布成功!", + "question.flash.operated": "操作成功", + "question.flash.markedRead": "已标记为已读", + "question.flash.markedUnread": "已标记为未读", + + // 追问:访客/箱主可见(P0) + "followup.errNoPermission": "无权操作", + "followup.errNotAnswered": "问题尚未被回答,暂时不能追问", + "followup.errLimit": "每条提问最多追问 %d 次,已达上限", + "followup.errWaitReply": "请等待主人回复上一条追问后再继续追问", + "followup.errNotFound": "追问不存在", + "followup.flash.sent": "追问发送成功!", + "followup.flash.answered": "回答成功!", + + // 后台设置:箱主可见(P1) + "admin.flash.profileUpdated": "更新个人信息成功", + "admin.flash.chatUpdated": "私聊设置更新成功", + "admin.flash.pagePwdOff": "已关闭页面密码访问", + "admin.flash.pagePwdUpdated": "页面访问密码已更新", + "admin.flash.askPwdOff": "已关闭提问密码", + "admin.flash.askPwdUpdated": "提问密码已更新", + "admin.flash.tagsTooMany": "标签不能超过 5 个", + "admin.flash.tagsUpdated": "更新标签成功", + "admin.flash.tagTooLong": "每个标签不能超过 5 个字符:%s", + "admin.flash.blockWordsTooMany": "屏蔽词不能超过 10 个", + "admin.flash.blockWordTooLong": "屏蔽词长度不能超过 10 个字符:%s", + "admin.flash.harassmentUpdated": "更新防骚扰设置成功", + "admin.flash.blockWordsUpdated": "屏蔽词已更新", + "admin.flash.deactivated": "您的账号已停用,感谢您使用 狼的提问箱。期待未来还能再见 👋🏻", + "admin.export.errUser": "导出失败:获取用户信息失败", + "admin.export.errQuestion": "导出失败:获取问题信息失败", + + // 投票管理:箱主可见(P1) + "vote.err.invalidID": "无效的投票 ID", + "vote.err.notExist": "投票不存在", + "vote.err.noPermission": "无权操作该投票", + "vote.err.type": "未知的投票类型", + "vote.err.titleRequired": "请填写投票标题", + "vote.err.titleTooLong": "投票标题不能超过 100 字", + "vote.err.visibility": "未知的可见性设置", + "vote.err.voterScope": "未知的投票范围设置", + "vote.err.showResult": "未知的结果展示设置", + "vote.err.timeRange": "结束时间必须晚于开始时间", + "vote.err.quota": "收集上限需为 0 到 1000000 之间的整数", + "vote.err.optionsTooFew": "请至少添加 2 个选项", + "vote.err.optionsFormat": "选项数据格式错误", + "vote.err.optionTooLong": "单个选项内容不能超过 %d 字", + "vote.err.maxChoicesExceed": "最多可选数量不能超过选项总数", + "vote.err.fieldsTooFew": "请至少添加 1 个表单字段", + "vote.err.fieldsFormat": "表单字段数据格式错误", + "vote.err.fieldsTooMany": "表单字段不能超过 50 个", + "vote.err.fieldType": "存在未知的表单字段类型", + "vote.err.fieldLabelMissing": "第 %d 个字段缺少标签", + "vote.err.fieldLabelTooLong": "第 %d 个字段的标签不能超过 100 字", + "vote.err.fieldLabelDuplicate": "字段标签「%s」重复,请使用不同的标签", + "vote.err.fieldMaxLength": "第 %d 个字段的字数上限需在 0-2000 之间", + "vote.err.fieldReservedOption": "第 %d 个字段(%s)的选项内容包含保留值,请更换", + "vote.err.fieldOptionsTooFew": "第 %d 个字段(%s)请至少填写 1 个选项", + "vote.err.fieldRankTooFew": "第 %d 个字段(%s)排序题至少需要 2 个选项", + "vote.err.fieldSerialize": "字段选项序列化失败", + "vote.err.editClosed": "已结束或归档的投票不允许编辑", + "vote.err.publishDraftOnly": "只有草稿状态的投票可以发布", + "vote.err.closePublishedOnly": "只有进行中的投票可以结束", + "vote.err.publishTitleRequired": "请先填写投票标题再发布", + "vote.err.publishFormFieldsRequired": "表单类型投票至少需要 1 个字段", + "vote.err.publishOptionsRequired": "选项投票至少需要 2 个选项", + "vote.err.optionUpdateFailed": "选项更新失败,请重试", + "vote.err.fieldUpdateFailed": "表单字段更新失败,请重试", + "vote.flash.published": "投票已发布!分享链接:%s", + "vote.flash.updated": "投票信息已更新(进行中的投票不可修改类型与选项)", + "vote.flash.draftSaved": "已保存到草稿", + "vote.flash.closed": "投票已结束", + "vote.flash.deleted": "投票已删除", + "vote.err.timeFormat": "时间格式不正确,请使用日期时间选择器", + "vote.err.maxChoicesLimit": "最多可选数量不能超过 20", + "vote.err.descriptionTooLong": "投票描述不能超过 5000 字", + "profile.err.avatarTooLarge": "头像文件太大,最大支持 2MB", + "profile.err.backgroundTooLarge": "背景图文件太大,最大支持 2MB", + "profile.err.newPasswordTooShort": "新密码长度不能少于 8 位", + "profile.err.badOldPassword": "旧密码输入错误", + "admin.export.errCreateExcel": "导出失败:创建Excel文件失败", + "admin.export.errWriteExcel": "导出失败:写入Excel文件失败", + + // profile 设置页 UI 重构:卡片分区 / 头像背景裁剪 / 改密强制登出 + "profile.card.basic": "基础资料", + "profile.card.avatarBg": "头像与背景", + "profile.card.qr": "二维码样式", + "profile.card.password": "修改密码", + "profile.avatarCropHint": "裁剪框已锁定为 1:1 正方形", + "profile.backgroundCropHint": "裁剪框已锁定为 16:9 宽屏", + "profile.cropTitle": "裁剪图片", + "profile.cropConfirm": "确认裁剪", + "profile.err.avatarRatio": "头像图片必须为 1:1 正方形,请裁剪后再上传", + "profile.err.backgroundRatio": "背景图片必须为 16:9 宽高比,请裁剪后再上传", + "profile.flash.passwordChanged": "密码修改成功,已退出登录,请使用新密码重新登录", + "profile.pwdNote": "保存后当前会话立即失效,需使用新密码重新登录", + "profile.pickAvatar": "更换头像", + "profile.pickBackground": "更换背景", + "profile.saveBasic": "保存基础资料", + "profile.saveMedia": "保存头像与背景", + "profile.savePassword": "确认修改密码", + "profile.saveQR": "保存二维码样式", + "profile.saveSocial": "保存社交链接", + "profile.err.cropLibUnavailable": "图片裁剪组件加载失败,请刷新页面后重试", + + // 验证码 JSON 接口:前端消费(P2) + "captcha.json.badRequest": "请求格式错误", + "captcha.json.idRequired": "验证码 ID 不能为空", + "captcha.json.genFailed": "生成验证码失败", + "chat.errDeletedByOwner": "该私聊对话已被对方删除。", + "chat.errBlockedView": "你已被对方拉黑,无法查看该私聊", + "chat.errEmpty": "消息不能为空", + "chat.errTooLong": "消息内容过长,请控制在 %d 字以内", + "chat.errConvDeletedSend": "该对话已被删除,无法发送消息", + "chat.errBlockedSend": "你已被对方拉黑,无法发送私信", + "chat.errBlockWords": "消息中包含了提问箱主人设置的屏蔽词,无法发送", + "chat.errDailyLimit": "你今日已达发送上限(%d条),请明天再试", + "chat.errLimitReached": "对话已达到上限,无法发送新消息", + "chat.errChatClosed": "该箱主已关闭私聊功能,无法发送消息", + "chat.errImageTooLarge": "图片大小不能超过 %dMB", + "chat.errUploadFailed": "图片上传失败,请稍后重试", + "chat.errNoPermission": "无权执行此操作", + "chat.flash.sent": "消息发送成功", + "chat.flash.deleted": "私聊对话已删除", + "chat.flash.operated": "操作成功", + "image.errTooLarge": "图片尺寸过大,最大支持 %d×%d 像素,请压缩后重新上传", + "internal.errFlash": "服务内部错误,请稍后重试。", + "internal.errServer": "服务器内部错误", + "home.errStats": "获取统计信息失败", + "pixel.errPath": "非法的请求路径", + "proxy.errNotFound": "页面不存在", + "proxy.errInternal": "服务网关内部错误", + "explore.errRandomUser": "获取随机用户失败", + // 表单校验 + "form.answer.content": "回答内容不能为空", + "form.answer.contentTooLong": "回答内容不能超过 %d 个字符", + "form.email.required": "请填写有效的电子邮箱地址", + "form.followup.answer": "追问回答不能为空", + "form.followup.answerTooLong": "追问回答不能超过 %d 个字符", + "form.followup.content": "追问内容不能为空", + "form.followup.contentTooLong": "追问内容不能超过 %d 个字符", + "form.login.password": "请输入密码", + "form.profile.backgroundimagealpha": "请填写二维码背景透明度", + "form.profile.colorHex": "请填写 7 位十六进制颜色代码(含 #)", + "form.profile.dotscale": "请填写二维码点大小", + "form.profile.intro": "个人介绍不能为空,且不超过 100 个字符", + "form.profile.linkMax": "主页链接长度不能超过 30 个字符", + "form.profile.name": "昵称不能为空,且不超过 20 个字符", + "form.profile.newPassword": "新密码长度不能超过 30 个字符", + "form.profile.passwordMax": "密码长度不能超过 30 个字符", + "form.question.content": "问题内容不能为空", + "form.question.contentTooLong": "问题内容不能超过 %d 个字符", + "form.question.receiveReplyEmail": "请填写有效的电子邮箱地址以接收回复", + "form.recaptcha": "请完成人机验证", + "form.recover.newPassword": "请设置 8 至 30 位的新密码", + "form.recover.repeatPassword": "两次输入的新密码不一致", + "form.register.domain": "个性域名只能包含字母、数字和下划线,长度为 3 至 20 位", + "form.register.email": "请填写有效的电子邮箱地址(不超过 100 个字符)", + "form.register.name": "昵称不能为空,且不超过 20 个字符", + "form.register.password": "请设置 8 至 30 位的密码", + "form.register.recaptcha": "无法加载人机验证,请刷新页面或切换网络后重试", + "form.register.repeatPassword": "两次输入的密码不一致", +} diff --git a/.workbuddy/backup/remove-vercount-20260906/dict_zh_tw.go b/.workbuddy/backup/remove-vercount-20260906/dict_zh_tw.go new file mode 100644 index 0000000..6f3acf4 --- /dev/null +++ b/.workbuddy/backup/remove-vercount-20260906/dict_zh_tw.go @@ -0,0 +1,842 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package i18n + +// zhTWDict 繁體中文文案。 +var zhTWDict = map[string]string{ + // 導覽 + "nav.explore": "探索", + "nav.mine": "我的", + "nav.register": "註冊", + "nav.login": "登入", + "nav.ask": "提問", + "nav.settings": "設定", + "nav.lang": "語言", + + // 通用 + "common.login": "登入", + "common.forgot": "忘記密碼", + "common.submit": "送出", + "common.cancel": "取消", + "common.save": "儲存", + "common.close": "關閉", + "common.delete": "刪除", + "common.moveUp": "上移", + "common.moveDown": "下移", + "common.share": "分享", + "common.verifying": "驗證中...", + "common.submitting": "提交中...", + "common.uploading": "上傳中...", + "common.lang": "語言", + "common.menu": "選單", + + "common.pleaseWait": "請稍候...", + "common.backHome": "返回首頁", + "common.theme": "切換深色/淺色模式", + + // 站點 + "site.title": "狼的提問箱 | 匿名提問箱", + "site.description": "狼的提問箱——一個無需註冊、可匿名提問的匿名提問箱,安全地傾訴與回應。", + "site.keywords": "匿名提問箱,提問箱,匿名提問,狼的提問箱,匿名問答,匿名提問網站", + "site.footer.visitor": "您是本站第 %s 位訪客", + "site.footer.pageview": "本頁面已被訪問 %s 次", + "site.footer.runtime": "提問箱已成功存活", + "site.footer.admin": "找站長", + "site.footer.notice": "公告板", + "site.footer.chat": "聊天室", + "site.footer.drive": "盤", + "site.footer.status": "監控板", + "site.footer.nav": "導航頁", + "site.maintenance": "本站正在維護中,請稍後再來~", + + // 認證 + "auth.login.title": "使用者登入", + "auth.login.email": "電子郵件", + "auth.login.password": "密碼", + "auth.login.submit": "登入", + "auth.login.forgot": "忘記密碼", + "auth.register.title": "使用者註冊", + "auth.register.name": "暱稱", + "auth.register.email": "電子郵件", + "auth.register.password": "密碼", + "auth.register.submit": "註冊", + "auth.forgot.title": "忘記密碼", + "auth.forgot.email": "電子郵件", + "auth.forgot.submit": "傳送重設郵件", + "auth.forgot.submitBtn": "找回密碼", + "auth.forgot.sent": "郵件已傳送至 %s,請查收。", + "auth.recover.title": "重設密碼", + "auth.recover.greeting": "%s,您正在重設您的密碼:", + "auth.recover.password": "新密碼", + "auth.recover.confirm": "確認密碼", + "auth.recover.submit": "重設密碼", + + // 探索頁 + "explore.title": "探索使用者標籤", + "explore.notice": "此處展示已開啟「在首頁展示我的標籤」的使用者。該功能預設關閉,若希望自己的提問箱在這裡被發現,請前往 個人設定 手動開啟。", + "explore.shuffle": "換一批", + "explore.empty": "暫時沒有可展示的使用者,快去開啟吧~", + "explore.hotVotes": "熱門投票", + "explore.questionsTab": "提問", + "explore.votesTab": "投票", + "explore.votesTitle": "公開投票", + "explore.votesDesc": "瀏覽進行中的公開投票,選擇你感興趣的主題參與。", + "explore.randomVote": "隨機推薦", + "explore.allVotes": "全部投票", + "explore.noVotes": "暫時沒有可參與的公開投票。", + + // 提問頁 + "ask.scan": "掃碼向@%s提問", + "ask.anonymous": "誰都可以以匿名的方式提問", + "ask.registerOnly": "僅允許註冊使用者向TA提問", + "ask.nextOpenAt": "下次開放時間:%s", + "ask.lastCloseAt": "上次關閉時間:%s", + "weekday.0": "週日", + "weekday.1": "週一", + "weekday.2": "週二", + "weekday.3": "週三", + "weekday.4": "週四", + "weekday.5": "週五", + "weekday.6": "週六", + "ask.pinned": "已置頂", + "ask.share": "分享提問箱", + "ask.placeholder": "在此處撰寫你的問題...", + "ask.chatPlaceholder": "在此處撰寫你的私聊訊息...", + "ask.addImage": "新增圖片", + "ask.private": "回覆後不公開", + "ask.notify": "接收通知", + "ask.emailPlaceholder": "請輸入你的信箱地址", + "ask.submit": "傳送提問", + "ask.chat": "發起私聊", + "ask.chatDisabled": "該提問箱未開啟私聊", + "ask.chatLimit": "訊息上限:%d則", + "ask.history": "@%s 以前回答過的問題", + "ask.loginRequired": "需要登入", + "ask.loginRequiredChat": "發起私聊需要登入帳號", + "ask.goLogin": "去登入", + "ask.needPassword": "此提問箱需要密碼", + "ask.needLogin": "提問箱的主人設定了僅註冊使用者才能提問,你需要先登入才能向他提問。", + "ask.pleaseEmail": "請填寫接收通知的信箱地址", + "ask.generating": "正在產生分享圖…", + "ask.genFailed": "產生分享圖失敗,請稍後重試", + "ask.networkError": "網路錯誤", + "ask.shareFilename": "share.png", + + // 問題條目 + "qitem.answer": "回答", + "qitem.delete": "刪除", + "qitem.private": "設為私密", + "qitem.public": "設為公開", + "qitem.asked": "提問", + "qitem.pending": "等待回答", + "qitem.answeredBy": "@%s 於 %s 的回答", + "qitem.danger": "危險!", + "qitem.deleteConfirm": "你確定要刪除這個提問嗎?該操作不可恢復,請謹慎操作。", + "qitem.deleteConfirmBtn": "確認刪除", + "qitem.backToBox": "返回%s的提問箱", + "qitem.answerTitle": "回答問題", + "qitem.answerPlaceholder": "在此處撰寫你的回答...", + "qitem.emailNotifyHint": "提問人留下了自己的電子郵箱,在你第一次回覆該問題後,提問人將會收到一封郵件通知。", + "qitem.submitAnswer": "回答", + "qitem.updateAnswer": "更新回答", + "qitem.askMore": "再問點別的問題?", + "qitem.markRead": "標記為已讀", + "qitem.markUnread": "標記為未讀", + "qitem.readLocked": "已回答,已鎖定為已讀", + + // 個人設定頁 + "admin.profile": "個人資訊", + "admin.lang": "介面語言", + "admin.langHint": "選擇訪客訪問你的提問箱時顯示的語言(後台頁面跟隨此設定)", + "admin.email": "電子郵件", + "admin.name": "暱稱", + "admin.nameColor": "暱稱顏色", + "admin.oldPassword": "舊密碼", + "admin.newPassword": "新密碼", + "admin.notify": "新提問通知", + "admin.personalize": "個人化設定", + "admin.intro": "提問箱介紹", + "admin.introColor": "提問箱介紹顏色", + "admin.qrBgColor": "QR Code 背景色(亮色部分)", + "admin.qrPdColor": "QR Code 探測圖形顏色(邊角方形)", + "admin.qrFgColor": "QR Code 前景色", + "admin.qrDotSize": "QR Code 點大小 (←小 大→)", + "admin.qrBgAlpha": "QR Code 背景透明度 (←不透明 很透明→)", + "admin.avatar": "個人頭像", + "admin.background": "提問箱背景", + "admin.qrBackground": "QR Code 背景圖", + "admin.social": "社交資訊設定", + "admin.harassment": "防騷擾設定", + "admin.askLimit": "提問限制", + "admin.blockWords": "屏蔽詞設定(Enter 或逗號分隔,最多支援 10 個屏蔽詞,每個屏蔽詞最大長度為 10)", + "admin.chat": "私聊設定", + "admin.chatMaxMessages": "私聊訊息條數上限", + "admin.chatDailyLimit": "單一使用者每日私訊條數上限", + "admin.tags": "標籤設定", + "admin.tagsHint": "標籤(最多5個,每個最多5字,Enter 或逗號分隔)", + "admin.tagsPlaceholder": "例如:動漫,音樂,遊戲", + "admin.tagInputHint": "輸入後按 Enter 或逗號新增", + "admin.tagInputDuplicate": "已存在,已忽略", + "admin.pagePassword": "頁面訪問密碼", + "admin.pagePasswordHint": "設定訪問密碼(留空則關閉)", + "admin.askPassword": "提問密碼", + "admin.askPasswordHint": "設定提問密碼(留空則關閉)", + "admin.saveProfile": "儲存修改", + "admin.updated": "更新個人資訊成功", + "admin.logout": "登出", + "admin.export": "匯出資料", + + // 後台設定(補充) + "admin.oldPasswordHint": "修改密碼使用,留空則不修改", + "admin.newPasswordHint": "6-64 位,留空則不修改", + "admin.notifyEmail": "郵件", + "admin.useCustomFg": "啟用自訂前景色(否則自動比對)", + "admin.customFgHint": "僅在啟用時生效,否則顏色由系統自動產生", + "admin.avatarPlaceholder": "上傳個人頭像(頭像比例不為1:1就扁了你哦)", + "admin.backgroundPlaceholder": "上傳提問箱背景", + "admin.qrBackgroundPlaceholder": "上傳QR Code背景(顏色過深的背景會導致QR Code無法辨識)", + "admin.qrPreviewHint": "選擇圖片後預覽將即時更新", + "admin.preview": "即時預覽", + "admin.themePreset": "預設主題", + "admin.themeDefault": "預設", + "admin.themeDark": "暗夜", + "admin.themeOcean": "海洋", + "admin.themeSunset": "日落", + "admin.resetDefaults": "🔄 恢復預設值", + "admin.previewHint": "調整僅用於預覽,最終效果點擊「儲存修改」後生效", + "admin.socialHint": "勾選後填寫主頁地址(無需 https://),未勾選的項目將不會在前台顯示。", + "admin.enableAcfun": "啟用 AcFun", + "admin.enableBili": "啟用 Bilibili", + "admin.enableWeibo": "啟用 微博", + "admin.enableXiaohongshu": "啟用 小紅書", + "admin.enableBlog": "啟用 個人部落格", + "admin.registerOnly": "僅允許註冊使用者向我提問", + "admin.updateHarassment": "更新防騷擾設定", + "admin.globalBlockWords": "全局屏蔽詞", + "admin.globalBlockWordsHint": "屏蔽詞對提問、私聊(對方傳送給你的訊息)與投票提交內容生效;三個設定頁同步顯示同一份設定,任意一處修改即時生效。", + "admin.updateBlockWords": "儲存屏蔽詞", + "admin.allowChat": "允許註冊使用者向我發起私聊", + "admin.dailyLimitHint": "0 表示不限制", + "admin.updateChat": "更新私聊設定", + "admin.showInHome": "在首頁展示我的標籤(允許其他使用者透過標籤搜尋到我)", + "admin.updateTags": "更新標籤", + "admin.updatePagePassword": "更新頁面密碼", + "admin.pagePasswordPlaceholder": "輸入頁面訪問密碼", + "admin.updateAskPassword": "更新提問密碼", + "admin.askPasswordPlaceholder": "輸入提問密碼", + "admin.account": "帳號設定", + "admin.exportHint": "您可以匯出您在 %s 中的所有個人資料,包括你的基本資訊、收到的問題以及回答。", + "admin.exportJSON": "導出全部資料(JSON)", + "admin.exportJSONHint": "包含提問、回答、追問與私聊記錄,可完整備份或遷移。", + "admin.deactivate": "停用我的帳號", + "admin.deactivateHint": "您隨時可以選擇停用您的帳號。停用後,您的帳號將無法登入,您的提問箱頁面以及提問將無法訪問,其他人也無法再給您發送新的提問。該操作無法撤銷!請謹慎操作!", + "admin.socialRequired": "請填寫連結或取消勾選", + + // 問題管理頁 + "qlist.title": "我的提問", + "qlist.answered": "已回答", + "qlist.pending": "待回答", + "qlist.private": "私密", + "qlist.empty": "還沒有提問,快把提問箱分享出去吧~", + "qlist.action": "操作", + "qlist.answerNow": "去回答", + "qlist.sort": "排序", + "qlist.status": "狀態", + "qlist.type": "類型", + "qlist.latest": "最新", + "qlist.oldest": "最早", + "qlist.all": "全部", + "qlist.public": "一般提問", + "qlist.privateQuestion": "私密提問", + "qlist.received": "我收到的提問", + "qlist.myChats": "我發起的私聊", + "qlist.statsTotal": "總提問數", + "qlist.statsAnswered": "已回答", + "qlist.statsUnanswered": "未回答", + "qlist.statsPrivate": "私密提問", + "qlist.statsPinned": "置頂", + "qlist.statsChats": "私聊會話", + "qlist.searchPlaceholder": "搜尋問題或回答內容...", + "qlist.searchBtn": "搜尋", + "qlist.searchClear": "清除搜尋", + "qlist.questionsTab": "提問", + "qlist.votesTab": "投票", + "qlist.chatsTab": "私聊", + "qlist.receivedChats": "我收到的私聊", + "qlist.chatEmpty": "還沒有私聊,把提問箱分享出去讓大家來私聊吧~", + "qlist.pinnedShort": "置頂", + "qlist.privateShort": "私密", + "qlist.chatStatsTotal": "總私聊", + "qlist.chatStatsReceived": "我收到的", + "qlist.chatStatsInitiated": "我發起的", + "qlist.chatStatsClosed": "已關閉", + "qlist.unansweredShort": "待答", + "qlist.readShort": "已讀", + "qlist.unreadShort": "未讀", + "qitem.markReadShort": "標記", + "qlist.pinShort": "置頂", + "qlist.unpinShort": "取消置頂", + "qlist.myVotes": "我建立的投票", + "qlist.loadMore": "載入更多", + "qlist.newVote": "新建投票", + "qlist.edit": "編輯", + "qlist.untitledVote": "未命名投票", + "qlist.blocked": "已拉黑", + "qlist.unanswered": "未回答", + + // 站點 Logo 後綴 + "site.logoSuffix": "的提問箱", + "site.stats": "提問箱資訊統計", + + // 驗證碼彈窗 + "captcha.title": "人機驗證", + "captcha.hint": "請計算下方的算術題以驗證你不是機器人", + "captcha.refresh": "換一題", + "captcha.submit": "驗證並送出", + "captcha.loading": "載入中...", + "captcha.loadFailed": "載入失敗", + "captcha.loadRetry": "載入失敗,請重試", + "captcha.inputAnswer": "請輸入答案", + "captcha.wrongAnswer": "答案錯誤,請重新計算", + "captcha.verifyFailed": "驗證失敗,請重試", + + // 註冊頁補充 + "auth.register.domain.prefix": "個性網域(你的問答箱網址將會是:%s + ", + "auth.register.domain.suffix": " + 你在下面文字框中填寫的內容)", + "auth.register.confirm": "確認密碼", + "auth.register.language": "介面語言", + "auth.register.languageDefault": "跟隨站點預設", + "auth.register.success": "註冊成功,歡迎來到 狼的提問箱!", + + // 探索頁補充 + "explore.recommend": "隨機推薦", + "explore.search": "搜尋標籤...", + "explore.sortLatest": "最新加入", + "explore.sortOldest": "最早加入", + "explore.noTags": "無標籤", + "explore.noRecommend": "暫無推薦用戶", + "explore.hotTags": "熱門標籤", + "explore.hotQuestions": "熱門問題", + "explore.noResult": "暫無符合條件的用戶。", + "explore.lazy": "這個人很懶,什麼都沒寫~", + "explore.prevPage": "上一頁", + "explore.nextPage": "下一頁", + "explore.loading": "載入中...", + "explore.loadFailed": "載入失敗", + + // 提問箱密碼頁 + "password.title": "此提問箱需要密碼", + "password.desc": "此提問箱已設定存取密碼,請輸入密碼查看內容", + "password.input": "請輸入存取密碼", + "password.enter": "驗證進入", + "password.submit": "確認", + + // 問題不存在 + "qitem.notFound": "問題不存在或已被刪除", + + // 聊天頁 + "chat.title": "私聊", + "chat.input": "輸入訊息...", + "chat.send": "傳送", + "chat.delete": "刪除對話", + "chat.block": "封鎖對方", + "chat.unblock": "取消封鎖", + "chat.empty": "還沒有訊息,說點什麼吧~", + "chat.withAsker": "與提問者的私聊", + "chat.withUser": "與 %s 的私聊", + "chat.closed": "對話已關閉", + "chat.closedNoSend": "對話已關閉,無法發送新訊息", + "chat.remaining": "訊息剩餘:%d 條(共 %d 條)", + "chat.me": "我", + "chat.other": "對方", + "chat.userBlocked": "該使用者已被拉黑", + "chat.addImage": "新增圖片(可選,最大5MB)", + "chat.confirm": "確認", + "chat.confirmBlock": "確定要拉黑該使用者嗎?他將無法再發送私訊。", + "chat.confirmUnblock": "確定要取消封鎖該使用者嗎?他將可以再次發送私訊。", + "chat.deleteConfirm": "確定要刪除這條私聊對話嗎?對方將無法再看到此對話,且操作不可恢復。", + "maintenance.title": "NekoBox 維護中...", + "maintenance.desc": "NekoBox 正在進行維護,服務暫時不可用。過一會再來吧~", + + // 單題分享(v4) + "qitem.shareCard": "分享此提問", + + // 追問(v4) + "followup.title": "追問記錄", + "followup.content": "追問:", + "followup.answerPlaceholder": "回答這條追問...", + "followup.answerBtn": "回答追問", + "followup.waiting": "等待回答中...", + "followup.askMore": "繼續追問", + "followup.remaining": "還可追問 %d / %d 次", + "followup.contentPlaceholder": "補充你的問題...", + "followup.waitingReply": "你的追加提問已發出,等待提問箱主人回覆中...", + "followup.submit": "提交追問", + + // 置頂(v4) + "qlist.pinned": "置頂中", + "qlist.pin": "置頂", + "qlist.unpin": "取消置頂", + "qlist.readStatus": "閱讀狀態", + "qlist.read": "已讀", + "qlist.unread": "未讀", + "qlist.statsRead": "已讀", + "qlist.statsUnread": "未讀", + + // 提問成功頁(v4) + "success.title": "提問發送成功!", + "success.yourQuestion": "你的提問:", + "success.emailSent": "已向你的信箱發送了該提問的私密連結,也可以使用下方連結隨時查看提問、接收回答與繼續追問。", + "success.saveLink": "請務必保存下面的私密連結!由於你沒有留下信箱,此連結(含口令 Token)是你查看提問、接收回答與繼續追問的唯一憑證,遺失後將無法找回。", + "success.privateLink": "你的提問私密連結(點擊複製保存)", + "success.copy": "複製", + "success.copied": "已複製 ✓", + "success.copyFailed": "複製失敗", + "success.token": "口令 Token:%s(提問人憑 Token 存取私密連結)", + "success.viewQuestion": "查看我的提問", + "success.backToBox": "返回%s的提問箱", + "success.pageTitle": "提問成功 - %s", + + // 停用頁 + "deactivate.title": "帳號停用", + "deactivate.desc": "停用後你的提問箱將無法存取,且所有資料將被刪除,此操作不可恢復!", + "deactivate.confirm": "我確認要停用帳號", + "deactivate.submit": "停用帳號", + + // 匿名投票 + "nav.votes": "投票", + + "common.back": "返回", + + "vote.listTitle": "投票管理", + "vote.newTitle": "新建投票", + "vote.editTitle": "編輯投票", + "vote.resultsTitle": "投票結果", + "vote.statsTotal": "投票總數", + "vote.statsPublished": "進行中", + "vote.createNew": "新建投票", + "vote.typeSingle": "單選", + "vote.typeMultiple": "多選", + "vote.typeRating": "評分", + "vote.typeRank": "排序", + "vote.typeForm": "表單收集", + "vote.statusNotStarted": "未開始", + "vote.statusDraft": "草稿", + "vote.statusPublished": "進行中", + "vote.statusEnded": "已結束", + "vote.statusArchived": "已歸檔", + "vote.participants": "參與", + "vote.remainLabel": "剩餘", + "vote.perpetual": "無限期", + "vote.durationDay": "天", + "vote.durationHour": "小時", + "vote.durationMinute": "分鐘", + "vote.createdAt": "建立於", + "vote.edit": "編輯", + "vote.results": "結果", + "vote.preview": "預覽", + "vote.page.mustComplete": "請完成", + "vote.page.rankHintRequired": "排名 1-N(必填)", + "vote.page.rankHintOptional": "排名 1-N(可選,可只排部分)", + "vote.page.previewHint": "預覽模式:這是發布前的頁面範例,提交已停用", + "vote.page.previewSubmitHint": "預覽模式,發布後即可提交", + "vote.publish": "發布", + "vote.close": "結束", + "vote.share": "複製連結", + "vote.copied": "已複製", + "vote.shareURL": "投票分享連結", + "vote.confirmPublish": "確定發布該投票嗎?發布後即產生可分享連結。", + "vote.confirmClose": "確定結束該投票嗎?結束後參與者將無法再投票。", + "vote.confirmDelete": "確定刪除該投票嗎?投票資料將一併刪除,不可復原!", + "vote.manageEntry": "管理投票", + + "vote.manageTitle": "管理投票", + "vote.manageDesc": "建立與管理你的匿名投票", "vote.empty": "還沒有投票,點擊右上角\"新建投票\"開始吧~", + "vote.formLockedHint": "該投票已發布,僅可修改基本資訊;類型與選項已鎖定(避免破壞已收集的投票資料)", + "vote.formBasic": "基本設定", + "vote.formTitle": "投票標題", + "vote.formTitlePlaceholder": "例如:今天吃什麼?", + "vote.formDescription": "描述 / 說明", + "vote.formDescriptionPlaceholder": "補充說明(可選)", + "vote.formType": "投票類型", + "vote.formVisibility": "展示方式", + "vote.formVisibilityPublic": "公開展示(探索頁 + 提問箱頁)", + "vote.formVisibilityLinkOnly": "僅連結分享", + "vote.formVoterScope": "投票範圍", + "vote.formVoterScopeAnyone": "任何人(含匿名)", + "vote.formVoterScopeRegistered": "僅註冊用戶", + "vote.formShowResult": "結果可見時機", + "vote.formShowResultAfterVote": "投票後立即可見", + "vote.formShowResultAfterEnd": "結束後可見", + "vote.formShowResultOwnerOnly": "僅我可見", + "vote.formStartAt": "開始時間(留空立即開始)", + "vote.formEndAt": "結束時間(留空不限制)", + "vote.formMaxChoices": "最多可選數量", + "vote.formMaxVotesPerFingerprint": "每個投票每個裝置限 1 次,使用同一瀏覽器重複提交將被攔截。", + "vote.formMaxVotesPerAccount": "每個投票每個註冊帳號限 1 次,使用同一帳號重複提交將被攔截。", + "vote.formAllowCustom": "允許參與者補充自訂選項", + "vote.formRequireCaptcha": "匿名投票需通過驗證碼", + "vote.formOptions": "投票選項", + "vote.formRatingHint": "評分題無需設定選項(1-10 分)", + "vote.addOption": "新增選項", + "vote.optionPlaceholder": "選項內容", + "vote.formFields": "表單欄位", + "vote.addField": "新增欄位", + "vote.field": "欄位", + "vote.formFieldType": "欄位類型", + "vote.fieldTypeText": "單行文字", + "vote.fieldTypeTextarea": "多行文字", + "vote.fieldTypeSelect": "下拉選擇", + "vote.fieldTypeRadio": "單選", + "vote.fieldTypeCheckbox": "多選", + "vote.fieldTypeNumber": "數字", + "vote.fieldTypeRank": "排序", + "vote.page.selectPlaceholder": "請選擇", + "vote.page.avgNumber": "平均", + "vote.page.fieldFilled": "已填寫", + "vote.fieldTypeRating": "評分", + "vote.formFieldLabel": "欄位標籤", + "vote.formFieldRequired": "必填", + "vote.formFieldMaxLength": "字數上限(0 不限制)", + "vote.formFieldOptions": "選項", + "vote.formFieldOptionsHint": "點擊下方「新增選項」逐條新增,不需用逗號分隔", + "vote.fieldAllowCustom": "允許補充自訂選項", + "vote.formFieldOptionsPlaceholder": "如:滿意,一般,不滿意", + "vote.createDraft": "儲存草稿", + "vote.builderHintOptions": "至少需要 2 個選項", + "vote.builderHintFields": "請至少新增 1 個欄位", + "vote.builderHintFieldOptions": "選擇題/排序題請填寫選項(排序題至少 2 個)", + "vote.resultsAnswered": "回答數", + "vote.page.rankedTimes": "被排次數", + "vote.resultsTotal": "總參與人數", + "vote.resultsSubmissions": "表單回覆", + "vote.resultsViewTexts": "查看文字提交", + "vote.resultsToggleHint": "點擊展開或收起文字回覆明細", + "vote.resultsOptions": "投票結果", + "vote.resultsVotes": "票", + "vote.export": "匯出 CSV", + "vote.resultsEmpty": "還沒有人參與,快來分享吧~", + + // 匿名投票參與頁 + "vote.inlineTitle": "投票", + "vote.page.by": "發起的投票", + "vote.page.goVote": "去投票", + "vote.page.notStarted": "未開始", + "vote.page.notStartedHint": "該投票尚未開始,敬請期待~", + "vote.page.ended": "已結束", + "vote.page.endedHint": "該投票已結束", + "vote.page.active": "進行中", + "vote.page.participated": "已參與", + "vote.page.loginRequired": "該投票僅限註冊用戶參與,請先登入。", + "vote.page.anonymousHint": "該投票允許匿名參與,你的身分不會被記錄(同一裝置最多可參與 1 次)。", + "vote.page.submit": "提交投票", + "vote.page.alreadyVoted": "你已參與過該投票,感謝參與!", + "vote.page.resultsTitle": "投票結果", + "vote.page.totalVotes": "總參與", + "vote.page.avgRating": "平均分", + "vote.page.avgRank": "平均排名", + "vote.page.optionColumn": "選項", + "vote.page.ratingLabel": "請評分", + "vote.page.ratingUnit": "分", + "vote.page.rankHint": "請為每個選項填寫 1-N 的排名(數字越小越靠前,不可重複)", + "vote.page.rankPlaceholder": "排名", + "vote.page.multipleHint": "可多選", + "vote.page.customOption": "補充選項(可選)", + "vote.page.customPlaceholder": "填寫你心中的其他選項", + "vote.page.customOther": "其他", + "vote.page.customFieldPlaceholder": "填寫自訂選項…", + "vote.page.customStats": "自訂補充選項", + "vote.page.formCount": "已收到回覆", + "vote.page.ownerManage": "管理此投票(僅你可見結果)", + + // 單份投票的定量收集 + "vote.formQuotaLimit": "收集上限(份)", + "vote.formQuotaHint": "0 表示不限制;收集到指定份數後自動結束該投票。", + "vote.flash.notFound": "該投票不存在或已失效", + "vote.flash.notPublished": "該投票尚未發布", + "vote.flash.archived": "該投票已歸檔,無法參與", + "vote.flash.ended": "該投票已結束", + "vote.flash.notStarted": "該投票尚未開始", + "vote.flash.success": "投票成功!感謝參與", + "vote.err.noChoice": "請至少選擇一個選項", + "vote.err.tooManyChoices": "最多只能選擇 %d 個選項", + "vote.err.pickOne": "請選擇一個選項", + "vote.err.invalidOption": "存在無效的選項", + "vote.err.optionDuplicate": "選項不能重複選擇", + "vote.err.ratingRequired": "請給出 1-10 分的評分", + "vote.err.rankRequired": "請為每個選項填寫 1-%d 的排名", + "vote.err.rankDuplicate": "排名不能重複", + "vote.err.fieldRequired": "請填寫「%s」", + "vote.err.fieldCustomRequired": "請填寫「%s」的自訂選項", + "vote.err.fieldCustomTooLong": "「%s」的自訂選項不能超過 %d 字", + "vote.err.fieldInvalidOption": "「%s」的選項無效", + "vote.err.fieldConfigError": "「%s」選項配置錯誤", + "vote.err.fieldRankIncomplete": "請填寫「%s」的完整排名", + "vote.err.fieldRankRange": "「%s」排名必須是 1-%d 之間的數字", + "vote.err.fieldRankDuplicate": "「%s」排名不能重複", + "vote.err.fieldTooLong": "「%s」超出字數限制(最多 %d 字)", + "vote.err.fieldNotNumber": "「%s」必須是數字", + "vote.err.fieldRating": "「%s」請給出 1-10 分的評分", + "vote.err.unknownType": "未知的投票類型", + "vote.err.customTooLong": "自訂選項不能超過 %d 字", + "vote.err.blockWords": "提交內容中包含了投票發起人設定的屏蔽詞,無法提交", + "vote.err.serialize": "提交內容序列化失敗", + "captcha.error": "驗證碼錯誤", + "captcha.errEmpty": "驗證碼不能為空", + "captcha.errFormat": "驗證碼格式錯誤,請重新整理後重試", + "captcha.errAnswerFormat": "驗證碼答案格式錯誤", + "captcha.errExpired": "驗證碼已過期,請重新整理後重試", + "captcha.errService": "驗證碼服務異常,請稍後再試", + "captcha.errAnswerWrong": "驗證碼答案錯誤", + "censor.unavailable": "內容審核服務暫時不可用,請稍後再試", + + // 功能管理:提問 / 私聊 / 投票 的開關、定時開關與定量收集 + "admin.tabAccount": "用戶設定", + "admin.featuresHint": "在「提問 / 私聊 / 投票」面板中管理各功能的開關、開放時段與收集上限;達到上限後對應功能自動關閉。", + "admin.featuresEntry": "設定", + "admin.featureHint.question": "關閉後訪客無法提交新提問;達到收集上限後自動停止接收(含私密提問)。", + "admin.featureHint.chat": "關閉後訪客無法發起新的私聊;已有會話不受影響。", + "admin.featureHint.vote": "關閉後提問箱頁不再展示投票板塊,訪客也無法參與你的投票。單份投票可在編輯頁單獨設定收集上限。", + "admin.featureEnabled": "啟用該功能", + "admin.featureOpenAt": "定時開放", + "admin.featureCloseAt": "定時關閉", + "admin.featureTimeHint": "留空表示不限制;開放時間之前、關閉時間之後該功能均不可用。", + "admin.featureSchedule": "循環定時(每週循環)", + "admin.featureScheduleStart": "每日開始", + "admin.featureScheduleEnd": "每日結束", + "admin.featureScheduleHint": "勾選每週固定開放日並設定每日時間段,按週循環生效;全部留空表示不啟用。只填開放日(不填時間)表示該天全天開放;只填時間(不勾選任何日)表示每天該時段開放。", + "admin.featureMode": "收集模式", + "admin.featureModeAlways": "長期開放", + "admin.featureModeWindow": "定時收集", + "admin.featureModeRecurring": "循環定時", + "admin.featureModeHint": "長期開放:不限時間,保持開放直到手動關閉;定時收集:一次性開放 / 關閉時間視窗;循環定時:每週固定開放日循環生效。三種模式互斥,儲存時未選模式的設定將被清空。", + "admin.featureQuotaLimit": "收集上限(條 / 份)", + "admin.featureQuotaHint": "0 表示不限制;累計收集達到上限後自動關閉,重設計數後可開啟下一輪。", + "admin.featureQuotaCount": "已收集", + "admin.featureQuotaUnlimited": "不限制", + "admin.featureQuotaResetAt": "上次重設:", + "admin.featureResetQuota": "重設計數", + "admin.featureSave": "儲存該功能設定", + + // 功能管理:狀態與提示 + "feature.name.question": "提問", + "feature.name.chat": "私聊", + "feature.name.vote": "投票", + "feature.statusOpen": "進行中", + "feature.status.disabled": "已關閉", + "feature.status.not_started": "未開始", + "feature.status.ended": "已結束", + "feature.status.quota_reached": "已達上限", + "feature.saved": "功能設定已儲存", + "feature.errTime": "%s 的時間格式不正確,請使用日期時間選擇器", + "feature.errTimeRange": "%s 的定時關閉時間必須晚於定時開放時間", + "feature.errQuota": "%s 的收集上限需為 0 到 1000000 之間的整數", + "feature.errInvalid": "未知的功能類型", + "feature.quotaReset": "%s 的收集計數已重設", + "feature.errScheduleHalf": "%s 的循環定時開始與結束時間必須同時填寫", + "feature.errScheduleTime": "%s 的循環定時時間格式不正確,請使用時間選擇器", + "feature.errScheduleRange": "%s 的循環定時結束時間必須晚於開始時間", + + // 功能關閉時對訪客的提示 + "feature.disabled.question": "提問箱主人已關閉提問功能", + "feature.disabled.chat": "該提問箱未開啟私聊功能", + "feature.disabled.vote": "該提問箱已關閉投票功能", + "feature.not_started.question": "提問功能尚未開放", + "feature.not_started.chat": "私聊功能尚未開放", + "feature.not_started.vote": "投票功能尚未開放", + "feature.ended.question": "提問功能已結束收集", + "feature.ended.chat": "私聊功能已結束", + "feature.ended.vote": "投票功能已結束", + "feature.quota_reached.question": "提問功能已達到收集上限", + "feature.quota_reached.chat": "私聊功能已達到收集上限", + "feature.quota_reached.vote": "投票功能已達到收集上限", + + // 認證:訪客可見的提示(P0) + "auth.errBadCredential": "郵箱或密碼錯誤", + "auth.errUserNotFound": "使用者不存在", + "auth.errEmailFrequent": "郵件發送太頻繁,請稍後再試", + "auth.errEmailFailed": "郵件發送失敗,請稍後再試", + "auth.errCodeExpired": "驗證碼已過期", + "auth.errPasswordChanged": "密碼修改成功", + "auth.errLoginRequired": "請先登入", + "auth.errDuplicateEmail": "該郵箱已被註冊", + "auth.errDuplicateDomain": "該個性網域已被使用", + + // 提問箱頁:訪客可見(P0) + "question.errWrongPassword": "密碼錯誤", + "question.errAskPasswordWrong": "提問密碼錯誤", + "question.errLoginRequired": "提問箱的主人設定了僅註冊使用者才能提問,請先登入。", + "question.errSelfChat": "不能給自己發起私聊", + "question.errBlockedChat": "你已被對方封鎖,無法發起私聊", + "question.errChatDailyLimit": "你今日已達發送上限(%d則),請明天再試", + "question.errDuplicateSubmit": "偵測到重複提交,請稍後再試", + "question.errImageTooLarge": "圖片檔案大小不能大於 5Mb", + "question.errUploadImageFailed": "上傳圖片失敗", + "question.errBlockWords": "提問內容包含了提問箱主人設定的屏蔽詞,發送失敗", + "question.errAnsweredLocked": "已回答的問題不能標記為未讀", + "question.flash.chatSent": "私聊請求已發送!你可以透過以下連結查看對話:%s", + "question.flash.answered": "回答發布成功!", + "question.flash.operated": "操作成功", + "question.flash.markedRead": "已標記為已讀", + "question.flash.markedUnread": "已標記為未讀", + + // 追問:訪客/箱主可見(P0) + "followup.errNoPermission": "無權操作", + "followup.errNotAnswered": "問題尚未被回答,暫時不能追問", + "followup.errLimit": "每條提問最多追問 %d 次,已達上限", + "followup.errWaitReply": "請等待主人回覆上一條追問後再繼續追問", + "followup.errNotFound": "追問不存在", + "followup.flash.sent": "追問發送成功!", + "followup.flash.answered": "回答成功!", + + // 後台設定:箱主可見(P1) + "admin.flash.profileUpdated": "更新個人資訊成功", + "admin.flash.chatUpdated": "私聊設定更新成功", + "admin.flash.pagePwdOff": "已關閉頁面密碼存取", + "admin.flash.pagePwdUpdated": "頁面存取密碼已更新", + "admin.flash.askPwdOff": "已關閉提問密碼", + "admin.flash.askPwdUpdated": "提問密碼已更新", + "admin.flash.tagsTooMany": "標籤不能超過 5 個", + "admin.flash.tagsUpdated": "更新標籤成功", + "admin.flash.tagTooLong": "每個標籤不能超過 5 個字元:%s", + "admin.flash.blockWordsTooMany": "屏蔽詞不能超過 10 個", + "admin.flash.blockWordTooLong": "屏蔽詞長度不能超過 10 個字元:%s", + "admin.flash.harassmentUpdated": "更新防騷擾設定成功", + "admin.flash.blockWordsUpdated": "屏蔽詞已更新", + "admin.flash.deactivated": "您的帳號已停用,感謝您使用 狼的提問箱。期待未來還能再見 👋🏻", + "admin.export.errUser": "匯出失敗:獲取使用者資訊失敗", + "admin.export.errQuestion": "匯出失敗:獲取問題資訊失敗", + + // 投票管理:箱主可見(P1) + "vote.err.invalidID": "無效的投票 ID", + "vote.err.notExist": "投票不存在", + "vote.err.noPermission": "無權操作該投票", + "vote.err.type": "未知的投票類型", + "vote.err.titleRequired": "請填寫投票標題", + "vote.err.titleTooLong": "投票標題不能超過 100 字", + "vote.err.visibility": "未知的可見性設定", + "vote.err.voterScope": "未知的投票範圍設定", + "vote.err.showResult": "未知的結果展示設定", + "vote.err.timeRange": "結束時間必須晚於開始時間", + "vote.err.quota": "收集上限需為 0 到 1000000 之間的整數", + "vote.err.optionsTooFew": "請至少新增 2 個選項", + "vote.err.optionsFormat": "選項資料格式錯誤", + "vote.err.optionTooLong": "單個選項內容不能超過 %d 字", + "vote.err.maxChoicesExceed": "最多可選數量不能超過選項總數", + "vote.err.fieldsTooFew": "請至少新增 1 個表單欄位", + "vote.err.fieldsFormat": "表單欄位資料格式錯誤", + "vote.err.fieldsTooMany": "表單欄位不能超過 50 個", + "vote.err.fieldType": "存在未知的表單欄位類型", + "vote.err.fieldLabelMissing": "第 %d 個欄位缺少標籤", + "vote.err.fieldLabelTooLong": "第 %d 個欄位的標籤不能超過 100 字", + "vote.err.fieldLabelDuplicate": "欄位標籤「%s」重複,請使用不同的標籤", + "vote.err.fieldMaxLength": "第 %d 個欄位的字數上限需在 0-2000 之間", + "vote.err.fieldReservedOption": "第 %d 個欄位(%s)的選項內容包含保留值,請更換", + "vote.err.fieldOptionsTooFew": "第 %d 個欄位(%s)請至少填寫 1 個選項", + "vote.err.fieldRankTooFew": "第 %d 個欄位(%s)排序題至少需要 2 個選項", + "vote.err.fieldSerialize": "欄位選項序列化失敗", + "vote.err.editClosed": "已結束或歸檔的投票不允許編輯", + "vote.err.publishDraftOnly": "只有草稿狀態的投票可以發布", + "vote.err.closePublishedOnly": "只有進行中的投票可以結束", + "vote.err.publishTitleRequired": "請先填寫投票標題再發布", + "vote.err.publishFormFieldsRequired": "表單類型投票至少需要 1 個欄位", + "vote.err.publishOptionsRequired": "選項投票至少需要 2 個選項", + "vote.err.optionUpdateFailed": "選項更新失敗,請重試", + "vote.err.fieldUpdateFailed": "表單欄位更新失敗,請重試", + "vote.flash.published": "投票已發布!分享連結:%s", + "vote.flash.updated": "投票資訊已更新(進行中的投票不可修改類型與選項)", + "vote.flash.draftSaved": "已儲存到草稿", + "vote.flash.closed": "投票已結束", + "vote.flash.deleted": "投票已刪除", + "vote.err.timeFormat": "時間格式不正確,請使用日期時間選擇器", + "vote.err.maxChoicesLimit": "最多可選數量不能超過 20", + "vote.err.descriptionTooLong": "投票描述不能超過 5000 字", + "profile.err.avatarTooLarge": "頭像檔案太大,最大支援 2MB", + "profile.err.backgroundTooLarge": "背景圖檔案太大,最大支援 2MB", + "profile.err.newPasswordTooShort": "新密碼長度不能少於 8 位", + "profile.err.badOldPassword": "舊密碼輸入錯誤", + "admin.export.errCreateExcel": "匯出失敗:建立Excel檔案失敗", + "admin.export.errWriteExcel": "匯出失敗:寫入Excel檔案失敗", + + // profile 設定頁 UI 重構:卡片分區 / 頭像背景裁切 / 改密強制登出 + "profile.card.basic": "基本資料", + "profile.card.avatarBg": "頭像與背景", + "profile.card.qr": "二維碼樣式", + "profile.card.password": "修改密碼", + "profile.avatarCropHint": "裁切框已鎖定為 1:1 正方形", + "profile.backgroundCropHint": "裁切框已鎖定為 16:9 寬螢幕", + "profile.cropTitle": "裁切圖片", + "profile.cropConfirm": "確認裁切", + "profile.err.avatarRatio": "頭像圖片必須為 1:1 正方形,請裁切後再上傳", + "profile.err.backgroundRatio": "背景圖片必須為 16:9 寬高比,請裁切後再上傳", + "profile.flash.passwordChanged": "密碼修改成功,已登出,請使用新密碼重新登入", + "profile.pwdNote": "儲存後目前工作階段立即失效,需使用新密碼重新登入", + "profile.pickAvatar": "更換頭像", + "profile.pickBackground": "更換背景", + "profile.saveBasic": "儲存基本資料", + "profile.saveMedia": "儲存頭像與背景", + "profile.savePassword": "確認修改密碼", + "profile.saveQR": "儲存 QR Code 樣式", + "profile.saveSocial": "儲存社交連結", + "profile.err.cropLibUnavailable": "圖片裁切元件載入失敗,請重新整理頁面後重試", + + // 驗證碼 JSON 介面:前端消費(P2) + "captcha.json.badRequest": "請求格式錯誤", + "captcha.json.idRequired": "驗證碼 ID 不能為空", + "captcha.json.genFailed": "生成驗證碼失敗", + "chat.errDeletedByOwner": "該私聊對話已被對方刪除。", + "chat.errBlockedView": "你已被對方拉黑,無法查看該私聊", + "chat.errEmpty": "消息不能為空", + "chat.errTooLong": "消息內容過長,請控制在 %d 字以內", + "chat.errConvDeletedSend": "該對話已被刪除,無法發送消息", + "chat.errBlockedSend": "你已被對方拉黑,無法發送私信", + "chat.errBlockWords": "訊息中包含了提問箱主人設定的屏蔽詞,無法傳送", + "chat.errDailyLimit": "你今日已達發送上限(%d條),請明天再試", + "chat.errLimitReached": "對話已達到上限,無法發送新消息", + "chat.errChatClosed": "該箱主已關閉私聊功能,無法發送消息", + "chat.errImageTooLarge": "圖片大小不能超過 %dMB", + "chat.errUploadFailed": "圖片上傳失敗,請稍後重試", + "chat.errNoPermission": "無權執行此操作", + "chat.flash.sent": "消息發送成功", + "chat.flash.deleted": "私聊對話已刪除", + "chat.flash.operated": "操作成功", + "image.errTooLarge": "圖片尺寸過大,最大支援 %d×%d 像素,請壓縮後重新上傳", + "internal.errFlash": "服務內部錯誤,請稍後重試。", + "internal.errServer": "伺服器內部錯誤", + "home.errStats": "獲取統計資訊失敗", + "pixel.errPath": "非法的請求路徑", + "proxy.errNotFound": "頁面不存在", + "proxy.errInternal": "服務網關內部錯誤", + "explore.errRandomUser": "獲取隨機用戶失敗", + // 表单校验 + "form.answer.content": "回答內容不能為空", + "form.answer.contentTooLong": "回答內容不能超過 %d 個字元", + "form.email.required": "請填寫有效的電子郵件地址", + "form.followup.answer": "追問回答不能為空", + "form.followup.answerTooLong": "追問回答不能超過 %d 個字元", + "form.followup.content": "追問內容不能為空", + "form.followup.contentTooLong": "追問內容不能超過 %d 個字元", + "form.login.password": "請輸入密碼", + "form.profile.backgroundimagealpha": "請填寫 QR Code 背景透明度", + "form.profile.colorHex": "請填寫 7 位十六進制顏色代碼(含 #)", + "form.profile.dotscale": "請填寫 QR Code 點大小", + "form.profile.intro": "個人介紹不能為空,且不超過 100 個字元", + "form.profile.linkMax": "主頁連結長度不能超過 30 個字元", + "form.profile.name": "暱稱不能為空,且不超過 20 個字元", + "form.profile.newPassword": "新密碼長度不能超過 30 個字元", + "form.profile.passwordMax": "密碼長度不能超過 30 個字元", + "form.question.content": "問題內容不能為空", + "form.question.contentTooLong": "問題內容不能超過 %d 個字元", + "form.question.receiveReplyEmail": "請填寫有效的電子郵件地址以接收回覆", + "form.recaptcha": "請完成人機驗證", + "form.recover.newPassword": "請設定 8 至 30 位的新密碼", + "form.recover.repeatPassword": "兩次輸入的新密碼不一致", + "form.register.domain": "個性網域只能包含字母、數字與底線,長度為 3 至 20 位", + "form.register.email": "請填寫有效的電子郵件地址(不超過 100 個字元)", + "form.register.name": "暱稱不能為空,且不超過 20 個字元", + "form.register.password": "請設定 8 至 30 位的密碼", + "form.register.recaptcha": "無法人機驗證,請重新整理頁面或更換網路後重試", + "form.register.repeatPassword": "兩次輸入的密碼不一致", +} diff --git a/.workbuddy/backup/remove-vercount-20260906/footer.html b/.workbuddy/backup/remove-vercount-20260906/footer.html new file mode 100644 index 0000000..0536a82 --- /dev/null +++ b/.workbuddy/backup/remove-vercount-20260906/footer.html @@ -0,0 +1,79 @@ +

+ {{t .LangCode "site.footer.visitor" `` | safe}} | {{t .LangCode "site.footer.pageview" `` | safe}} +
Powered by NekoBox | {{ ICP }}
{{t .LangCode "site.footer.runtime"}}: +
+ + {{t .LangCode "site.footer.admin"}} + | {{t .LangCode "site.footer.notice"}} + | {{t .LangCode "site.footer.chat"}} + | {{t .LangCode "site.footer.drive"}} + | {{t .LangCode "site.footer.status"}} + | {{t .LangCode "site.footer.nav"}} +

+
+
+ + + + diff --git a/.workbuddy/backup/remove-vercount-20260906/header.html b/.workbuddy/backup/remove-vercount-20260906/header.html new file mode 100644 index 0000000..6518b98 --- /dev/null +++ b/.workbuddy/backup/remove-vercount-20260906/header.html @@ -0,0 +1,1044 @@ + + + + + + {{ .Title }} + + + + + + + + + + + + + + + + + + {{ if .VConsole }} + + + {{ end }} + + + + + + {{ if eq .CaptchaType "math" }} + + + {{ else if .RecaptchaTurnstileStyle }} + + + {{ else }} + + + {{ end }} + {{ if ne SentryDSN "" }} + + + {{ end }} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {{ if .NoIndex }}{{ end }} + {{ if .IsUserPage }} + + + + + + + + + {{ else }} + + + + + + + {{ end }} + + + + + + + + + + + + + +
+ {{ if not .IsUserPage }} + + {{ end }} + +
+ + + +{{ if .IsPixel }} +
+{{ else }} +
+{{ end }} + +{{ if eq .CaptchaType "math" }} +
+
+

{{t .LangCode "captcha.title"}}

+

{{t .LangCode "captcha.hint"}}

+
+ {{t .LangCode "captcha.loading"}} + +
+
+ +
+ +
+ + +
+
+
+ + + + +{{ end }} \ No newline at end of file diff --git a/.workbuddy/backup/remove-vercount-20260906/i18n_test.go b/.workbuddy/backup/remove-vercount-20260906/i18n_test.go new file mode 100644 index 0000000..e16347b --- /dev/null +++ b/.workbuddy/backup/remove-vercount-20260906/i18n_test.go @@ -0,0 +1,76 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package i18n + +import ( + "testing" +) + +// TestDictionaryComplete 校验四种语言的字典 key 完全一致,防止漏翻译。 +func TestDictionaryComplete(t *testing.T) { + ref := dictionary[LangZhCN] + langs := []string{LangZhTW, LangEn, LangJa} + + for _, lang := range langs { + dict := dictionary[lang] + if len(dict) != len(ref) { + t.Errorf("%s: 词条数量 %d != 简体中文 %d", lang, len(dict), len(ref)) + } + for key := range ref { + if _, ok := dict[key]; !ok { + t.Errorf("%s: 缺少词条 %q", lang, key) + } + } + for key := range dict { + if _, ok := ref[key]; !ok { + t.Errorf("%s: 多出简体中文没有的词条 %q", lang, key) + } + } + } +} + +func TestResolve(t *testing.T) { + cases := map[string]string{ + "": LangZhCN, + "zh-cn": LangZhCN, + "zh": LangZhCN, + "zh-TW": LangZhTW, + "zh-Hant": LangZhTW, + "en": LangEn, + "en-US": LangEn, + "ja": LangJa, + "ja-JP": LangJa, + "fr": LangZhCN, // 未知回退 + " En ": LangEn, // 自动去除首尾空白 + "zh_cn": LangZhCN, + "zh_tw": LangZhTW, + "zh_hk": LangZhTW, // 香港繁体(下划线变体) + } + for in, want := range cases { + if got := Resolve(in); got != want { + t.Errorf("Resolve(%q) = %q, want %q", in, got, want) + } + } +} + +func TestT(t *testing.T) { + if got := T(LangZhCN, "nav.explore"); got != "探索" { + t.Errorf("zh-CN nav.explore = %q", got) + } + if got := T(LangEn, "nav.explore"); got != "Explore" { + t.Errorf("en nav.explore = %q", got) + } + if got := T(LangJa, "nav.explore"); got != "探索" { + t.Errorf("ja nav.explore = %q", got) + } + // 参数填充 + if got := T(LangEn, "site.footer.visitor", "42"); got != "You are visitor #42" { + t.Errorf("en site.footer.visitor with arg = %q", got) + } + // 未知 key 回退返回 key 本身 + if got := T(LangEn, "no.such.key"); got != "no.such.key" { + t.Errorf("unknown key = %q", got) + } +} diff --git a/.workbuddy/backup/remove-vercount-20260906/tamabox.changelogs.json b/.workbuddy/backup/remove-vercount-20260906/tamabox.changelogs.json new file mode 100644 index 0000000..e089503 --- /dev/null +++ b/.workbuddy/backup/remove-vercount-20260906/tamabox.changelogs.json @@ -0,0 +1,35 @@ +{ + "page": 1, + "perPage": 3, + "totalItems": 3, + "totalPages": 1, + "items": [ + { + "collectionId": "tamabox", + "collectionName": "tamabox-changelogs", + "content": "新增:用户私信功能上线,可在「我的」页查看匿名来信。
\n修复:移动端问题列表间距过窄的问题。
\n优化:首页加载速度提升约 30%。", + "created": "2024-03-04 21:45:55.000Z", + "id": "none", + "published_at": "2024-03-04 21:45:55.000Z", + "updated": "2024-03-04 21:45:55.000Z" + }, + { + "collectionId": "tamabox", + "collectionName": "tamabox-changelogs", + "content": "修复:部分旧浏览器下时间显示异常。
\n新增:修改记录页(本页),将完整更新历史从首页挪出,保持首页简洁。", + "created": "2024-02-29 00:00:55.000Z", + "id": "none", + "published_at": "2024-02-29 00:00:55.000Z", + "updated": "2024-02-29 00:00:55.000Z" + }, + { + "collectionId": "tamabox", + "collectionName": "tamabox-changelogs", + "content": "项目初始化:匿名提问 / 回答的基础流程跑通。", + "created": "2023-06-03 13:11:55.000Z", + "id": "none", + "published_at": "2023-06-03 13:11:55.000Z", + "updated": "2023-06-03 13:11:55.000Z" + } + ] +} \ No newline at end of file diff --git a/.workbuddy/backup/tamami-load-inject-20260906/header.html b/.workbuddy/backup/tamami-load-inject-20260906/header.html new file mode 100644 index 0000000..7659d79 --- /dev/null +++ b/.workbuddy/backup/tamami-load-inject-20260906/header.html @@ -0,0 +1,1020 @@ + + + + + + {{ .Title }} + + + + + + + + + + + + + + + + + {{ if .VConsole }} + + + {{ end }} + + + + {{ if eq .CaptchaType "math" }} + + + {{ else if .RecaptchaTurnstileStyle }} + + + {{ else }} + + + {{ end }} + {{ if ne SentryDSN "" }} + + + {{ end }} + + + + + + + + + + + + + + + + + + + + + + + + + + + {{ if .NoIndex }}{{ end }} + {{ if .IsUserPage }} + + + + + + + + + {{ else }} + + + + + + + {{ end }} + + + + + + + + + + + + + +
+ {{ if not .IsUserPage }} + + {{ end }} + +
+ + + +{{ if .IsPixel }} +
+{{ else }} +
+{{ end }} + +{{ if eq .CaptchaType "math" }} +
+
+

{{t .LangCode "captcha.title"}}

+

{{t .LangCode "captcha.hint"}}

+
+ {{t .LangCode "captcha.loading"}} + +
+
+ +
+ +
+ + +
+
+
+ + + + +{{ end }} \ No newline at end of file diff --git a/.workbuddy/backup/timebox-inline-20260906/footer.html b/.workbuddy/backup/timebox-inline-20260906/footer.html new file mode 100644 index 0000000..0564317 --- /dev/null +++ b/.workbuddy/backup/timebox-inline-20260906/footer.html @@ -0,0 +1,78 @@ +

+
Powered by NekoBox | {{ ICP }}
{{t .LangCode "site.footer.runtime"}}: +
+ + {{t .LangCode "site.footer.admin"}} + | {{t .LangCode "site.footer.notice"}} + | {{t .LangCode "site.footer.chat"}} + | {{t .LangCode "site.footer.drive"}} + | {{t .LangCode "site.footer.status"}} + | {{t .LangCode "site.footer.nav"}} +

+
+
+ + + + diff --git a/.workbuddy/backup/timebox-inline-20260906/header.html b/.workbuddy/backup/timebox-inline-20260906/header.html new file mode 100644 index 0000000..ad7f165 --- /dev/null +++ b/.workbuddy/backup/timebox-inline-20260906/header.html @@ -0,0 +1,1029 @@ + + + + + + {{ .Title }} + + + + + + + + + + + + + + + + + {{ if .VConsole }} + + + {{ end }} + + + + {{ if eq .CaptchaType "math" }} + + + {{ else if .RecaptchaTurnstileStyle }} + + + {{ else }} + + + {{ end }} + {{ if ne SentryDSN "" }} + + + {{ end }} + + + + + + + + + + + + + + + + + + + + + + + + + + + {{ if .NoIndex }}{{ end }} + {{ if .IsUserPage }} + + + + + + + + + {{ else }} + + + + + + + {{ end }} + + + + + + + + + + + + + + +
+ {{ if not .IsUserPage }} + + {{ end }} + +
+ + + +{{ if .IsPixel }} +
+{{ else }} +
+{{ end }} + +{{ if eq .CaptchaType "math" }} +
+
+

{{t .LangCode "captcha.title"}}

+

{{t .LangCode "captcha.hint"}}

+
+ {{t .LangCode "captcha.loading"}} + +
+
+ +
+ +
+ + +
+
+
+ + + + +{{ end }} \ No newline at end of file diff --git a/.workbuddy/backup/wp-fragments-20260906/autoban.go b/.workbuddy/backup/wp-fragments-20260906/autoban.go new file mode 100644 index 0000000..f2186aa --- /dev/null +++ b/.workbuddy/backup/wp-fragments-20260906/autoban.go @@ -0,0 +1,277 @@ +// Package autoban 提供 fail2ban 风格的自动临时封禁:检测批量扫描/探测特征后 +// 临时封禁来源 IP,并可回调发送告警。纯标准库实现,便于独立测试与复用。 +package autoban + +import ( + "strings" + "sync" + "time" +) + +// 探测事件类型 +const ( + KindNone = 0 // 无探测特征 + KindSensitive = 1 // 命中敏感路径 + KindNotFound = 2 // 404 响应(未命中敏感路径) +) + +// 默认阈值/窗口(Options 未配置或为 0 时兜底)。 +const ( + DefaultWindowSeconds = 60 + DefaultDurationMinutes = 15 + DefaultThresholdSensitive = 10 + DefaultThreshold404 = 20 + pathSampleMax = 6 +) + +// Options 自动封禁配置。 +type Options struct { + Enabled bool + // TrackNotFound 是否把 KindNotFound(未注册路径的 404)计入封禁统计。 + // 默认 false:正常业务路径一律放行,仅敏感扫描特征路径参与计数封禁, + // 避免共享出口下正常访问被 404 探测连坐误伤(详见 conf.Security.BanTrackNotFound)。 + TrackNotFound bool + ThresholdSensitive int // 窗口内敏感路径命中次数 + Threshold404 int // 窗口内 404 次数 + Window time.Duration // 统计窗口 + Duration time.Duration // 封禁时长 + AlertEmail string // 告警收件人(留空不发送) + SendAlert func(ip string, paths []string, durationMinutes int) error // 告警发送函数(nil 则不发送) +} + +// sensitivePaths 常见后台/配置/漏洞探测路径特征(忽略大小写,前缀匹配)。 +var sensitivePaths = []string{ + "/admin", "/wp-admin", "/wp-login.php", "/wp-content", "/wordpress", + "/administrator", "/manager", "/cpanel", "/plesk", + "/.env", "/.git", "/.aws", "/.ssh", "/.svn", "/.hg", "/.htaccess", + "/config", "/configuration", "/backup", "/database", "/db", + "/actuator", "/swagger", "/api-docs", "/openapi", "/v2/api-docs", + "/phpmyadmin", "/pma", "/mysql", "/server-status", "/server-info", + "/shell", "/webshell", "/cmd", "/eval", "/hack", "/shell.php", + "/login.php", "/admin.php", "/index.php", "/console", "/vendor", +} + +type probeEvent struct { + at time.Time + kind int +} + +type probeStat struct { + events []probeEvent + sensitive int + notFound int + paths []string // 命中路径样本(告警用) +} + +// Banner 自动封禁器。方法并发安全。 +type Banner struct { + mu sync.Mutex + + probes map[string]*probeStat + banned map[string]time.Time + alerted map[string]bool + + thresholdSensitive int + threshold404 int + trackNotFound bool + window time.Duration + duration time.Duration + alertEmail string + sendAlert func(ip string, paths []string, durationMinutes int) error + enabled bool +} + +// New 按配置创建封禁器并注册全局清理。 +func New(opts Options) *Banner { + window := opts.Window + if window <= 0 { + window = DefaultWindowSeconds * time.Second + } + duration := opts.Duration + if duration <= 0 { + duration = DefaultDurationMinutes * time.Minute + } + sensitive := opts.ThresholdSensitive + if sensitive <= 0 { + sensitive = DefaultThresholdSensitive + } + notFound := opts.Threshold404 + if notFound <= 0 { + notFound = DefaultThreshold404 + } + b := &Banner{ + probes: make(map[string]*probeStat), + banned: make(map[string]time.Time), + alerted: make(map[string]bool), + thresholdSensitive: sensitive, + threshold404: notFound, + trackNotFound: opts.TrackNotFound, + window: window, + duration: duration, + alertEmail: strings.TrimSpace(opts.AlertEmail), + sendAlert: opts.SendAlert, + enabled: opts.Enabled, + } + register(b) + return b +} + +// Record 记录一次探测事件,达到阈值时封禁 IP 并触发一次告警。 +func (b *Banner) Record(ip, path string, kind int) { + if !b.enabled || ip == "" || kind == KindNone { + return + } + // 404 计数默认关闭(正常业务路径一律放行,仅敏感扫描特征参与封禁): + // 只有显式开启 TrackNotFound 时才把未注册路径的 404 计入统计。 + if kind == KindNotFound && !b.trackNotFound { + return + } + b.mu.Lock() + defer b.mu.Unlock() + + now := time.Now() + cutoff := now.Add(-b.window) + + st := b.probes[ip] + if st == nil { + st = &probeStat{} + b.probes[ip] = st + } + + // 滚动清理过期事件并重算计数 + valid := st.events[:0] + sensitive, notFound := 0, 0 + for _, e := range st.events { + if e.at.After(cutoff) { + valid = append(valid, e) + if e.kind == KindSensitive { + sensitive++ + } else if e.kind == KindNotFound { + notFound++ + } + } + } + valid = append(valid, probeEvent{at: now, kind: kind}) + if kind == KindSensitive { + sensitive++ + } else { + notFound++ + } + st.events = valid + st.sensitive = sensitive + st.notFound = notFound + if len(st.paths) < pathSampleMax && path != "" { + st.paths = append(st.paths, path) + } + + if sensitive < b.thresholdSensitive && notFound < b.threshold404 { + return + } + + // 已达阈值:封禁(已在封禁中则跳过) + if until, ok := b.banned[ip]; ok && until.After(now) { + return + } + until := now.Add(b.duration) + b.banned[ip] = until + + // 告警(每 IP 仅一次) + if b.alertEmail != "" && b.sendAlert != nil && !b.alerted[ip] { + b.alerted[ip] = true + sample := append([]string{}, st.paths...) + dur := int(b.duration.Minutes()) + go func() { + _ = b.sendAlert(ip, sample, dur) + }() + } +} + +// IsBanned 判断 IP 是否处于封禁期;到期自动解除。 +func (b *Banner) IsBanned(ip string) bool { + if !b.enabled || ip == "" { + return false + } + b.mu.Lock() + defer b.mu.Unlock() + if until, ok := b.banned[ip]; ok { + if until.After(time.Now()) { + return true + } + delete(b.banned, ip) + } + return false +} + +// IsSensitivePath 判断路径是否命中敏感探测特征(忽略大小写,完整段前缀匹配)。 +func IsSensitivePath(p string) bool { + lower := strings.ToLower(p) + for _, s := range sensitivePaths { + if lower == s || strings.HasPrefix(lower, s+"/") { + return true + } + } + return false +} + +// ---------- 全局注册与清理 ---------- + +var ( + bannersMu sync.Mutex + banners = make(map[*Banner]struct{}) + bannersOnce sync.Once +) + +func register(b *Banner) { + bannersMu.Lock() + banners[b] = struct{}{} + bannersMu.Unlock() + + bannersOnce.Do(func() { + go func() { + for { + time.Sleep(2 * time.Minute) + bannersMu.Lock() + for b := range banners { + b.cleanup() + } + bannersMu.Unlock() + } + }() + }) +} + +// cleanup 定期清理过期探测记录与已到期封禁(防止内存膨胀)。 +func (b *Banner) cleanup() { + b.mu.Lock() + defer b.mu.Unlock() + + now := time.Now() + cutoff := now.Add(-b.window) + + for ip, st := range b.probes { + if len(st.events) == 0 || st.events[len(st.events)-1].at.Before(cutoff) { + delete(b.probes, ip) + continue + } + valid := st.events[:0] + sensitive, notFound := 0, 0 + for _, e := range st.events { + if e.at.After(cutoff) { + valid = append(valid, e) + if e.kind == KindSensitive { + sensitive++ + } else if e.kind == KindNotFound { + notFound++ + } + } + } + st.events = valid + st.sensitive = sensitive + st.notFound = notFound + } + for ip, until := range b.banned { + if !until.After(now) { + delete(b.banned, ip) + } + } +} diff --git a/.workbuddy/backup/wp-fragments-20260906/autoban_test.go b/.workbuddy/backup/wp-fragments-20260906/autoban_test.go new file mode 100644 index 0000000..57ee69b --- /dev/null +++ b/.workbuddy/backup/wp-fragments-20260906/autoban_test.go @@ -0,0 +1,143 @@ +package autoban + +import ( + "sync/atomic" + "testing" + "time" +) + +func newTestBanner(thresholdSensitive, threshold404 int, window, duration time.Duration, alertEmail string, alertCalls *int64) *Banner { + return New(Options{ + Enabled: true, + TrackNotFound: true, // 测试 helper 显式开启 404 跟踪,覆盖两种计数的既有用例 + ThresholdSensitive: thresholdSensitive, + Threshold404: threshold404, + Window: window, + Duration: duration, + AlertEmail: alertEmail, + SendAlert: func(ip string, paths []string, dur int) error { + if alertCalls != nil { + atomic.AddInt64(alertCalls, 1) + } + return nil + }, + }) +} + +func TestSensitiveThreshold(t *testing.T) { + b := newTestBanner(2, 5, time.Minute, time.Minute, "", nil) + b.Record("1.2.3.4", "/admin", KindSensitive) + if b.IsBanned("1.2.3.4") { + t.Fatal("should not be banned before reaching threshold") + } + b.Record("1.2.3.4", "/.env", KindSensitive) + if !b.IsBanned("1.2.3.4") { + t.Fatal("expected ban after reaching sensitive threshold") + } +} + +func TestNotFoundThreshold(t *testing.T) { + b := newTestBanner(10, 3, time.Minute, time.Minute, "", nil) + for i := 0; i < 3; i++ { + b.Record("5.6.7.8", "/random-"+string(rune('a'+i)), KindNotFound) + } + if !b.IsBanned("5.6.7.8") { + t.Fatal("expected ban after reaching 404 threshold") + } +} + +func TestNotFoundTrackDisabledByDefault(t *testing.T) { + // 默认(TrackNotFound=false)下 404 不参与统计:正常业务路径一律放行, + // 仅敏感扫描路径仍计数封禁——防止共享出口下正常访问被 404 探测连坐误伤。 + b := New(Options{Enabled: true, ThresholdSensitive: 1, Threshold404: 1, Window: time.Minute, Duration: time.Minute}) + for i := 0; i < 5; i++ { + b.Record("7.7.7.7", "/random-"+string(rune('a'+i)), KindNotFound) + } + if b.IsBanned("7.7.7.7") { + t.Fatal("404 events must not accumulate when TrackNotFound is false") + } + b.Record("7.7.7.7", "/.env", KindSensitive) + if !b.IsBanned("7.7.7.7") { + t.Fatal("sensitive events must still ban even when 404 tracking is off") + } +} + +func TestWindowExpiry(t *testing.T) { + b := newTestBanner(2, 5, 50*time.Millisecond, time.Minute, "", nil) + b.Record("1.1.1.1", "/admin", KindSensitive) + time.Sleep(80 * time.Millisecond) // 事件滑出窗口 + b.Record("1.1.1.1", "/.env", KindSensitive) + if b.IsBanned("1.1.1.1") { + t.Fatal("events outside the window must not accumulate") + } +} + +func TestDurationExpiry(t *testing.T) { + b := newTestBanner(1, 5, time.Minute, 60*time.Millisecond, "", nil) + b.Record("2.2.2.2", "/admin", KindSensitive) + if !b.IsBanned("2.2.2.2") { + t.Fatal("expected ban") + } + time.Sleep(100 * time.Millisecond) // 封禁到期 + if b.IsBanned("2.2.2.2") { + t.Fatal("ban should expire after duration") + } +} + +func TestAlertOncePerIP(t *testing.T) { + var calls int64 + b := newTestBanner(1, 5, time.Minute, time.Minute, "admin@example.com", &calls) + b.Record("9.9.9.9", "/wp-admin", KindSensitive) + b.Record("9.9.9.9", "/.git", KindSensitive) // 已在封禁中,不应重复告警 + b.Record("9.9.9.9", "/config", KindSensitive) + + // sendAlert 异步调用,轮询等待最多 500ms + deadline := time.Now().Add(500 * time.Millisecond) + for atomic.LoadInt64(&calls) == 0 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + if got := atomic.LoadInt64(&calls); got != 1 { + t.Fatalf("expected exactly 1 alert, got %d", got) + } +} + +func TestDisabled(t *testing.T) { + b := New(Options{Enabled: false}) + b.Record("3.3.3.3", "/admin", KindSensitive) + if b.IsBanned("3.3.3.3") { + t.Fatal("disabled auto-ban must not ban") + } +} + +func TestDefaults(t *testing.T) { + b := New(Options{Enabled: true}) // 全部走默认值 + if b.thresholdSensitive != DefaultThresholdSensitive || b.threshold404 != DefaultThreshold404 { + t.Fatalf("default thresholds wrong: %d/%d", b.thresholdSensitive, b.threshold404) + } + if b.window != DefaultWindowSeconds*time.Second || b.duration != DefaultDurationMinutes*time.Minute { + t.Fatalf("default window/duration wrong: %v/%v", b.window, b.duration) + } + if b.trackNotFound { + t.Fatal("404 tracking must be disabled by default") + } +} + +func TestIsSensitivePath(t *testing.T) { + cases := []struct { + path string + want bool + }{ + {"/admin", true}, + {"/admin/panel", true}, + {"/WP-ADMIN", true}, + {"/.env", true}, + {"/user/questions", false}, + {"/vote/abc123", false}, + {"/administratorx", false}, // 前缀必须完整段匹配,避免误伤 + } + for _, c := range cases { + if got := IsSensitivePath(c.path); got != c.want { + t.Errorf("IsSensitivePath(%q) = %v, want %v", c.path, got, c.want) + } + } +} diff --git a/.workbuddy/memory/2026-09-04.md b/.workbuddy/memory/2026-09-04.md new file mode 100644 index 0000000..e975282 --- /dev/null +++ b/.workbuddy/memory/2026-09-04.md @@ -0,0 +1,99 @@ +# 2026-09-04 + +- 调研并输出 /user/profile 页面(account 面板)UI 优化评审与改造方案(等待用户批准后实施)。 +- 关键结论: + - 密码强制登出:`users.password_version` + 会话 `pwd_ver` 机制已存在(internal/context/auth.go authenticatedUser),改密后旧会话下次请求即失效;但 UpdateProfile 改密后仍重定向 /user/profile,被 Toggle 以「请先登录」错误文案弹回 /login,成功 flash 被吞。改造方向:改密成功 → Session.Flush() + success flash(复用 auth.errPasswordChanged)→ 直接跳 /login。 + - 头像/背景裁剪:项目无任何 crop 库;第三方库全部自托管于 R2(r2.337845818.best/tamabox/cdn)。候选方案:Cropper.js 内嵌 static/(需扩 static/fs.go embed 规则)。当前 avatarPlaceholder 文案自嘲"非1:1会扁"但无强制。 + - 复用点:profile-tabs 面板、Pickr 颜色选择、easy.qrcode 预览、UIkit modal/accordion、imagecheck 像素校验、storage.UploadPictureToS3(自动转 WebP、宽>1920 缩放)。 + - i18n 四语言字典 key 全等校验(i18n_test.go TestDictionaryComplete),新增词条须同步 4 个 dict 文件。 + +## 下午:profile account 面板改造已实施(用户已批准方案) + +- 决策:Cropper.js 走自有 R2 CDN(`lib/cropperjs/1.6.2/`,用户自行上传);改密立即登出跳登录页;卡片分区+折叠(中等重构);前后端双比例校验。 +- 改动清单: + - `route/user/profile.go`:avatar→storage.UploadAvatarToS3、background→storage.UploadBackgroundToS3(新增),改密成功(passwordChanged 标志)→ Session.Flush + flash(profile.flash.passwordChanged) → /login;比例不符 flash 提示(profile.err.avatarRatio / backgroundRatio)。 + - `internal/imagecheck/imagecheck.go`:新增 ErrBadAspectRatio + CheckAspectRatio + DefaultAspectTolerance(0.01);`imagecheck_test.go` 新增 4 个用例。 + - `internal/storage/s3.go`:抽 uploadPictureToS3 内部分管线(aspect 可选),UploadAvatarToS3=1:1、UploadBackgroundToS3=16:9,魔数后、像素总量前校验;原有 UploadPictureToS3 兼容签名(其他调用方不变)。 + - `internal/i18n/dict_*.go`(4 语):新增 15 词条(card.* 4、cropHint 2、cropTitle/cropConfirm、pwdNote、pickAvatar/pickBackground、err.avatarRatio/backgroundRatio/cropLibUnavailable、flash.passwordChanged)。 + - `templates/user/profile.html`:account 面板重构为 8 张卡片(基础资料/头像与背景[预览+裁剪]/二维码样式折叠/社交折叠/修改密码[随主表单]/标签/页面密码/账号操作);头像 96px 圆、背景 16:9 预览;Cropper 弹窗+写回 file input 逻辑;accordion 展开时重绘二维码预览;新增 .tb-pcard 等样式与暗色适配、移动端单列。 +- 验证:go build ./...(用 dev/webpstub overlay 方式,Windows 无 libwebp)通过;go test internal/i18n + internal/imagecheck 通过;dev/checktpl 全模板语法 OK;HTML 标签开闭平衡校验通过。 +- 待办:R2 上传 cropper.min.{js,css} 到 r2.337845818.best/tamabox/cdn/lib/cropperjs/1.6.2/ 后即可端到端生效;未做浏览器实测(需本地 DB/Redis)。 + +## 晚间:修复部署环境 `UIkit is not defined`(Rocket Loader 时序) + +- 现象:VM234:42 Uncaught ReferenceError: UIkit is not defined;更换头像/背景按钮点击无效果。 +- 根因:裁剪脚本(templates/user/profile.html 末尾)IIFE 解析期即执行 `var modalObj = UIkit.modal(modalEl)`;UIkit 在 base/header.html 是 defer 加载,Cloudflare Rocket Loader 把该内联脚本激活在 UIkit 执行前 → 抛错中断整个脚本 → `[data-pick-image]` 监听(其后)从未绑定。 +- 修复(templates/user/profile.html,4 处): + 1. `modalObj` 改为 null 懒创建(startCrop 内、依赖就绪后 `UIkit.modal(modalEl)`); + 2. 新增 `notify()`:UIkit 可用→UIkit.modal.alert,否则回退原生 window.alert; + 3. 新增 `whenReady(cb)`:轮询等待 window.UIkit && window.Cropper,超时 3s → notify(MSG_NO_CROPPER);文件大小校验前置(不依赖库); + 4. 脚本标签加 `data-cfasync="false"`,按钮监听尽早同步绑定。 +- 经验:模板内联脚本**禁止在解析期触碰 defer/外部库全局对象**(UIkit/Pickr 等),一律在用户事件回调内或依赖就绪后使用——Rocket Loader 会打乱执行序;全站内联脚本仅裁剪脚本踩中此坑。 +- 验证:node --check 通过(模板占位符替换后);R2 上 cropper 文件此前 curl 仍不可达(HTTP 000),用户需先上传,否则选图后 3s 提示「裁剪组件暂不可用」——需提醒用户。 + +## 晚间(二):图像保存 UX + 同行居中 + console 噪音排查 + +- 用户反馈:图像上传/裁剪已可用;但「保存修改」按钮在「修改密码」卡片里,改图后要去那里点击才生效,不直观;且头像修改显示在左上角别扭。 +- 改动(templates/user/profile.html): + 1. 头像与背景卡片内新增本地保存按钮(type=submit,label 新 i18n key `profile.saveMedia`,随主表单提交,裁剪写回的文件域一并上传);CSS `.tb-media-save`(居中条)。 + 2. `.tb-media-row` 改 `justify-content:center`、子项 `flex:0 1 auto` + column 居中、`tb-frame-bg` 固定 320px(max-width:100%);移动端 ≤640 子项 `flex-basis:100%` 上下堆叠居中、背景图全宽、保存按钮全宽。 + 3. 4 语字典新增 `profile.saveMedia`(zh-CN 保存头像与背景 / zh-TW 儲存頭像與背景 / en Save avatar & background / ja アイコンと背景を保存)。 +- console 噪音排查结论:`inspector.js` AbortError/Request timeout/responseType arraybuffer 报错**非项目代码**(全仓库 grep 无 inspector/fetch 包装);是浏览器 XHR 监控类扩展包装 fetch/XHR + Rocket Loader 激进异步调度(arraybuffer 脚本请求被中止)造成的误报。建议无痕窗口验证 + 或 Cloudflare 关闭 Rocket Loader。 +- 验证:gofmt -w 4 个 dict;go test ./internal/i18n/ 通过;go run ./dev/checktpl 全模板语法 OK。 + +## 晚间(三):二维码/社交默认展开 + 头像背景组件等宽 + 每卡片独立保存按钮 + +- 用户要求:①二维码、社交两块默认展开;②更换头像/更换背景组件大小一致(原头像 96 圆 vs 背景 320 宽预览悬殊);③为 account 面板每块加独立保存按钮(仿头像背景卡样式)。 +- 改动(templates/user/profile.html): + 1. 卡片3/4 的 uk-accordion `
  • ` 加 `uk-open` 默认展开(仍可折叠,multiple:true)。 + 2. `.tb-media-item` 固定等宽列 320px(flex:0 0 320 + max-width:100%),头像预览 96→120px、背景帧 width:100%(列内满宽 16:9);`.tb-media-actions .uk-button` min-width:150px 令两个更换按钮同宽。移动端:头像 80→96px、item 全宽堆叠、按钮全宽。 + 3. 保存按钮:基础资料(profile.saveBasic)/头像背景(已有 saveMedia)/二维码(profile.saveQR)/社交(profile.saveSocial)/改密(原 admin.saveProfile 改 profile.savePassword「确认修改密码」)——均为同表单 type=submit(提交整表),复用居中类 `.tb-card-save`(与 .tb-media-save 同规则)。 + 4. 二维码预览:默认展开后从其它 tab(?tab=question 等)切回 account 面板时不会再触发 accordion 'shown' → showPanel 里 account 时调 `window.__tbRefreshAccountPreview`(IIFE 内暴露的 debouncedUpdatePreview)重绘。 +- i18n 4 语新增 saveBasic/savePassword/saveQR/saveSocial;admin.saveProfile key 保留未删(四语仍在,仅模板不再引用)。 +- 验证:go test ./internal/i18n/ 通过;go run ./dev/checktpl OK。 + +## 晚间(四):头像/背景框等高 + 按钮统一居中 + 页面纵向压缩 + +- 用户反馈:①头像框偏小,希望与背景框显示高度一致;②按钮有的居中有的居左,要求统一并压缩空间。 +- 改动(templates/user/profile.html,纯 CSS/结构): + 1. 预览框等高:头像 120→150px 圆;背景框 267×150(16:9,与头像等高);媒体列 320→280 等宽;行间隙 20/40→14/32;移动端头像 96→120px。 + 2. 按钮统一居中:账号操作卡片(登出/导出/停用)`text-align:center` + 行距 12→9px;卡片6 标签、卡片7 页面密码按钮 `div.uk-margin`→`div.tb-card-save`;提问面板 updateHarassment/updateAskPassword、私聊面板 updateChat 三个按钮同改居中。 + 3. 压缩:`.tb-pcard` padding 16/16/10→13/14/8、margin-bottom 16→12、标题 margin 12→10;新增 `.profile-panel .uk-margin { margin-bottom: 12px }`(全面板字段间距 20→12)。 +- 范围说明:global-blockwords / feature-control-form 两个 partial 模板(三面板共用)内按钮未改(避免影响其它页面),如需统一再单独处理。 +- 验证:go run ./dev/checktpl OK。 + +## 晚间(五):账号操作按钮分组同行 + partial 内按钮居中 + +- 用户要求:①导出数据/导出全部数据按钮同一行;②退出登录/停用我的账号同一行;③屏蔽词设置、计数设置也居中。 +- 改动: + 1. `templates/user/profile.html`:账号操作卡重构为 `.tb-account-pair`(flex 居中,两按钮同行):导出组(默认按钮×2,target=_blank 表单)+ 说明行 `.tb-account-note`;登出组(danger 按钮+停用链接)+ 说明行。旧的 `.tb-account-action` 行式堆叠 CSS 删除,暗色规则改 `.tb-account-note`。 + 2. `.feat-quota-line` 加 text-align:center;`.feat-actions` 加 justify-content:center(保存/重置计数按钮居中)——覆盖 feature-control-form(提问/私聊/投票共用)。 + 3. `templates/user/global-blockwords.html`:提交按钮行 `.uk-margin` → `.tb-card-save`(居中);该 partial 仅 profile.html 引用,无外溢。 + 4. 说明文字合并保留:exportHint+exportJSONHint 合并一行小字,deactivateHint(含 )保留在其按钮组下方(deactivate 确认页另有完整警告文案)。 +- 验证:go run ./dev/checktpl OK。 + +## 晚间(六):修复导出按钮点击后永久「提交中」转圈 + +- 现象:导出数据/导出全部数据(target=_blank 下载表单)文件能下,但按钮永久转圈禁用。 +- 根因:`templates/base/footer.html` 全局 submit 反馈(P0 防重复提交)把触发按钮置「转圈+提交中」并禁用;复位仅靠整页导航/bfcache pageshow。`target="_blank"` 下载表单当前页不导航 → 无复位机会 → 永久卡死。 +- 修复(双保险): + 1. `templates/user/profile.html`:两个导出 form 加 `data-tb-skip-submit-feedback="1"`(footer 既有跳过通道,每次 submit 读到即跳并移除)。 + 2. `templates/base/footer.html`:submit 监听里对 `form.getAttribute('target')==='_blank'` 一律 return 跳过反馈——防御未来任何下载/新窗口表单踩同一坑(全站现存 target=_blank 表单仅 profile 这两处,行为从“卡死 bug”变“无反馈”=纯修复)。 +- 经验:全站提交反馈的复位依赖导航,凡不触发本页导航的提交(target=_blank / 下载 / iframe)都必须显式跳过。 +- 验证:go run ./dev/checktpl OK。 + +## 晚间(七):私聊面板 chat 专属功能聚合单卡 + +- 用户要求:`?tab=chat` 面板里「私聊块」(功能开关/收集窗口 feature-control-form)与「私聊设置」(update-chat-settings 消息上限)聚合为一张卡;全局屏蔽词为三面板共享、保持独立。 +- 改动(templates/user/profile.html): + 1. chat 面板改两段结构:私聊专属 = `
    ` 内含 FeatureChat partial + `
    ` + update-chat-settings 表单(原外层 `div.uk-margin` 移除);全局屏蔽词维持原 `hr` + partial 独立区。 + 2. CSS `.chat-zone`:内部 `.feat-card` 去边框透明(padding:0; border:0; background:transparent),避免卡中卡;`hr` margin 14px;内部 `legend`(admin.chat)从 uk-legend 大标题降级为 1.05rem 小节标题。 +- 提问/投票面板未动(结构同前)。 +- 验证:go run ./dev/checktpl OK。 + +## 晚间(八):功能控制卡按钮尺寸统一为常规按钮 + +- 用户要求:「保存该功能设置」按钮样式/大小改成与「更新私聊设置」一致;「重置计数」同调。 +- 改动(templates/user/feature-control-form.html,三面板共享 partial):feat-actions 内两按钮去掉 `uk-button-small` —— 保存改 `uk-button uk-button-primary`、重置改 `uk-button uk-button-default`(常规尺寸,与全站其它表单主按钮一致)。提问/私聊/投票同步生效。 +- 验证:go run ./dev/checktpl OK。 + diff --git a/.workbuddy/memory/2026-09-05.md b/.workbuddy/memory/2026-09-05.md new file mode 100644 index 0000000..d2ad474 --- /dev/null +++ b/.workbuddy/memory/2026-09-05.md @@ -0,0 +1,167 @@ +# 2026-09-05 工作日志 + +## 提问箱公开主页「加载更多」翻页失效(内容重复)排查 + +- 用户报告:提问列表加载完后「加载更多」按钮仍在,点击后加载相同内容。示例链接 `https://box.tama.guru/_/aoi/3105?t=Kmd0mu`(item 页底部嵌有该箱「历史提问」列表 + history-template 加载更多)。 +- 代码链路:`templates/question/history-template.html`(Alpine fetch) → `route/question/page.go ListAPI`(`/api/v1/user/{domain}/questions`) → `internal/db/questions.go GetByUserID`(PinFirst 复合键集游标 `isPinned.CreatedAtUnixNano.ID`)。 +- 线上实测(box.tama.guru, aoi 箱共 38 条已答公开问题): + - 首页 20 条 id 3109→3089;`next_cursor=0.1788566476678885000.3089`。 + - 携带任意真实 next_cursor 再次请求 → 仍返回首页同样 20 条(has_more 恒 true)→ 内容重复、无法翻页(已稳定复现)。 + - 部分异常游标返回空集/6 条等与源码 keyset 预期不符的怪异结果 → 指向线上二进制或 DB 环境与工作区源码假设不一致(时区/列精度/部署版本),单凭源码无法闭合解释。 +- 前端模板与工作区 0904 版逐字符一致(x-on:click.debounce、payload.next_cursor、注释),说明线上模板=新版;但服务端行为异常。 +- 历史:outputs/re-audit-2026-09-01.md P0-2 曾记录同款症状(前端回传旧格式游标→parsePinCursor 失败→永远第一页),当时修复为服务端下发 next_cursor;但线上当前仍复现,说明修复未生效或有残余缺陷。 +- 后续建议:生产库执行 keyset SQL 直查对照 + SHOW CREATE TABLE 确认列精度;代码侧做健壮化(游标未前进/解析失败 → 返回空 + has_more=false;前端按已见 id 集合防重)。 + +## 落地修复(用户选定:防重复兜底) + +1. `internal/db/questions.go`: + - `GetByUserID`:携带游标但 PinFirst 复合游标/纯 id 游标解析失败时,由「忽略游标静默回退首页」改为直接 `return []*Question{}, nil`(空列表 → 上层 has_more=false → 按钮收敛)。 + - `getBy`(GetByAskUserID 旧路径):同步改为解析失败返回空。 +2. `templates/question/history-template.html`: + - SSR range 项与 JS append 项均加 `data-qid`;点击时先扫描 `#question-list [data-qid]` 收集已见 id,过滤重复项;无新增条目时 `more=false`(按钮隐藏/显示无更多)。 + - 注释说明重复加载 bug 的历史形态。 +3. 验证:`go build ./internal/db/...`、`go vet ./internal/db/` 通过;模板测试 `TestTemplatesParse/TestTemplateCrossReferences/TestRenderPublicQuestionList/TestRenderPublicQuestionItem` 全 PASS。全量 `go build ./...` 因第三方 `chai2010/webp`(CGO,本地缺 C 库)预存失败,与本次改动无关。 +4. 待办(未做):生产侧核对部署二进制是否含 9/1 P0-2 修复、DB 列精度/时区一致性诊断;线上复现的 keyset 怪异行为(同 nano 不同 id 返回不同页等)仍未完全由源码闭合解释。 +- 为用户产出 PG 根因诊断脚本 outputs/pg-cursor-pagination-diagnose.sql:PART A 环境/表结构/集合核对(含 created_at 列精度、索引、answered_public_all 应=38 与线上 API 对齐);PART B 用 DO+临时表纯 SQL 复刻 ListAPI 复合键集翻页循环,逐页打印 ids、带死循环/重复页检测;PART C UnixNano 指纹核对(1788566476678885000 类)用于区分部署版本旧 vs DB 环境问题。ListAPI 等价条件已核对: FilterAnswered(True)+PrivateStatus=1+PinFirst+page_size=20+1 探测。待用户执行回贴结果判读。 +- 生产库真实结构确认(用户探查): schema=nekobox(search_path 默认 public 导致首版脚本找不到表);nekobox.questions: id numeric(seq nekobox.questions_id_seq), created_at/updated_at/deleted_at = timestamp(6) WITHOUT TIME ZONE, user_id bigint, answer text, is_private/is_pinned/is_read boolean NOT NULL;nekobox.users 含 domain。线上库与源码(GORM timestamptz 假设)不一致 -> 无时区列+Go UTC 解释=线上 keyset 错位头号嫌疑。产出 v2 脚本 outputs/pg-cursor-diagnose-v2-nekobox.sql:SET search_path=nekobox; PART A 结构/集合核对(应38)+DB墙钟vs线上Z文本目视(差8h即偏移实锤); PART B DO+临时表纯墙钟 keyset 复现(锚点 timestamp 变量避免时区换算, 重复页/死循环检测); PART C nano 指纹反推命中检测(match_3089)+Z文本墙钟命中。待用户执行回贴。 +- 【根因闭合】v2 脚本线上结果: aoi_user_id=329, answered_public_all=38(与线上API一致), 无置顶行(pinned=0)。DB 墙钟==线上 JSON Z 文本(无时区偏移,会话 Asia/Shanghai 不影响无时区列直比)。PART B 纯墙钟 keyset 翻页: 第1页20条(3109..3089)=线上首页, 第2页18条(3088,2883..2411), 无重复无跳行 -> **DB 层完全自洽**。PART C: nano=1788566476678885000 反推墙钟 00:01:16.678885 精确命中 3089 (match_3089=t), Z 文本命中 3109/3089 -> 服务端 encode 正确、无时区/精度错位。结论: DB/SQL 层彻底排除,线上"游标被无视返回首页"只能用【线上部署二进制与 0904 源码不一致(解析路径差异)】解释。修复=部署含防重兜底的最新源码; 部署后需 curl 复测翻页收敛。 +- 【真根因确认+已修复】部署 0904 后线上仍复现 -> 读 parsePinCursor 源码定位: `time.Unix(0, nano)` 返回 Local 时区,进程 TZ=Asia/Shanghai 时墙钟 +8h(00:01->08:01)。生产 questions.created_at 是 timestamp WITHOUT time zone,驱动按 time.Location 墙钟直发无时区列 -> `created_at < '08:01'` 对库内全部 00:xx 行恒真 -> keyset 退化为全量 -> 永远返回首页 has_more=true -> 无限循环。本地实验 tz_proof.go 证明 08:01 vs 00:01 偏移。已修复 internal/db/questions.go parsePinCursor: time.Unix(0,nano) -> time.Unix(0,nano).UTC()(含时区约定注释)。build/vet PASS。其余 UnixNano 用途(随机/文件名)无 keyset 风险。待用户重新部署后 curl 验收翻页收敛(38条唯一)。 +- 【修复验收通过】用户重新部署后线上验证:第1页20条(新增20) has_more=true -> 第2页18条(新增18) has_more=false -> 总计38条唯一,完全收敛 ✓。非法游标(abc)/旧纯id游标(3089)均返回 {"data":[],"has_more":false} -> 解析失败收敛兜底同时生效。根因(parsePinCursor 时区偏移)与今日两处防重兜底均已上线。问题闭环。 +- 用户拟将生产库克隆到本地实验环境做 timestamptz 迁移测试。本地已建独立 PG 测试实例: 127.0.0.1:5433, user=postgres, trust 认证, data 目录 $HOME/AppData/Local/Temp/tamabox-pg-clone-test/data (PostgreSQL 18 at C:/OtherFiles/PostgreSQL/18)。等待用户 pg_dump 生产库(Fc, --schema=nekobox) 后导入跑迁移验证(epoch 快照/转换/验收/翻页复现)。注意本地另有用户自己的 5432 实例(scram 认证, 无密码勿扰)。 +- 【timestamptz 迁移已在克隆库验证通过】用户 dump(nekobox_clone_20260905.dump, 资料库 drive 节点 6oAmSRkxq7DVFAnqRt8QEv) 下载后导入本地 5433 测试实例 nekobox_clone。结果: 16 表, aoi=38 与线上一致。实际无时区时间列仅 4 表 12 列: questions/users/censor_logs/upload_images(其余表本为 timestamptz)。Asia/Shanghai 会话下迁移 ALTER TYPE timestamptz USING AT TIME ZONE 'UTC': 1.7s 完成, epoch 前后差异 0 行, 残余 without=0; 关键行指纹 3109=1788569378648502000/3089=1788566476678885000/2411=1781735419615754000 与线上一致; keyset 翻页带 +00 参数精确翻出线上第2页同款 18 条; 索引完整; 回滚路径双向验证无损。产出 outputs/timestamptz-migration-online.sql(PART0 核对/1 快照/2 迁移/3 验收4项/4 注释回滚)。克隆测试实例与 dump 暂存本地 Temp, 待用户线上执行确认后清理。 +- 【线上 timestamptz 迁移执行成功】用户线上跑 timestamptz-migration-online.sql: PART0=4表12列, PART1快照12列, PART2迁移DO完成, PART3验收全绿: 3.1 epoch差异0行, 3.2 remain_without=0, 3.3 指纹 2411=1781735419615754000/3089=1788566476678885000/3109=1788569378648502000 与克隆库/线上游标一致, 3.4 keyset第2页18条(3088,2883..2411)同款。但端到端验收受阻: box.tama.guru 持续 HTTP 521(源站不可达, 页面+API均打不开, 观察约2.5min) -> 疑似用户正在重启/部署应用或服务宕机, 待服务恢复后重跑翻页验收脚本(38条唯一收敛)确认整体闭环; 本地5433克隆实例与dump暂留待最终验收后清理。 +- 【端到端验收通过·最终闭环】服务启动后重跑线上翻页: 第1页20条 has_more=true -> 第2页18条 has_more=false -> 38条唯一收敛 ✓。注意: 迁移后 JSON created_at 文本从 "...Z"(UTC) 变为 "...+08:00"(session TZ=Asia/Shanghai) —— 绝对时刻一致。前端消费核对: history-template SSR {{Date .CreatedAt}} 迁移前显示 UTC 墙钟(少8h) 而 JS dayjs() 追加项本地化 -> 首屏与追加时间曾不一致(隐藏显示bug), 迁移后 SSR 读 timestamptz 转会话时区 -> 两者一致且显示上海本地时间(对用户更正确); item.html/list.html 同理顺带修正。无需改代码, 属显示语义修正观察项。遗留: 用户清理 diag_test 报依赖错误 -> 解答用 DROP SCHEMA diag_test CASCADE (schema 内仅 snap_before/snap_after 两张自建快照表)。本地 5433 克隆实例+dump 待清理。 +- 【发现迁移基准错误+已产修复脚本】用户反馈: 真实本地时间 00:01 的提问页面显示 08:01 -> 存量墙钟实为"上海本地时间"(驱动按进程本地墙钟写无时区列, 读出按UTC标记, 文本一致造成 v2 诊断"对称"假象), 先前迁移用 AT TIME ZONE 'UTC' 把上海墙钟误标 UTC -> 存量绝对时刻整体 +8h。克隆库验证反向修正(USING c AT TIME ZONE 'UTC' AT TIME ZONE 'Asia/Shanghai', 净-8h): 3089 08:01->00:01:16+08 (epoch 1788566476678885000->1788537676678885000), 3109->00:49:38+08, 2411->06-17 22:30+08; keyset 第2页仍18条。产出 outputs/timestamptz-migration-fix-8h.sql (PART0 聚焦4表12列/1快照/2修正/3验收含3.1显示+epoch/3.2翻页/3.3计数/3.4残余/4注释回滚=反向AT TIME ZONE 'Asia/Shanghai' AT TIME ZONE 'UTC')。克隆库全流程演练通过。待用户线上执行贴回 + 我重跑 API 验收(next_cursor nano 应从 0.1788566476678885000 变 0.1788537676678885000)。 +- 【线上反向修正验收通过】用户线上执行 timestamptz-migration-fix-8h.sql(PART2 修正完成, 后续输出被 psql 分页截断不影响), 我直接 API 验证: next_cursor nano 1788566476678885000->1788537676678885000 ✓, created_at 文本回到本地墙钟 00:49:38.648502+08:00 / 末条 00:01:16.678885+08:00 ✓, 翻页 38 唯一收敛 ✓。存量时间语义修正为"上海墙钟"。注意: 该脚本不可重跑(会再-8h)。遗留: 用户如需补看验收可跑只读 SQL; diag_test 清理可用 DROP SCHEMA diag_test CASCADE; 本地 5433 克隆实例+dump 待清理(询问用户后执行)。 +- 【留档完成】事故复盘文档 outputs/TamaBox-v4-keyset-pagination-timezone-incident-2026-09-05.md:完整记录两层缺陷(①parsePinCursor time.Unix Local +8h 致 keyset 失效②timestamptz 迁移基准误用 UTC 致存量+8h 已反向修正)、时间线、4文件代码改动、SQL 脚本产物清单(标注 v1/v2 已淘汰、online.sql 基准错误勿复用、fix-8h.sql 不可重跑)、经验教训预防清单(无时区列+带时区代码混用是土壤/迁移前须用现实锚点确认数据语义/文本一致≠语义正确)、遗留建议(页面抽查/可选 UTC 输出/清理克隆实例与dump/生产 DROP SCHEMA diag_test CASCADE)。 + +## UIkit CSS 迁移公共 CDN(速度优化落地) + +- 背景:生产速度测试发现 R2 自托管 `uikit/3.3.3/css/modify-black-font/uikit.min.css`(263432B)加载 ~1100ms 是大头。 +- Diff 结论:自建版与官方 uikit@3.3.3(263444B,sha256 6630e078...)**仅 3 处颜色差异**——把有色容器(.uk-light/.uk-card-primary/.uk-card-secondary/.uk-overlay-primary/.uk-section-*/.uk-tile-*/.uk-offcanvas-bar)内默认白字/白标题改黑:容器文字与 table th `rgba(255,255,255,.7)→rgba(0,0,0,.7)`,h1-h6/.uk-h*/.uk-heading-* `#fff→#000`。 +- 模板实际仅用 `.uk-light`(用户背景封面,question/list.html、question-not-found.html;内部 h3/p 由 #usernamecolor/#introcolor 内联 JS 覆盖,优先级最高),其余有色容器全仓无 class 使用 → 补丁可只投影 .uk-light(477B 代替 9KB)。 +- 测速(本地国内网络,全量 263KB 3 次):cdnjs.snrat.com ~0.25s(热)最快 > jsdelivr ~0.47s > unpkg ~1.3s > cdnjs.cloudflare ~1.0-1.4s > R2 自建 1.4-2.0s。check-host.net 全球 12 节点:snrat 与 jsdelivr 均 12/12 = 200 OK(snrat 根路径 301 不影响带资源路径请求)。snrat 缓存头 max-age=31104000(360 天)。 +- 落地修改(仅 templates/base/header.html): + 1. css link → `https://cdnjs.snrat.com/ajax/libs/uikit/3.3.3/css/uikit.min.css` + 2. js(uikit.min.js/uikit-icons.min.js)→ `https://cdnjs.snrat.com/ajax/libs/uikit/3.3.3/js/...`(CDNJS 路径与 cdnjs 官方同构,已验证文件存在 Content-Type 正确) + 3. link 后新增补丁 ``, + } + for _, in := range cases { + got := string(MarkdownToHTML(in)) + if strings.Contains(got, "x`, "x"}, + {"quote-inject", `x`, "x"}, + {"url-inject", `x`, "x"}, + {"onattr-inject", `x`, "x"}, + {"long-value", `x`, "x"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := string(MarkdownToHTML(tc.in)) + if !strings.Contains(got, tc.want) { + t.Errorf("输出 %q 应包含 %q", got, tc.want) + } + // 注入的 color 值不得出现 + for _, evil := range []string{";", "position:", "onclick", "javascript:", "红字`, "红字"}, + {"link", "[百度](https://baidu.com)", "百度"}, + {"code", "`code`", "code"}, + {"list", "- 第一项\n- 第二项", "第一项"}, + {"block", "# 标题\n内容", "标题"}, + {"mixed", "问题:**重要** 详情 蓝", "重要"}, + {"empty", "", ""}, + // 危险标签被剥离:script 的内容是纯文本(绘制无风险),img 自闭合无文本则输出空 + {"xss-script", "", "alert(1)"}, + {"xss-img", ``, ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := strings.Join(strings.Fields(MarkdownToPlainText(tc.in)), " ") + if tc.want == "" { + if got != "" { + t.Errorf("MarkdownToPlainText(%q) = %q, 期望空", tc.in, got) + } + return + } + if !strings.Contains(got, tc.want) { + t.Errorf("MarkdownToPlainText(%q) = %q, 期望包含 %q", tc.in, got, tc.want) + } + // 输出不得残留任何标签(< 必须被剥离) + if strings.Contains(got, "<") { + t.Errorf("MarkdownToPlainText(%q) = %q, 不应包含标签字符", tc.in, got) + } + }) + } +} + +// TestSafeURL 是 P2-1 的回归测试:markdown 链接白名单必须拒绝协议相对 URL +// (//evil.com 等),否则会被误判为站内相对路径而渲染成指向外站的钓鱼 / 外链埋点链接。 +// 同时验证 javascript:/data:/ftp: 等危险协议与大小写变体均被拒绝,http/https/mailto +// 与站内相对路径被放行。 +func TestSafeURL(t *testing.T) { + allow := []string{ + "https://example.com", + "http://example.com", + "HTTPS://EXAMPLE.COM", // 大小写不敏感 + "mailto:foo@bar.com", + "/path/to/page", + "./relative", + "../up", + "#fragment", + } + for _, u := range allow { + if !safeURL(u) { + t.Errorf("safeURL(%q) = false, 期望放行", u) + } + } + + deny := []string{ + "//evil.com", // 协议相对 URL(核心回归点) + `\\evil.com`, // 反斜杠变体 + `/\evil.com`, // 反斜杠变体 + "javascript:alert(1)", // 危险协议 + "JavaScript:alert(1)", // 大小写变体 + "data:text/html,` 输出 `"\u003c/script\u003e"`。两种写法均安全,无需修改(仅风格不统一)。 + +2. **`multipart.FileHeader.Size` 不可伪造** —— 详见 P1-3 中的澄清说明。 + +3. **`service.Proxy` / `pixel.Proxy` 无 SSRF** —— 目标 Host 取自配置,用户仅控制路径且经 `path.Clean` 归一化,非用户可控目标。 + +--- + +## 五、经确认实现正确的部分 + +- **密码安全**:bcrypt(cost=10) + 每用户 salt,超 72 字节截断;旧 HMAC-SHA1 仅作兼容且登录时自动升级,旧路径用 `subtle.ConstantTimeCompare` +- **会话固定防护**:`login.go:67` 认证成功后先 `RegenerateID()` 再写入身份 +- **密码重置**:`randstr.String(64)` 加密级随机,24h 过期,一次性消费,按 code 直查无枚举面 +- **页面密码 / 提问密码**:均 bcrypt 存储与比较 +- **验证码**:`crypto/rand` 生成,答案仅存服务端 session,5 分钟 TTL,一次性,尝试上限 5 次,`ConstantTimeCompare` 比对 +- **SQL 注入**:`Raw`/`Exec` 仅用于固定 DDL;排序字段已归一化为 `ASC`/`DESC` 白名单;`LIKE` 有 `escapeLike` 转义 `% _ \`;`db.go` 的 `fmt.Sprintf` 仅拼接配置 schema 与硬编码表名 +- **越权防护**:`getOwnedVote` 校验 `vote.UserID`;`Questioner` 中间件校验归属并注入 `canDelete`;chat 处理器校验 `OwnerID`/`AskerID` +- **SSRF**:**实测全部拦截** —— `127.0.0.1:6379`、`169.254.169.254`(云元数据)、`localhost`、`10.0.0.1`、`[::1]`、`example.com` 均返回 `403 domain not allowed`,`file://` 返回 `400 invalid url`。白名单默认为空即 fail-closed;`proxyImageDialContext` 在拨号时重新解析并固定公网 IP,彻底防 DNS rebinding;`CheckRedirect` 对每跳重复校验 +- **开放重定向**:**实测全部拦截** —— `//evil.com`、`https://evil.com`、`\\evil.com`、`/\evil.com`、`////evil.com`、`/%09/evil.com`、`%2F%2Fevil.com` 一律回落到 `/` +- **XSS 主链路**:blackfriday 未开启 `HTML` 扩展(原始标签被转义),渲染后经白名单 sanitize + `on*` 属性剥离 + `safeURL`/`safeColorValue` 校验 + 文本节点二次转义;`toJSON` 依赖 `json.Marshal` 默认 HTML 转义 +- **HTTP 方法约束**:`site-stats` 等只读端点对 `POST`/`PUT`/`DELETE` 均不执行;登出已正确改为 POST +- **中间件顺序**:CSRF 校验先于限流,无效 token 不消耗限流配额 +- **并发安全**:`go test -race` 零 race;`rateLimiter.visitors`、`autoban.probes/banned`、`TTLCache.items`、`stats.cached`、`shared.App` 全部有锁保护;`captcha` 类型断言使用双返回值 +- **数据一致性**:追问创建用 `clause.Locking` 行锁;会话消息计数为原子 `UPDATE ... WHERE count < ?` 且失败回滚;投票提交有复合唯一索引兜底;配额用 `gorm.Expr` 并防负数 +- **敏感字段**:`Password`/`PagePassword`/`AskPassword`/`UID`/`BlockWords`/`FromIP`/`VoterIP` 均标 `json:"-"`;CSV/XLSX 导出有公式注入转义 +- **超时配置**:`http.Server` 四类超时齐备;所有外部 HTTP 调用均设 `Timeout` + +--- + +## 六、建议修复顺序 + +1. **P1-1 CSRF `SessionKey: "uid"`** —— 一行改动,收益最高,**建议补回归测试** +2. **P1-2 session cookie `Secure`** —— 一行改动 +3. **P1-3 `http.MaxBytesReader`** —— 防匿名磁盘耗尽 +4. **P1-4 IPv6 `/64` 聚合** —— 同时缓解内存膨胀 +5. **P2-1 `safeURL` 拒绝 `//`** —— 一行改动 +6. P1-5 与其余 P2 项按迭代节奏推进 + +--- + +## 七、修复状态(批次 A+B 已落地) + +| 项 | 修复 | 回归测试 | +|----|------|----------| +| P1-1 CSRF `SessionKey: "uid"` | `route.go` 改为包级常量 `CSRFUserSessionKey = "uid"` | `internal/route/csrf_binding_test.go`:`TestCSRFTokenBoundToUserSession`(内存会话重放跨会话 token 复用 → 期望 400;SessionKey 误改回 `"userID"` 即失败) | +| P1-2 session cookie `Secure` | `route.go`:`Secure = strings.HasPrefix(ExternalURL,"https")` | (一行常量改动,行为随部署 `ExternalURL` 而定;HTTPS 部署下自动 `Secure`) | +| P1-3 请求体上限 | `form/form.go`:`http.MaxBytesReader` 封顶 12 MiB | (`internal/form` 既有测试保持通过) | +| P1-4 IPv6 `/64` 聚合 | `shared/ip.go` 新增 `LimitKey`;`ratelimit.go`/`autoban.go`/NotFound 统一套用 | `internal/shared/ip_test.go`:`TestLimitKey` + `TestLimitKeyIPv6SamePrefixCollapses` | +| P2-1 `safeURL` 拒绝 `//` | `markdown.go`:先拒协议相对 URL(`//`、`\\`、`/\`) | `internal/template/markdown_test.go`:`TestSafeURL` | + +**验证**:`go build ./...` 与 `go vet ./...` 均干净;`internal/route`、`internal/shared`、`internal/template`、`internal/form` 测试全过(含上述 3 个新测试)。 +**说明**:CSRF 跨会话拒绝(最关键动态发现)已由 DB 无关集成测试覆盖;本沙箱无 SQL DB(`db.Init` 启动连库),故未在此重启动服务做完整动态复验,需在用户可达 SQL DB 的测试环境下复跑 SSRF / 开放重定向 / 限流等探针。 + +--- + +*报告完毕。全程未读取 `conf/app.ini`;测试服务已停止,临时文件已清理;审阅期间在 `internal/template/` 临时创建的验证测试文件已删除,工作区无残留改动。* diff --git a/outputs/shared-egress-vote-antispam-review-2026-08-26.md b/outputs/shared-egress-vote-antispam-review-2026-08-26.md new file mode 100644 index 0000000..678ef33 --- /dev/null +++ b/outputs/shared-egress-vote-antispam-review-2026-08-26.md @@ -0,0 +1,76 @@ +# 共享出口匿名投票防刷修改与测试报告 + +- **时间**:2026-08-26 +- **目标**:解决 Cloudflare + `trust_proxy=true` 场景下,局域网用户共享公网 IP 导致同一投票只能一人提交的问题。 +- **策略**:签名 `vote_fp` 负责设备级一人一票;IP 仅用于高阈值突发风控,不再承担同一投票的一票封顶。 + +## 修改内容 + +### 1. 删除匿名投票的 IP 一票封顶 + +`route/vote/vote.go`: + +- 移除提交处理器内 `CountByIP(... 24h)` 且 `count >= 1` 即拒绝的逻辑。 +- 匿名用户继续通过有效 HMAC `vote_fp` 与数据库唯一索引防止同一浏览器/设备重复投票。 +- 无效或缺失 Cookie 仍会被重新签发,不会成为可信身份。 + +### 2. 新增投票提交专用的身份优先限流 + +`internal/route/ratelimit.go`: + +新增 `voteSubmitRateLimitMiddleware`,投票提交同时经过两层限制: + +- 登录用户:按 `user:` 独立限流,额度为常规参数的 3 倍。 +- 匿名用户:按有效 `token:` 独立限流。 +- 所有匿名请求:同时经过 `ip:` 高阈值兜底限流,默认是传入基础额度的 10 倍。 +- 无效/缺失 Cookie 不会获得独立 token 限流身份,只能使用 IP 兜底。 +- 触发限制时返回 HTTP 429,不进入实际投票提交处理器。 + +`internal/route/route.go` 已将 `/vote/{token}/submit` 从普通 IP 限流切换到该专用中间件。 + +### 3. 校准 Cloudflare 客户端 IP 解析 + +`internal/shared/ip.go`: + +- `TrustProxy=true` 时优先读取 Cloudflare 官方 `CF-Connecting-IP`。 +- 若该头不存在或非法,再回退到 `X-Real-IP`、`X-Forwarded-For`,最后使用 `RemoteAddr`。 +- `TrustProxy=false` 时仍完全忽略这些请求头,只使用 `RemoteAddr`。 +- 新增 Cloudflare 头优先级和不信任代理时忽略头部的测试。 + +### 4. 更新设计文档 + +`anonymous-vote-design.md` 已同步新的防刷矩阵、token 流程和共享出口说明。 + +## 验证结果 + +通过: + +```text +gofmt -d internal/route/ratelimit.go internal/route/route.go \ + internal/shared/ip.go route/vote/vote.go +# 无输出 + +go test -count=1 ./internal/shared ./route/vote ./internal/template \ + ./templates ./internal/i18n ./internal/cache ./internal/security/autoban +# 全部 PASS + +go vet ./route/vote ./internal/shared ./internal/template ./templates ./internal/i18n +# 无输出 +``` + +补充测试覆盖: + +- 同一共享 IP 下多个不同 token 彼此独立; +- 同一 token 仍受独立限流; +- IP 兜底允许多次正常请求,但能阻断异常突发; +- Cloudflare `CF-Connecting-IP` 优先于其他代理头; +- 未启用可信代理时伪造的代理头不会生效。 + +`go test ./internal/route` 当前仍无法编译完成,原因是项目既有的 `github.com/chai2010/webp@v1.4.0` 在本机缺少 CGO/WebP 编译符号,并非本次限流逻辑测试失败。 + +## Cloudflare 部署注意事项 + +1. 源站防火墙应只允许 Cloudflare 官方 IP 段访问源站端口,否则攻击者可能直接访问源站并伪造 `CF-Connecting-IP`。 +2. 保持 `trust_proxy=true` 的前提是源站确实位于可信反向代理之后。 +3. 重要投票建议开启 Turnstile 或要求登录;匿名签名 Cookie 只能保证设备级防重,无法阻止清 Cookie、换浏览器或自动化客户端。 +4. 当前共享 IP 兜底阈值为 200 次/分钟(投票路由传入基础值 20),可根据真实并发量调整。 diff --git a/outputs/tb-dev-test-qr-crop.png b/outputs/tb-dev-test-qr-crop.png new file mode 100644 index 0000000..67e48eb Binary files /dev/null and b/outputs/tb-dev-test-qr-crop.png differ diff --git a/outputs/tb-dev-test-qr.png b/outputs/tb-dev-test-qr.png new file mode 100644 index 0000000..3b7484f Binary files /dev/null and b/outputs/tb-dev-test-qr.png differ diff --git a/outputs/tb-page-snapshot.html b/outputs/tb-page-snapshot.html new file mode 100644 index 0000000..e87f7ed --- /dev/null +++ b/outputs/tb-page-snapshot.html @@ -0,0 +1,1712 @@ + + + + + + 小狼 - 狼的提问箱 | 匿名提问箱 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    + + + + +
    + + + +
    +
    +

    人机验证

    +

    请计算下方的算术题以验证你不是机器人

    +
    + 加载中... + +
    +
    + +
    + +
    + + +
    +
    +
    + + + + + + + + + + +
    +
    +
    + +

    小狼

    +

    提问密码是12123。欢迎你,我的朋友,不管你是因为什么原因发现这个网站,都希望它能帮助到你。有疑问和建议可以在下方提交问题,或者加群聊聊。

    +
    + + + acfunlink + + + + + + weibolink + + + + + xiaohongshulink + + + + + bloglink + + +
    +
    +
    +
    + +
    +
    + + + + +
    + + +

    扫码向@小狼提问
    谁都可以以匿名的形式提问

    + + + + + + + + + + + + + + + + + + +
    + + + + +
    + +
    + +
    + + + + + + + + + +
    + +
    +
    + + + +
    + +
    +
    + +
    + + + +
    + +
    +
    +
    + + + +
    + +
    + +
    + +
    +
    +
    + + + + + + +

    @小狼 以前回答过的问题 (32)

    + +
    + +
    +
    + 查看回答 +
    + ⭐ + 2026-08-27 13:42:36 +
    +

    礼貌请教小狼提问箱如何避免被恶意利用 +

    +
    + +
    +
    + 查看回答 +
    + ⭐ + 2026-05-12 21:22:46 +
    +

    小狼小狼,想问问可不可以实现提问后继续回复被提问者的功能,就像在同一层聊天一样;还有就是好像我发出提问之后,在提问者回答之前我好像都看不到自己发出的提问,这样的话感觉有点不好找(?) +

    +
    + +
    +
    + 查看回答 +
    + + 2026-08-18 14:59:06 +
    +

    以下是markdown语法展示,大部分功能基本正常实现,空格和换行调整为一般语法,html代码暂不开放。 +标题展示: +Heading level 1 +Heading level 2 +Heading level 3 +Heading level 4 +Heading level 5 +Heading level 6 +粗体: +I just love bold text. +斜体: +Italicized text is the cat’s meow. +又粗又斜: +This text is really important. +引用: +> Dorothy followed her through many of the beautiful rooms in her castle. +列表: +- First item +- Second item +- Third item + - Indented item + - Indented item +- Fourth item +代码块: +At the command prompt, type nano. +链接: +这是一个链接 提问箱。 +

    +
    + +
    +
    + 查看回答 +
    + + 2026-08-13 02:04:36 +
    +

    这是个md测试: +粗体 +斜体 + 代码 +链接 +

    +
    + +
    +
    + 查看回答 +
    + + 2026-07-15 15:36:26 +
    +

    小狼有没有想过为什么人总是先学会告别再学会爱吗 +

    +
    + +
    +
    + 查看回答 +
    + + 2026-06-15 13:39:45 +
    +

    啊不是 是聊天室总是显示 应用程序错误:发生了客户端异常(更多信息请参见浏览器控制台)。(上一条打错字了orz +

    +
    + +
    +
    + 查看回答 +
    + + 2026-06-15 13:28:43 +
    +

    小狼是什么mbti( +

    +
    + +
    +
    + 查看回答 +
    + + 2026-06-15 13:27:29 +
    +

    页面底部的 聊天室 如何创建房间哇 +

    +
    + +
    +
    + 查看回答 +
    + + 2026-06-15 05:24:30 +
    +

    这个网站的页面和box.n3ko.cc这个好像(是同一个开发者嘛 +

    +
    + +
    +
    + 查看回答 +
    + + 2026-05-06 11:23:26 +
    +

    好厉害啊,自己做一个网站也太棒了吧👍🏻老师回复的好及时,感觉好温暖啊。原来这个提问箱背后是这样的初心,希望它能一直被好好运营下去,也谢谢你愿意分享这些想法✨ +

    +
    + +
    +
    + 查看回答 +
    + + 2026-05-06 10:46:32 +
    +

    小狼,你做这个网站是为了什么呀 +

    +
    + +
    +
    + 查看回答 +
    + + 2026-04-23 01:07:41 +
    +

    小狼小狼,请问可以有拉黑功能吗? +

    +
    + +
    +
    + 查看回答 +
    + + 2026-03-20 18:26:42 +
    +

    谢谢小狼ruarua小狼(鞠躬 +

    +
    + +
    +
    + 查看回答 +
    + + 2026-03-16 23:02:34 +
    +

    小狼,你有哪个瞬间感觉到“界限”消失,又或者猛然意识到命运这回事吗🤔 +

    +
    + +
    +
    + 查看回答 +
    + + 2025-12-30 16:15:04 +
    +

    测试图片上传机能 +

    +
    + +
    +
    + 查看回答 +
    + + 2025-11-16 23:03:26 +
    +

    找了几个例子,这些”?“的位置以前都是emoji,看起来好像确实是比较新的emoji会显示成符号,老版常规的像❤️这样的就可以显示出来。回答页面也是类似的情况 +

    +
    + +
    +
    + 查看回答 +
    + + 2025-11-15 13:58:28 +
    +

    小狼,之前提问里的emoji是可以正常显示的,但是从昨天开始变成了”?“符号🤔不过也有个别emoji现在还能显示 +

    +
    + +
    +
    + 查看回答 +
    + + 2025-08-31 14:02:26 +
    +

    小狼小狼今天吃了什么! +

    +
    + +
    +
    + 查看回答 +
    + + 2025-07-25 12:28:46 +
    +

    awa +

    +
    + +
    +
    + 查看回答 +
    + + 2024-12-31 15:04:20 +
    +

    小狼小狼,如果提问者勾选了私密不公开提问,但又没有勾选接收通知,就算被提问者回答了,提问者是不是也没有办法看到回复呀? +

    +
    + +
    + + +
    + +
    +
    + 无更多留言 +

    +
    +
    + + +
    + + +
    +
    + +

    + 您是本站第 位访客 | 本页面已被访问 次 +
    Powered by NekoBox | 狼ICP备 20230101
    提问箱已成功存活: +
    + + 找站长 + | 公告板 + | 聊天室 + | 盘 + | 监控板 + | 导航页 +

    +
    +
    + + + + diff --git a/outputs/tb-prod-test-qr-crop.png b/outputs/tb-prod-test-qr-crop.png new file mode 100644 index 0000000..5c68d2e Binary files /dev/null and b/outputs/tb-prod-test-qr-crop.png differ diff --git a/outputs/tb-prod-test-qr.png b/outputs/tb-prod-test-qr.png new file mode 100644 index 0000000..510f972 Binary files /dev/null and b/outputs/tb-prod-test-qr.png differ diff --git a/outputs/timestamptz-migration-fix-8h.sql b/outputs/timestamptz-migration-fix-8h.sql new file mode 100644 index 0000000..54550e3 --- /dev/null +++ b/outputs/timestamptz-migration-fix-8h.sql @@ -0,0 +1,124 @@ +-- ============================================================================ +-- TamaBox 存量时间 +8h 漂移反向修正脚本(线上执行版) +-- 背景: 先前 timestamptz 迁移用 `AT TIME ZONE 'UTC'` 把存量"上海墙钟"误标为 +-- UTC,导致全部存量时间绝对时刻 +8h(页面显示比真实本地时间晚 8 小时)。 +-- 本脚本: 把当前值按 UTC 还原出原墙钟,再按 Asia/Shanghai 重新解释(净效果 +-- -8h 绝对时刻,会话显示回到真实本地墙钟)。与会话时区无关。 +-- 影响范围: nekobox.questions / users / censor_logs / upload_images 的 +-- created_at / updated_at / deleted_at(12 列,全为 timestamptz)。 +-- 安全: 全程无 DROP 业务对象;仅 CREATE SCHEMA/临时快照表 + ALTER TYPE。 +-- 回滚方式见 PART 4(注释)。 +-- 预期: PART 3 各项判读通过即成功;异常则执行 PART 4 回滚后贴回输出。 +-- ============================================================================ + +-- PART 0: 核对当前状态 ------------------------------------------------------- +-- 确认处于"错误状态"(时间列全为 timestamptz 且显示比真实晚 8h)。 +-- 应输出 12 列 timestamptz; 3089 应显示 08:01:16(错误态) 而非 00:01:16。 +SET TIME ZONE 'Asia/Shanghai'; +SELECT 'PART 0: 当前状态核对(仅本次修正涉及的4表12列)' AS step; +SELECT table_name, column_name, data_type +FROM information_schema.columns +WHERE table_schema = 'nekobox' + AND table_name IN ('questions','users','censor_logs','upload_images') + AND column_name IN ('created_at','updated_at','deleted_at') +ORDER BY table_name, column_name; +SELECT id, created_at AS now_display, (extract(epoch FROM created_at)*1000000000)::numeric(30,0) AS epoch_ns +FROM nekobox.questions WHERE id = 3089; + +-- PART 1: 迁移前快照 ---------------------------------------------------------- +CREATE SCHEMA IF NOT EXISTS diag_test; +DROP TABLE IF EXISTS diag_test.fix_before; +CREATE TABLE diag_test.fix_before(tbl text, col text, n bigint, s numeric); +DO $$ +DECLARE r record; +BEGIN + FOR r IN + SELECT table_name tbl, column_name col + FROM information_schema.columns + WHERE table_schema='nekobox' AND data_type='timestamp with time zone' + AND column_name IN ('created_at','updated_at','deleted_at') + AND table_name IN ('questions','users','censor_logs','upload_images') + ORDER BY table_name, column_name + LOOP + EXECUTE format( + 'INSERT INTO diag_test.fix_before SELECT %L, %L, count(%I), sum(extract(epoch FROM %I)*1000000000) FROM nekobox.%I', + r.tbl, r.col, r.col, r.col, r.tbl); + END LOOP; +END $$; +SELECT 'PART 1: 快照完成' AS step, count(*) AS cols FROM diag_test.fix_before; + +-- PART 2: 反向修正 ------------------------------------------------------------ +-- 核心: 原墙钟按 Asia/Shanghai 解释。净效果 = 绝对时刻 -8h, 会话显示回本地墙钟。 +SELECT 'PART 2: 反向修正执行' AS step; +DO $$ +DECLARE r record; +BEGIN + FOR r IN + SELECT table_name tbl, column_name col + FROM information_schema.columns + WHERE table_schema='nekobox' AND data_type='timestamp with time zone' + AND column_name IN ('created_at','updated_at','deleted_at') + AND table_name IN ('questions','users','censor_logs','upload_images') + ORDER BY table_name, column_name + LOOP + EXECUTE format( + 'ALTER TABLE nekobox.%I ALTER COLUMN %I TYPE timestamptz USING (%I AT TIME ZONE ''UTC'' AT TIME ZONE ''Asia/Shanghai'')', + r.tbl, r.col, r.col); + END LOOP; +END $$; +SELECT '修正完成' AS step; + +-- PART 3: 验收 ----------------------------------------------------------------- +-- 3.1 关键行: 会话上海显示应回到真实本地墙钟(3089=00:01:16.678885+08, epoch 1788537676678885000) +DROP TABLE IF EXISTS diag_test.fix_after; +CREATE TABLE diag_test.fix_after(tbl text, col text, n bigint, s numeric); +DO $$ +DECLARE r record; +BEGIN + FOR r IN + SELECT table_name tbl, column_name col + FROM information_schema.columns + WHERE table_schema='nekobox' AND data_type='timestamp with time zone' + AND column_name IN ('created_at','updated_at','deleted_at') + AND table_name IN ('questions','users','censor_logs','upload_images') + ORDER BY table_name, column_name + LOOP + EXECUTE format( + 'INSERT INTO diag_test.fix_after SELECT %L, %L, count(%I), sum(extract(epoch FROM %I)*1000000000) FROM nekobox.%I', + r.tbl, r.col, r.col, r.col, r.tbl); + END LOOP; +END $$; +SELECT '3.1 修正后关键行(期望 3089=2026-09-05 00:01:16.678885+08 / epoch 1788537676678885000)' AS check_name; +SELECT id, created_at AS val_after, (extract(epoch FROM created_at)*1000000000)::numeric(30,0) AS epoch_ns +FROM nekobox.questions WHERE id IN (3089,3109,2411) ORDER BY id; + +-- 3.2 keyset 翻页抽查(期望第2页 3088,2883..2411 共18条) +SELECT '3.2 keyset 第2页抽查' AS check_name; +SELECT q.id +FROM nekobox.questions q +WHERE q.user_id = 329 AND q.deleted_at IS NULL AND q.answer <> '' AND q.is_private = false + AND q.is_pinned = false + AND (q.created_at < TIMESTAMPTZ '2026-09-05 00:01:16.678885+08' + OR (q.created_at = TIMESTAMPTZ '2026-09-05 00:01:16.678885+08' AND q.id < 3089)) +ORDER BY q.is_pinned DESC, q.created_at DESC, q.id DESC +LIMIT 20; + +-- 3.3 全表差异留档(修正前后仅整体偏移, n 与结构不变; 供留档) +SELECT '3.3 修正前后列计数(应逐列一致)' AS check_name; +SELECT b.tbl, b.col, b.n AS n_before, a.n AS n_after +FROM diag_test.fix_before b JOIN diag_test.fix_after a USING (tbl,col) +WHERE b.n IS DISTINCT FROM a.n; + +-- 3.4 列类型(仍应为 timestamptz, 残余 without=0) +SELECT '3.4 残余 timestamp without time zone(应0)' AS check_name; +SELECT count(*) AS remain_without +FROM information_schema.columns +WHERE table_schema='nekobox' AND data_type='timestamp without time zone' + AND column_name IN ('created_at','updated_at','deleted_at'); + +-- PART 4: 回滚(需要时才执行; 当前被注释) --------------------------------------- +-- 若修正后发现问题需回到"错误态"(UTC 基准): +-- 把 PART 2 的 USING 子句换成 (%I AT TIME ZONE 'Asia/Shanghai' AT TIME ZONE 'UTC') +-- 即: ALTER TABLE nekobox.xxx ALTER COLUMN c TYPE timestamptz +-- USING (c AT TIME ZONE 'Asia/Shanghai' AT TIME ZONE 'UTC'); +-- 可先对比 diag_test.fix_before 快照确认还原。 diff --git a/outputs/timestamptz-migration-online.sql b/outputs/timestamptz-migration-online.sql new file mode 100644 index 0000000..85a17a9 --- /dev/null +++ b/outputs/timestamptz-migration-online.sql @@ -0,0 +1,158 @@ +-- ============================================================================ +-- TamaBox 时间列 timestamptz 迁移脚本(线上执行版) +-- 前置: 本脚本已在你提供的生产克隆库(nekobox_clone)完整验证通过: +-- * 迁移后 epoch 与迁移前逐项一致(差异 0) +-- * 回滚路径同样验证无损(可安全回退) +-- * 会话时区无关(验证时使用 Asia/Shanghai 会话) +-- 实际受影响表(含数据): questions / users / censor_logs / upload_images +-- 其余表(conversations/messages/votes/...)时间列本来就是 timestamptz, 脚本会自动跳过 +-- 覆盖: 只读 + ALTER(DDL), 建议低峰窗口执行; 克隆实测全库 1.7s 完成 +-- 使用: psql/pgAdmin 整段按 PART 顺序执行, 把输出贴回核对 +-- 注意: 迁移期间避免应用滚动发布; 执行前确认无长时间运行事务持锁 +-- ============================================================================ + +-- ============================================================================ +-- PART 0 前置核对: 列出将被迁移的列(线上应为 4 表 x 3 列 = 12 列) +-- ============================================================================ +SELECT 'PART 0: 将被迁移的无时区时间列' AS step; +SELECT table_name, column_name +FROM information_schema.columns +WHERE table_schema = 'nekobox' + AND data_type = 'timestamp without time zone' + AND column_name IN ('created_at','updated_at','deleted_at') +ORDER BY table_name, column_name; + +-- ============================================================================ +-- PART 1 迁移前 epoch 快照(存入 diag_test schema, 供 PART 3 自动比对) +-- ============================================================================ +SELECT 'PART 1: 迁移前快照' AS step; +CREATE SCHEMA IF NOT EXISTS diag_test; +DROP TABLE IF EXISTS diag_test.snap_before; +CREATE TABLE diag_test.snap_before(tbl text, col text, n bigint, minv numeric, maxv numeric, s numeric); +DO $$ +DECLARE r record; +BEGIN + FOR r IN + SELECT table_name tbl, column_name col + FROM information_schema.columns + WHERE table_schema='nekobox' AND data_type='timestamp without time zone' + AND column_name IN ('created_at','updated_at','deleted_at') + ORDER BY table_name, column_name + LOOP + EXECUTE format( + 'INSERT INTO diag_test.snap_before SELECT %L, %L, count(%I), min(extract(epoch FROM %I)*1000000000), max(extract(epoch FROM %I)*1000000000), sum(extract(epoch FROM %I)*1000000000) FROM nekobox.%I', + r.tbl, r.col, r.col, r.col, r.col, r.col, r.tbl); + END LOOP; +END $$; +SELECT '快照完成, 共 ' || count(*) || ' 列' AS info FROM diag_test.snap_before; + +-- ============================================================================ +-- PART 2 执行迁移 +-- 核心语义: 库存值是 UTC 墙钟, 用 AT TIME ZONE 'UTC' 显式解释为 timestamptz, +-- 与会话时区无关。绝不可用裸 ALTER(会按会话时区解释 -> 全部 -8h 偏移)。 +-- ============================================================================ +SELECT 'PART 2: 执行迁移' AS step; +DO $$ +DECLARE r record; +BEGIN + FOR r IN + SELECT table_name tbl, column_name col + FROM information_schema.columns + WHERE table_schema='nekobox' AND data_type='timestamp without time zone' + AND column_name IN ('created_at','updated_at','deleted_at') + ORDER BY table_name, column_name + LOOP + EXECUTE format( + 'ALTER TABLE nekobox.%I ALTER COLUMN %I TYPE timestamptz USING %I AT TIME ZONE ''UTC''', + r.tbl, r.col, r.col); + END LOOP; +END $$; +SELECT '迁移完成' AS step; + +-- ============================================================================ +-- PART 3 验收(4 项全绿 = 迁移成功; 任一项不满足立即执行 PART 4 回滚) +-- ============================================================================ +SELECT 'PART 3: 验收' AS step; + +-- 3.1 迁移后快照并自动比对: 差异应为 0 行 +DROP TABLE IF EXISTS diag_test.snap_after; +CREATE TABLE diag_test.snap_after(tbl text, col text, n bigint, minv numeric, maxv numeric, s numeric); +DO $$ +DECLARE r record; +BEGIN + FOR r IN + SELECT table_name tbl, column_name col + FROM information_schema.columns + WHERE table_schema='nekobox' AND data_type='timestamp with time zone' + AND column_name IN ('created_at','updated_at','deleted_at') + ORDER BY table_name, column_name + LOOP + EXECUTE format( + 'INSERT INTO diag_test.snap_after SELECT %L, %L, count(%I), min(extract(epoch FROM %I)*1000000000), max(extract(epoch FROM %I)*1000000000), sum(extract(epoch FROM %I)*1000000000) FROM nekobox.%I', + r.tbl, r.col, r.col, r.col, r.col, r.col, r.tbl); + END LOOP; +END $$; +SELECT '3.1 迁移前后 epoch 差异(应为 0 行)' AS check_name; +SELECT b.tbl, b.col, b.n AS n_before, a.n AS n_after, + b.minv AS min_before, a.minv AS min_after, + b.maxv AS max_before, a.maxv AS max_after, + b.s AS sum_before, a.s AS sum_after +FROM diag_test.snap_before b +JOIN diag_test.snap_after a USING (tbl, col) +WHERE b.n IS DISTINCT FROM a.n OR b.minv IS DISTINCT FROM a.minv + OR b.maxv IS DISTINCT FROM a.maxv OR b.s IS DISTINCT FROM a.s; + +-- 3.2 残余无时区时间列(应为 0) +SELECT '3.2 残余 timestamp without time zone(应 0)' AS check_name; +SELECT count(*) AS remain_without +FROM information_schema.columns +WHERE table_schema='nekobox' AND data_type='timestamp without time zone' + AND column_name IN ('created_at','updated_at','deleted_at'); + +-- 3.3 关键行 epoch 指纹(应与迁移前/线上游标一致) +SELECT '3.3 关键行 epoch 指纹' AS check_name; +SELECT id, (extract(epoch FROM created_at)*1000000000)::numeric(30,0) AS epoch_ns +FROM nekobox.questions WHERE id IN (3109, 3089, 2411) ORDER BY id; + +-- 3.4 keyset 翻页抽查: 应精确返回 3088,2883,...,2411 共 18 条(与修复后线上第2页一致) +SELECT '3.4 keyset 翻页抽查(第2页)' AS check_name; +SELECT q.id +FROM nekobox.questions q +WHERE q.user_id = (SELECT id FROM nekobox.users WHERE domain='aoi') + AND q.deleted_at IS NULL AND q.answer <> '' AND q.is_private = false + AND q.is_pinned = false + AND (q.created_at < TIMESTAMPTZ '2026-09-05 00:01:16.678885+00' + OR (q.created_at = TIMESTAMPTZ '2026-09-05 00:01:16.678885+00' AND q.id < 3089)) +ORDER BY q.is_pinned DESC, q.created_at DESC, q.id DESC; + +-- ============================================================================ +-- PART 4 回滚(仅在 PART 3 验收不通过或线上出现异常时执行) +-- 还原为 timestamp, 与迁移前快照一致(已在克隆库验证无损) +-- ============================================================================ +-- SELECT 'PART 4: 回滚(按需执行)' AS step; +-- DO $$ +-- DECLARE r record; +-- BEGIN +-- FOR r IN +-- SELECT table_name tbl, column_name col +-- FROM information_schema.columns +-- WHERE table_schema='nekobox' AND data_type='timestamp with time zone' +-- AND column_name IN ('created_at','updated_at','deleted_at') +-- AND table_name IN ('questions','users','censor_logs','upload_images') +-- ORDER BY table_name, column_name +-- LOOP +-- EXECUTE format( +-- 'ALTER TABLE nekobox.%I ALTER COLUMN %I TYPE timestamp USING %I AT TIME ZONE ''UTC''', +-- r.tbl, r.col, r.col); +-- END LOOP; +-- END $$; +-- SELECT '回滚完成(可再次跑 PART 3 核验)' AS step; +-- ============================================================================ +-- 验收说明: +-- 3.1 = 0 行且 3.2 = 0、3.3 指纹与迁移前一致、3.4 翻出 18 条 -> 迁移成功 +-- 任何一项不符 -> 执行 PART 4 回滚后停止排查, 联系开发 +-- 迁移后建议: +-- 1) 重新部署应用(含 parsePinCursor 的 .UTC() 修复版本) +-- 2) 复跑今日翻页验收脚本, 预期 38 条唯一收敛 +-- 3) 确认无误后可清理 diag_test schema: DROP SCHEMA diag_test; +-- ============================================================================ diff --git a/outputs/tutorial-dual-cdn-split-routing.md b/outputs/tutorial-dual-cdn-split-routing.md new file mode 100644 index 0000000..87d9a57 --- /dev/null +++ b/outputs/tutorial-dual-cdn-split-routing.md @@ -0,0 +1,314 @@ +# 以狼的提问箱为例-免备案双 CDN 分流实战教程:境内走 EdgeOne、境外走 Cloudflare + +> **教程性质**: +> 本文以 狼的提问箱 项目为例,但所有原理与步骤对任何「不备案、有海外用户、想让境内/境外各走最优线路」的站点通用。 +> +> 场景速览:域名权威 DNS 托管在 **DNSPod**(免费版支持按「境内 / 境外 / 默认」线路返回不同解析结果);境内线路 CNAME 到**腾讯 EdgeOne 国际站**(免备案区域,大陆用户落到香港等最近节点,走腾讯跨境骨干,比 Cloudflare 免费版大陆绕行明显更快);境外/默认线路 CNAME 到 **Cloudflare 优选 IP**(经 Cloudflare for SaaS 自定义主机名识别流量,由既有 Cloudflare Tunnel 回源)。 + + +--- + +## 1. 为什么能这么搭 —— 三个关键认知 + +整套方案成立的前提,是先把三个「概念解耦」想清楚: + +### 1.1 Cloudflare for SaaS:让「流量识别」与「DNS 解析权」解耦 + +Cloudflare 普通接入(Free 套餐)要求把整域 NS 迁到 Cloudflare,这与「DNS 要放在 DNSPod 做分线路」**天然冲突**——NS 在谁手里,谁才说了算。 + +Cloudflare for SaaS(免费额度 100 个自定义主机名)绕开这个限制: + +- 你有一个**承载 zone**(例如 `cf-zone.example.net`,托管在 Cloudflare); +- 在承载 zone 里把目标域名(`box.example.com`)加为 **Custom Hostname**,并验证归属; +- Cloudflare 边缘从此「认识」这个域名:**任何带着 `Host: box.example.com` 到达 CF 边缘的请求**,都会被匹配证书、按配置路由(本项目为 Tunnel 回源)。 + +关键结论:**CF 侧只负责"来了流量怎么认、怎么转",不负责"流量怎么来"**。流量能不能到 CF 边缘,取决于你自己的 DNS(DNSPod)把境外用户解析到哪。所以「境外走 CF」必须在 DNSPod 配一条境外线路指向 CF 的 IP/CNAME——CF 自己不会拉客。 + +### 1.2 DNSPod 分线路:免费就能「同一域名,不同答案」 + +腾讯云解析(DNSPod)免费版就支持按查询来源返回不同记录:线路可选「中国境内 / 境外 / 默认」,境内细分到省、运营商。**默认线路是兜底**,任何未命中的查询都走它。 + +要理解一个易错点:**分线路的判定发生在 DNSPod 的权威服务器上**,依据是「递归 DNS 服务器的出口 IP 归属地」——所以「境外用户走境外线路」成立的前提是境外用户的递归 DNS(8.8.8.8 等)能真的问到 DNSPod 权威,且没被中间网络劫持/污染(第 6 节有实战案例)。 + +### 1.3 EdgeOne 国际站:选对「加速区域」就不用备案 + +EdgeOne 分「中国大陆可用区 / 全球可用区(不含中国大陆)/ 海外可用区」等区域配置。官方口径: + +- 选 **全球可用区(不含中国大陆)** 或海外区域 → **不要求 ICP 备案**; +- 选中国大陆区域 → 必须备案。 + +不备案的代价:大陆用户**没有本地节点**,请求落到最近的海外节点(大陆一般落香港,也有日韩/新加坡等),由腾讯跨境骨干回源。实测体验通常仍明显优于 Cloudflare 免费版大陆线路(后者常绕美/日且抖动大)——所以「不备案也选 EO 当境内线路」是有实测前提的,切换前建议先测速对比。 + +> 补充:Cloudflare for SaaS 启用通常需要账户先绑定支付方式,额度内不扣费。 + +--- + +## 2. 目标架构 + +``` + DNS 层 DNSPod(example.com 整域权威,免费版支持按线路返回) + NS = byron.dnspod.net / sunshine.dnspod.net(官方 NS) + box CNAME 记录 + ├─ 境内 ──▶ box.example.com.edgeone.example (EdgeOne 接入目标) + ├─ 境外 ──▶ cf-pref.example.net (CF 优选 IP 域名) + └─ 默认 ──▶ cf-pref.example.net (兜底,语义同境外) + ┌──────────────┴──────────────────────────────┐ +大陆用户 ▶▶(命中境内线路) ◀◀ 海外用户(命中境外/默认线路) + ▼ ▼ +EdgeOne 国际站 Cloudflare 边缘 +区域: 全球(不含中国大陆) 优选 IP: 198.51.100.x(示例段) +证书: TrustAsia, CN=box.example.com 识别: for SaaS 自定义主机名 +回源: EO 直连源站公网端口 回源: Cloudflare Tunnel(纯出站) + │ │ + └──────────────────┬──────────────────────────┘ + ▼ + 源站防火墙 iptables+ipset(仅放行 EO 回源网段;cloudflared 走 127.0.0.1 不受影响) + ▼ + HTTP 应用直接监听公网高位端口(本项目 TamaBox,无 nginx) +``` + +两条回源路径互不干扰:EO 是 **入站直连**(需开放端口 + 白名单锁定),CF 是 **Tunnel 出站**(无需任何入站规则)。 + +--- + +## 3. 前置条件清单 + +| # | 条件 | 说明 | +|---|---|---| +| 1 | 一个域名(`example.com`),权威 DNS 托管在 DNSPod | 免费版即可;注册局委派的 NS = byron/sunshine.dnspod.net | +| 2 | 一个 Cloudflare 账户 + 承载 zone(`cf-zone.example.net`) | 用于 for SaaS 与 Tunnel;**域名本身的 DNS 不用迁给 CF** | +| 3 | cloudflared Tunnel 已在跑 | 服务器 → CF 纯出站连接,绑定承载域 `box.cf-zone.example.net` | +| 4 | 服务器有公网 IP,且能开一个高位入站端口 | 给 EO 回源用;**不需要 nginx**,应用直接监听即可 | +| 5 | EdgeOne 账户(本例国际站 edgeone.ai) | 选免备案区域 | +| 6 | CF 账户已绑支付方式 | 启用 for SaaS 的前提(额度内不扣费) | +| 7 | 服务器 1C1G 级别即可 | iptables/ipset 是内核规则,无常驻进程 | + +--- + +## 4. 分步实施 + +> 建议顺序:**先 CF(步骤 A)→ 再 EO(步骤 B)→ 再 DNS(步骤 C)→ 最后服务器(步骤 D)**。 +> 前两步做完,流量仍在旧路径上,随时可暂停;步骤 C/D 才真正切换与收敛。 + +### Step A —— Cloudflare 侧:SaaS 自定义主机名 + Tunnel(本次零改动,讲解原理) + +本项目 `box.example.com` 的 SaaS 自定义主机名此前已配好(放在承载 zone `cf-zone.example.net` 下),Tunnel 已正常回源。若从零配置,动作是: + +1. 承载 zone `cf-zone.example.net` → **SSL/TLS → Custom hostnames** → Add custom hostname,填 `box.example.com`; +2. 按提示完成归属验证(加一条 TXT 或 CNAME 验证记录); +3. 在 Tunnel 的路由里把 `box.example.com` 指到本地 HTTP 服务(`http://127.0.0.1:端口`); +4. 记录页里能拿到该主机名的 **CNAME target**(形如 `.cdn.cloudflare.net`)——它是「把流量引到 CF 边缘」的官方入口。 + +> ⚠️ 本项目实际没用 SaaS CNAME target,而是用**优选 IP CNAME(`cf-pref.example.net`)**:一个第三方维护的、解析到 CF 低延迟边缘 IP 的域名。原理相同——解析结果落在 CF 边缘,CF 靠 `Host: box.example.com` 识别出这是 SaaS 自定义主机名流量再按 Tunnel 路由。**优选域名的可用性依赖第三方维护,失效时换回官方 CNAME target 即可**(第 7 节维护清单)。 +> +> 本项目 DNSPod 上境外/默认线路指向的是 `cf-pref.example.net`。 + +### Step B —— EdgeOne 侧:添加站点(CNAME 接入,免备案区域) + +1. EO 控制台 → 添加站点 → 填 `box.example.com`; +2. **接入方式选 CNAME 接入**(⚠️ 不要选 NS 接入——NS 接入会要求把域名托管给 EO,与 DNSPod 分线路冲突,和「DNS 在 CF 手里没法分线路」是同一个问题); +3. **加速区域选「全球可用区(不含中国大陆)」**(免备案的关键选择); +4. 归属验证:按 EO 提示添加验证记录(本项目用 TXT:`edgeonereclaim.example.com TXT ...`),**记录加在 DNSPod 的默认线路**(CA/验证服务器多在境外,放默认线路全球可见最稳); +5. 配置回源:源站地址 = 你的公网 IP + 高位端口,Host 头 = `box.example.com`;回源协议按你的源站监听协议选(应用直监听 HTTP 就选 HTTP,TLS 由 EO 边缘终结); +6. 免费证书:CNAME 验证通过 + 回源配置就绪后,EO 自动签发(本项目 TrustAsia,`CN=box.example.com`)。签发需要几分钟到几小时——**在证书签发完成前,443 会拿 `*.cdn.myqcloud.com` 兜底证书应答**,浏览器会出现证书/HSTS 报错(第 6 节排障 6.1),属正常过程,等签发即可; +7. **开启「客户端 IP 头」**(关键,默认关闭!):站点 → 网络优化 / 规则引擎 → 客户端 IP 头部 → 开启,**自定义头部名必须填 `EO-Client-IP`**——应用侧固定读取这个名字; +8. **删除/改写伪造的 CF 头**:在 EO 加一条规则引擎规则,把客户端可能携带的 `CF-Connecting-IP` / `X-Real-IP` 等头删掉——否则大陆攻击者经 EO 带假 CF 头,会被应用当成 CF 流量优先信任(头信任模型见 Step D)。 + +### Step C —— DNSPod 分线路:三条记录 + +权威 DNS 在 DNSPod(整域 zone `example.com`),所以**直接在整域 zone 里配,不需要任何子域委派**。 + +| 主机记录 | 类型 | 线路 | 记录值 | TTL | +|---|---|---|---|---| +| `box` | CNAME | **中国境内** | `box.example.com.edgeone.example`(EO 分配的目标) | 120~600 | +| `box` | CNAME | **境外** | `cf-pref.example.net`(CF 优选 / 或 SaaS CNAME target) | 600 | +| `box` | CNAME | **默认** | `cf-pref.example.net`(兜底,语义同境外) | 600 | + +要点: + +- **EO 归属验证 TXT 保持「默认」线路**(全球可见),别只放境内; +- 若之前误把 EO 的 CNAME 建在「默认」线路,会导致全球都走 EO——把它改成「中国境内」,境外/默认补 CF 两条; +- TTL 别太大,方便回滚与换优选域时快速生效。 + +### Step D —— 服务器侧:应用监听 + 信任头 + 端口锁定 + +#### D1 应用直接监听公网端口(免 nginx) + +本项目 TamaBox 自带 HTTP 服务器,改配置即可: + +```ini +[server] +listen = 0.0.0.0:18080 ; 从仅本机 127.0.0.1 改为全网卡,EO 才能远程连入(18080 仅为示例端口) +``` + +- cloudflared 连的是 `127.0.0.1:端口`,`0.0.0.0` 监听兼容回环连入,**Tunnel 分支不受影响**; +- nginx 在本方案中从头到尾不是必需——防火墙(iptables/ufw)是内核规则,零常驻进程,比 nginx 轻得多,适合 1C1G 小机器。 + +#### D2 应用信任两家 CDN 的权威头 + +`conf/app.ini`: + +```ini +[security] +trust_proxy = true +``` + +配合代码层支持(本项目 `internal/shared/ip.go` 的 `ResolveClientIP`),信任顺序: + +1. `CF-Connecting-IP`(Cloudflare 权威头,海外分支); +2. `EO-Client-IP`(EdgeOne 权威头,境内分支); +3. 兜底:TCP 对端 RemoteAddr。 + +> ⚠️ **头信任的安全前提(缺一不可)**: +> 1. 源站防火墙**只放行两家 CDN 的回源来源**(EO 直连需要;CF 分支天然安全——Tunnel 是出站,外人到不了源站); +> 2. EO 侧已删除伪造的 CF 头(Step B-8); +> 3. 若还有 CF 侧直连,同样在 CF 规则里删除伪造的 EO 头。 +> +> 任一缺失,「信任头」就会被攻击者直连源站 + 自带假头绕过——限流/封禁会拿到伪造 IP。 + +#### D3 端口白名单:iptables + ipset 自动维护(EO 免费档没有官方回源段) + +EO 官方回源清单由「源站防护 / Origin ACL」提供(配套 `DescribeOriginACL` API),**但该功能只支持付费套餐**——免费档在控制台找不到入口,也没有可拉取的清单 URL。 + +> 🔴 **免费档方案定稿(2026-09-03 实测)**:**不要**逐个收集 EO 出口 IP 做白名单——实测发现 EO 回源出口是**海量轮换节点池**(一次 23 秒抓包就出现 13 个不同出口、散布多个腾讯云 /16 段),逐 IP 白名单必然间歇漏放 → 境内访问偶发 **521**(EO 边缘回源失败)。正解 = 直接放行 EO 所属的**腾讯云大段**(CIDR 整段入清单,脚本原生支持)。实测生效清单见下。 + +交付脚本 `scripts/edgeone-origin-whitelist.sh`(bash,需 root,架构要点): + +- 白名单放 **ipset 集合** `EO_ORIGIN`,iptables 一条规则引用它:`自建链 EO_IN` 内「命中集合放行 → 其余 REJECT tcp-reset」。INPUT 层规则默认**只对公网网卡 eth0 生效**(`EO_IFACE` 可配,网卡名不同必改否则端口裸奔);cloudflared 本机回连走独立的 `-i lo` ACCEPT 放行,与网卡限定解耦; +- 更新走「临时集填充 → `ipset swap` 原子替换」:**同步全程无规则清空窗口**; +- **fail-safe**:拉取失败 / 清单为空 / 全非法 → 拒绝更新、保留现网,绝不误删导致端口裸奔; +- 命令:`sync`(周期入口)/ `auto`(采集当前回源 IP → 新段预警)/ `learn`(即时观测)/ `show` / `flush`(回滚)/ `--dry-run`; +- 清单来源:本地文件(`/etc/edgeone-origin/cidr.txt`)+ 可选 URL,取并集。脚本支持每行一个 IP 或 CIDR。 + +落地四步: + +```bash +# 1. 改端口(默认 18080 → 你的实际端口) +# 2. 安装 ipset +apt-get install -y ipset +# 3. 建清单:放行腾讯云 EO 大段(每行一个 CIDR,# 注释;以下为实测生效配置) +mkdir -p /etc/edgeone-origin +cat > /etc/edgeone-origin/cidr.txt <<'EOF' +43.146.0.0/16 +43.152.0.0/16 +43.168.0.0/16 +43.174.0.0/16 +43.175.0.0/16 +EOF +# 段哪来的?用脚本 auto / tcpdump 持续观察回源出口,把出现的 IP whois 归并到所属腾讯云段 +# 注意:种子/采样是 EO 的"出口 IP",不是应用日志里的客户端 IP(日志里是 EO-Client-IP, +# 客户端真实 IP,不能当白名单)!段级方案下无需逐个采种,新段靠 auto 月度预警 +bash edgeone-origin-whitelist.sh sync --dry-run +bash edgeone-origin-whitelist.sh sync +# 4. 验证:外网机器 nc -zv 18080 应 refused;境内访问 https://box.example.com 应正常(无 521) +# 5. 挂定时:cron「17 4 */3 * *」或 systemd timer 每 3 天一次 sync(EO 段以月计才变) +``` + +> 日后升级付费套餐:把 `DescribeOriginACL` API 的输出写入 `cidr.txt` 即可,脚本零改动。 + +--- + +## 5. 验证方法(含大陆 DNS 劫持陷阱) + +### 5.1 分线路是否生效(🔴 重点:别在大陆本机 nslookup 境外 DNS) + +大陆网络对发往境外公共 DNS(8.8.8.8 / 1.1.1.1 / 9.9.9.9 / OpenDNS,**UDP 53 和 TCP 53 都会被劫持**)的查询会返回**按境内线路伪造的答案**——在本机 `nslookup box.example.com 8.8.8.8` 永远显示 EO,即使境外线路早已配好。正确验证通道: + +```bash +# 境内视角(本机直接查即可,通道可信) +nslookup box.example.com 223.5.5.5 # 期望 → CNAME edgeone.example → 203.0.113.x(EO 示例段) +nslookup box.example.com 119.29.29.29 # 同上(DNSPod 自家 DNS) + +# 境外视角:用「境外服务器代为查询」,浏览器直接打开下面两个 API 之一 +# https://api.hackertarget.com/dnslookup/?q=box.example.com +# https://networkcalc.com/api/dns/lookup/box.example.com +# 期望 → CNAME cf-pref.example.net → 198.51.100.x(CF 边缘 IP 示例段) +``` + +两条结果**不一样 = 分线路生效**。 + +### 5.2 HTTPS 证书是否就绪 + +```bash +echo | openssl s_client -connect box.example.com:443 -servername box.example.com \ + | openssl x509 -noout -subject -issuer -dates +# 期望 subject = CN=box.example.com(而不是 *.cdn.myqcloud.com 兜底证书) +``` + +### 5.3 真实 IP 是否被正确识别 + +境内访问后看源站/EO 访问日志中的客户端 IP = 你的大陆公网出口 IP(说明 `EO-Client-IP` 生效);海外访问后同理应为你的海外出口 IP(`CF-Connecting-IP`)。 + +--- + +## 6. 今日排障实录(每个坑都值得记) + +### 6.1 「网站使用 HSTS」报错 = EO 证书还没签发(不是配置错) + +现象:DNS 切到 EO 后浏览器报 HSTS 错误页。 +原因链:之前走 CF HTTPS 时应用下发了 `Strict-Transport-Security: max-age=31536000; includeSubDomains`(按 ExternalURL 以 https 开头就对每个响应下发)→ 浏览器记录「一年内必须 HTTPS」→ 切到 EO 后证书尚未签发、443 拿 `*.cdn.myqcloud.com` 兜底证书 → 证书与域名不匹配 → HSTS 错误页。 +处理:等 EO 证书签发(几分钟~几小时)即可,**域名不在 HSTS preload 列表,浏览器自动恢复,无需清缓存**。紧急回滚 = DNS 改回 CF。 +(若在 preload 列表里才是真麻烦——需先修好证书再等 preload 移除,故平时别主动提交 preload。) + +### 6.2 误判「权威 DNS 在 Cloudflare」(方向性错误) + +现象:一度以为 `example.com` 权威在 Cloudflare,推导出「需要子域 NS 委派」的复杂方案,差点让用户在 CF 做一堆不存在 zone 的操作。 +根因:apex `example.com` 本身是一条 CNAME → `your-project.pages.dev`(Cloudflare Pages 项目)——nslookup 查 NS 时**一路跟随 CNAME 链**走到 pages.dev 的 NS(CF),被误读为「example.com zone 在 CF」。 +正确做法:**查域名权威必须问注册局(RDAP)或直查 SOA**,不能信递归 CNAME 链: + +```bash +# RDAP(注册局铁证):https://rdap.org/domain/example.com → 应返回 byron/sunshine.dnspod.net +# 或直查 SOA:nslookup -type=SOA example.com byron.dnspod.net +``` + +用户一句「我的 Cloudflare 根本没有 example.com zone」就是最有效的纠偏信号——**控制台里没有的 zone,DNS 上不可能归它管**。 + +### 6.3 「境外也返回 EO」的假象 = 大陆 DNS 劫持(连 TCP 53 都劫) + +现象:从大陆本机用 nslookup 测 8.8.8.8 / 9.9.9.9 / OpenDNS(UDP 和 TCP 都试),境外视角全部返回 EO,一度以为分线路没生效、甚至怀疑 DNSPod 配置错了。 +真相:大陆网络劫持出境 DNS 查询,返回按境内线路伪造的 EO 答案,请求根本没到境外服务器。 +破案手段:用**境外服务器**(hackertarget / networkcalc API)代为查询,立刻看到 CF 答案——DNSPod 三线路配置完全正确,从未出过错。教训见 5.1。 + +### 6.4 残留的阿里云验证记录 + +实测发现 DNSPod 上有历史残留 `_dnsauth.box.example.com CNAME → xxxxxxxx...aliyunauth.certificate-validations.com`(以前阿里云申请证书留下的)。`_dnsauth` / `_acme-challenge` 下的旧验证记录会干扰证书自动续期验证——**证书验证记录的坑**,建议确认证书正常后删除。 + +### 6.5 免费档没有「源站防护」,回源 IP 段拿不到 + +见 Step D3:免费档无官方清单,用 learn 观察法兜底;付费后切 `DescribeOriginACL`,脚本零改动。 + +--- + +## 7. 日常维护清单 + +| 周期 | 事项 | +|---|---| +| 证书到期前 | EO 免费证书自动续期并**重新做域名验证**——⚠️ CA 验证服务器多在境外,**所有验证记录务必放默认线路**;到期前留意 EO 控制台证书状态,失败会提示重新验证 | +| 每 3 天(定时任务) | 白名单 sync(EO 回源段 3~6 个月才变,每 3 天足够);sync 是全量重建,清单里删掉的旧 IP 会自动剔除 | +| 每月 | 抽查清单有无漏网的新回源 IP(auto 已每日自动补种,此处仅兜底核对);确认优选域名 `cf-pref.example.net` 仍解析到 CF 边缘(失效则换回官方 SaaS CNAME target,只改 DNSPod 一条记录) | +| EO 回源突然失败 | 先临时放行全段定位,再按 learn 结果收紧——EO 免费档收不到段变更通知,要有这个预案 | +| 长期 | 若升级 EO 付费套餐:启用源站防护拿官方段 → 接入 DescribeOriginACL 输出到 cidr.txt | + +--- + +## 8. 回滚 + +1. **快速回滚(境外也要回 CF 之外的兜底)**:DNSPod 把「境内」线路改指向 CF(或删掉境内线路,让默认兜底接管)→ 全球走 CF,分钟级生效; +2. **彻底回滚(回到纯 CF 时代)**:删除 EO 站点/记录、撤防火墙放行、DNSPod 三线路合并为默认→CF; +3. EO 证书到期前回滚,记得去 EO 控制台删除站点避免残留验证记录干扰。 + +--- + +## 附:配置快照(示例,2026-09-03 实测定稿,域名已脱敏) + +``` +域名: box.example.com(权威 DNS: DNSPod,NS=byron/sunshine.dnspod.net) +境内: CNAME box.example.com.edgeone.example → 203.0.113.x (EdgeOne 国际站,区域不含大陆,示例段) +境外/默认: CNAME cf-pref.example.net → 198.51.100.x (CF 优选 IP,示例段) +CF 侧: SaaS 自定义主机名(承载 zone cf-zone.example.net)+ Tunnel 出站回源 +EO 证书: TrustAsia, CN=box.example.com(签发后约 90 天到期,自动续期) +EO 归属验证: edgeonereclaim.example.com TXT(DNSPod 默认线路 ✅) +EO 客户端头: EO-Client-IP(手动开启,头名固定 EO-Client-IP) +源站: TamaBox 直监听 0.0.0.0:高位端口(无 nginx);iptables+ipset 白名单 +应用信任: trust_proxy=true;ResolveClientIP 信任 CF-Connecting-IP → EO-Client-IP → RemoteAddr +``` diff --git a/outputs/user-updates-2026-09-01-02.md b/outputs/user-updates-2026-09-01-02.md new file mode 100644 index 0000000..3f88ab2 --- /dev/null +++ b/outputs/user-updates-2026-09-01-02.md @@ -0,0 +1,37 @@ +# 近期更新速览(9 月 1 日 — 9 月 2 日) + +> 面向站点使用者的简要更新说明,已省略技术细节。 +> 提示:以下内容在服务端部署最新版本后才会全部生效。 + +--- + +## 2026-09-01 + +### 新增 / 改进 +- 管理后台的「功能设置」为提问、私聊、投票新增三种开放方式:**一直开放**、**指定时间段开放**、**每周固定时段循环开放**。以前定时开放一旦结束,功能就会一直关闭;现在可以设定每周循环时间,到期自动开启与关闭。 +- 未登录访客查看问题详情页时,「分享」按钮自动居中,页面更整齐。 + +### 修复 +- 修复未登录用户切换界面语言不生效的问题。 +- 全站提示文字(错误提示、操作结果、表单校验等)统一跟随所选界面语言显示,简体中文 / 繁體中文 / English / 日本語 不再混用。 + +--- + +## 2026-09-02 + +### 新增 / 改进 +- 投票的自定义回答框加入**实时字数统计**,超过字数上限会标红并阻止提交,不再被悄悄截断。 +- 站长创建投票时,每个选项文本的长度上限放宽到 300 字。 +- 标签与屏蔽词改为「标签块」式输入:回车或逗号即可生成一个词,点 × 删除,无需手动敲英文逗号分隔,并实时显示数量。 +- 提问、回答、追问、私聊消息的字数上限已统一,超出时会有明确提示。 +- 私聊的会话消息条数上限可在 1~200 之间自行设置(新用户默认 200 条)。 + +### 修复 +- 修复已发布投票在编辑保存后出现「未知的投票类型」、选项看似丢失的问题,现在保存后投票与选项均正常显示。 +- 修复「加载更多」按钮失效:公开主页与后台投票列表可以正常翻页;列表到底后按钮不再出现,连点也不会重复加载。 +- 修复头像、背景、分享卡片等图片偶尔加载超时失败的问题。 + +### 调整 +- 屏蔽词现在对提问、私聊(对方发来的消息)与投票的自定义内容**同时生效**;提问 / 私聊 / 投票三个设置面板展示同一份屏蔽词,改一处即全局同步。 +- 精简后台投票设置页,移除重复的「投票内容管理」入口(投票列表仍可从顶栏进入)。 +- 多项安全与稳定性加固(细节略)。 diff --git a/outputs/vote-i18n-audit-2026-09-01.md b/outputs/vote-i18n-audit-2026-09-01.md new file mode 100644 index 0000000..76c9a4d --- /dev/null +++ b/outputs/vote-i18n-audit-2026-09-01.md @@ -0,0 +1,53 @@ +# 投票页中文提示 Bug 排查 + 同类 i18n 缺口审计(2026-09-01) + +## 一、结论先行 +- **你报告的 `投票成功!感谢参与` 确属 Bug**:`route/vote/vote.go` 的 `Submit` 之前把成功提示硬编码成了中文,未走 i18n,所以无论访客界面语言设成什么,弹出的都是中文。 +- **已修复**:投票页全部用户提示 + 验证码包(共享根因,影响 6 个页面)。 +- **还有大量同类问题**:route 层另有 40+ 处硬编码中文 flash(含登录页直接把 db 中文错误弹给用户),以及 db 层的中文错误哨兵,属于系统性 i18n 缺口,建议作为下一批次修复(见第三节)。 + +## 二、本次已修复(可直接验收) +### 1. `route/vote/vote.go`(投票参与页,访客可见) +- `SetSuccessFlash("投票成功!感谢参与")` → `i18n.T(lang, "vote.flash.success")`。 +- `Page` / `Submit` 的全部 `SetErrorFlash("中文")` 改为对应 i18n 键(`vote.flash.notFound/notPublished/archived/ended/notStarted`、`vote.page.loginRequired/alreadyVoted`)。 +- 表单解析 `parseSubmission` 内约 25 条校验错误(单选/多选/评分/排名/表单字段必填、超长、自定义选项、序列化失败等)全部改为 `i18n.T(lang, ...)`,动态字段名以 `%s` 占位注入(标签本身是箱主自定的内容,不翻译)。 +- `censorCheck` 签名改为 `(ctx, lang, text)`,失败文案走 `censor.unavailable` 键。 +- 新增 i18n 键:`vote.err.fieldRequired/fieldCustomRequired/fieldCustomTooLong/fieldInvalidOption/fieldConfigError/fieldRankIncomplete/fieldRankRange/fieldRankDuplicate/fieldTooLong/fieldNotNumber/fieldRating/customTooLong/serialize/unknownType/invalidOption/optionDuplicate`(四语言已补齐)。 + +### 2. `internal/captcha/math.go`(验证码,共享根因) +- `Verify` / `VerifyMath` 增加 `lang` 参数,6 处硬编码中文错误(不能为空/格式错误/答案格式/已过期/服务异常/答案错误/验证码错误)改为 i18n 键。 +- 新增 i18n 键:`captcha.errEmpty/errFormat/errAnswerFormat/errExpired/errService/errAnswerWrong`(四语言已补齐)。 +- 副作用:登录、注册、找回密码、提问箱页的验证码错误现在也跟随界面语言(这 6 个调用点已同步传 `ctx.Lang()` 并把 `if !ok` 分支的硬编码 `验证码错误` 改为 `captcha.error` 键)。 +- 配套:`internal/context/context.go` 新增 `(*Context).Lang()` 方法(返回中间件注入的界面语言,未注入回退 `i18n.Default`),供后端 flash/错误本地化复用。 + +**验证**:gofmt 通过;`go build -overlay`(含 webp 屏障包)全绿;`go vet` 全绿;全量可运行测试(templates / i18n / vote / auth / question 等)通过。 + +## 三、尚未修复的同类问题(建议下一批次) +判定标准:用户可见的 flash / 错误信息硬编码中文、不跟随界面语言。按「访客可见 / 箱主后台」分级。 + +### P0 — 访客/公开页(与投票页同类,匿名用户可见,优先级最高) +| 文件:行 | 当前硬编码 | 建议键 | +|---|---|---| +| route/auth/login.go:49 | `errors.Cause(err).Error()` → `ErrBadCredential` "邮箱或密码错误" | `auth.errBadCredential` | +| route/auth/recover.go:124 | `用户不存在` | `auth.errUserNotFound` | +| route/auth/recover.go:70 / 86 / 105 / 169 | 邮件频繁/失败/验证码过期/密码修改成功 | `auth.*` | +| route/question/page.go:232 | `密码错误` | `question.errWrongPassword` | +| route/question/page.go:313 | `仅注册用户才能提问…` | `question.errLoginRequired` | +| route/question/page.go:322 / 345 | `不能给自己发起私聊` / `你已被对方拉黑…` | `question.*` | +| route/question/page.go:384 | `检测到重复提交,请稍后再试` | `question.errDuplicate` | +| route/question/follow_up.go:38/45/75/90/149/161/180 | 无权操作/未回答不能追问/等上一条/审核不可用/追问不存在/回答成功 等 | `question.*` | +| route/question/question.go:215/281/299/313/325 | 回答发布成功/操作成功/已读/未读 等 | `question.*` | +| internal/db/users.go:206-208 | `ErrBadCredential`/`ErrDuplicateEmail`/`ErrDuplicateDomain` 中文哨兵 | 改为键或 handler 层映射 | + +### P1 — 箱主后台(登录态可见,影响较小) +route/user/vote.go、profile.go、password.go、tags.go、harassment.go 等约 25 处硬编码中文 flash +(如 `投票已发布!分享链接:…`、`更新标签成功`、`页面访问密码已更新`、`私聊设置更新成功` 等)。 + +### P2 — 内部 API(JS 消费的 JSON,非 flash) +internal/captcha/math.go `VerifyHandler` 返回的 `请求格式错误` / `验证码 ID 不能为空`(JSON message,前端弹通用提示,影响低)。 + +## 四、建议的下一步 +1. **先修 P0(公开页)**:与投票页同类,直接决定匿名访客的语言体验,工作量约 8 个文件 + 约 30 个 i18n 键。 +2. 再修 P1(箱主后台)+ P2(可选)。 +3. db 层中文错误哨兵建议统一改为「哨兵错误 + handler 层按 `errors.Is` 映射 i18n」,避免翻译逻辑下沉到 db 包。 + +请确认是否按上述批次继续修复(特别是 P0 公开页),我可立即开工。 diff --git a/route/auth/login.go b/route/auth/login.go new file mode 100644 index 0000000..c47a18b --- /dev/null +++ b/route/auth/login.go @@ -0,0 +1,77 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package auth + +import ( + "path" + + "github.com/flamego/recaptcha" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + + "github.com/tamakyi/TamaBox/internal/captcha" + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/db" + "github.com/tamakyi/TamaBox/internal/form" + "github.com/tamakyi/TamaBox/internal/i18n" + "github.com/tamakyi/TamaBox/internal/shared" +) + +func Login(ctx context.Context) { + ctx.Success("auth/login") +} + +func LoginAction(ctx context.Context, f form.Login, recaptcha recaptcha.RecaptchaV3) { + if ctx.HasError() { + ctx.Success("auth/login") + return + } + + // Check captcha code (unified: recaptcha, turnstile, or math). + uri := ctx.Request().Request.RequestURI // Keep the query when redirecting. + ok, err := captcha.Verify(f.Recaptcha, shared.ResolveClientIP(ctx.Request().Request), ctx.Session, recaptcha, ctx.Lang()) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to check captcha") + ctx.SetErrorFlash(err.Error()) + ctx.Redirect(uri) + return + } + if !ok { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "captcha.error")) + ctx.Redirect(uri) + return + } + + user, err := db.Users.Authenticate(ctx.Request().Context(), f.Email, f.Password) + if err != nil { + if errors.Is(err, db.ErrBadCredential) { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "auth.errBadCredential")) + } else { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to authenticate user") + ctx.SetInternalErrorFlash() + } + ctx.Redirect(uri) + return + } + + to := ctx.Query("to") + to = path.Clean("/" + to) + if to == "" { + to = "/_/" + user.Domain + } + + // 会话固定防护:登录认证成功后、写入用户标识之前,重新生成会话 ID, + // 使登录前种下的匿名会话失效,防止攻击者借固定会话 ID 劫持已认证会话。 + if err := ctx.Session.RegenerateID(ctx.ResponseWriter(), ctx.Request().Request); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to regenerate session ID on login") + ctx.SetInternalErrorFlash() + ctx.Redirect(uri) + return + } + + ctx.Session.Set("uid", user.ID) + ctx.Session.Set("pwd_ver", user.PasswordVersion) + ctx.Redirect(to) +} diff --git a/route/auth/logout.go b/route/auth/logout.go new file mode 100644 index 0000000..4f52a18 --- /dev/null +++ b/route/auth/logout.go @@ -0,0 +1,14 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package auth + +import ( + "github.com/tamakyi/TamaBox/internal/context" +) + +func Logout(ctx context.Context) { + ctx.Session.Flush() + ctx.Redirect("/") +} diff --git a/route/auth/recover.go b/route/auth/recover.go new file mode 100644 index 0000000..e33b6c3 --- /dev/null +++ b/route/auth/recover.go @@ -0,0 +1,172 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package auth + +import ( + "os" + "time" + + "github.com/flamego/cache" + "github.com/flamego/recaptcha" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + "github.com/thanhpk/randstr" + + "github.com/tamakyi/TamaBox/internal/captcha" + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/db" + "github.com/tamakyi/TamaBox/internal/form" + "github.com/tamakyi/TamaBox/internal/i18n" + "github.com/tamakyi/TamaBox/internal/mail" + "github.com/tamakyi/TamaBox/internal/shared" +) + +func ForgotPassword(ctx context.Context) { + ctx.Success("auth/forgot-password") +} + +func ForgotPasswordAction(ctx context.Context, f form.ForgotPassword, cache cache.Cache, recaptcha recaptcha.RecaptchaV3) { + if ctx.HasError() { + ctx.Success("auth/forgot-password") + return + } + + // Check captcha code (unified: recaptcha, turnstile, or math). + ok, err := captcha.Verify(f.Recaptcha, shared.ResolveClientIP(ctx.Request().Request), ctx.Session, recaptcha, ctx.Lang()) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to check captcha") + ctx.SetErrorFlash(err.Error()) + ctx.Redirect("/forgot-password") + return + } + if !ok { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "captcha.error")) + ctx.Redirect("/forgot-password") + return + } + + user, err := db.Users.GetByEmail(ctx.Request().Context(), f.Email) + if err != nil { + if errors.Is(err, db.ErrUserNotExists) { + // 防邮箱枚举:不区分邮箱是否存在,统一渲染"已发送"提示页(不实际发信)。 + ctx.Data["email"] = f.Email + ctx.Success("auth/forgot-password-sent") + return + } + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get user by email") + ctx.SetInternalErrorFlash() + ctx.Redirect("/forgot-password") + return + } + + emailSentCacheKey := "forgot-password-email-sent:" + user.Email + _, err = cache.Get(ctx.Request().Context(), emailSentCacheKey) + if err != nil { + if !errors.Is(err, os.ErrNotExist) { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to read password recovery email sent cache") + } + } else { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "auth.errEmailFrequent")) + ctx.Redirect("/forgot-password") + return + } + + code := randstr.String(64) + recoveryCodeCacheKey := "forgot-password-recovery-code:" + code + if err := cache.Set(ctx.Request().Context(), recoveryCodeCacheKey, user.ID, 24*time.Hour); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to set password recovery code cache") + ctx.SetInternalErrorFlash() + ctx.Redirect("/forgot-password") + return + } + + if err := mail.SendPasswordRecoveryMail(user.Email, code); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to send password recovery mail") + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "auth.errEmailFailed")) + ctx.Redirect("/forgot-password") + return + } + + if err := cache.Set(ctx.Request().Context(), emailSentCacheKey, time.Now(), 2*time.Minute); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to set password recovery email cache") + } + + ctx.Data["email"] = user.Email + ctx.Success("auth/forgot-password-sent") +} + +func checkRecoverPasswordCode(ctx context.Context, cache cache.Cache) (*db.User, bool) { + code := ctx.Query("code") + recoveryCodeCacheKey := "forgot-password-recovery-code:" + code + userIDItf, err := cache.Get(ctx.Request().Context(), recoveryCodeCacheKey) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "auth.errCodeExpired")) + } else { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to read password recovery code cache") + ctx.SetInternalErrorFlash() + } + ctx.Redirect("/login") + return nil, false + } + + userID, ok := userIDItf.(uint) + if !ok { + logrus.WithContext(ctx.Request().Context()).WithField("user_id_itf", userIDItf).Error("Failed to convert user id interface to uint") + ctx.SetInternalErrorFlash() + ctx.Redirect("/login") + return nil, false + } + + user, err := db.Users.GetByID(ctx.Request().Context(), userID) + if err != nil { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "auth.errUserNotFound")) + ctx.Redirect("/login") + return nil, false + } + + return user, true +} + +func RecoverPassword(ctx context.Context, cache cache.Cache) { + user, ok := checkRecoverPasswordCode(ctx, cache) + if !ok { + return + } + + ctx.Data["User"] = user + ctx.Success("auth/password-recovery") +} + +func RecoverPasswordAction(ctx context.Context, cache cache.Cache, f form.RecoverPassword) { + user, ok := checkRecoverPasswordCode(ctx, cache) + if !ok { + return + } + if ctx.HasError() { + ctx.Data["User"] = user + ctx.Success("auth/password-recovery") + return + } + + code := ctx.Query("code") + recoveryCodeCacheKey := "forgot-password-recovery-code:" + code + if err := cache.Delete(ctx.Request().Context(), recoveryCodeCacheKey); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to delete password recovery code cache") + ctx.SetInternalErrorFlash() + ctx.Redirect("/login") + return + } + + if err := db.Users.UpdatePassword(ctx.Request().Context(), user.ID, f.NewPassword); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to update user password") + ctx.SetInternalErrorFlash() + ctx.Refresh() + return + } + + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "auth.errPasswordChanged")) + ctx.Redirect("/login") +} diff --git a/route/auth/register.go b/route/auth/register.go new file mode 100644 index 0000000..65d1e44 --- /dev/null +++ b/route/auth/register.go @@ -0,0 +1,92 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package auth + +import ( + "github.com/flamego/recaptcha" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + + "github.com/tamakyi/TamaBox/internal/captcha" + "github.com/tamakyi/TamaBox/internal/conf" + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/db" + "github.com/tamakyi/TamaBox/internal/form" + "github.com/tamakyi/TamaBox/internal/i18n" + "github.com/tamakyi/TamaBox/internal/shared" +) + +func Register(ctx context.Context) { + ctx.Success("auth/register") +} + +func RegisterAction(ctx context.Context, f form.Register, recaptcha recaptcha.RecaptchaV3) { + if ctx.HasError() { + ctx.Success("auth/register") + return + } + + // Check captcha code (unified: recaptcha, turnstile, or math). + ok, err := captcha.Verify(f.Recaptcha, shared.ResolveClientIP(ctx.Request().Request), ctx.Session, recaptcha, ctx.Lang()) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to check captcha") + ctx.SetErrorFlash(err.Error()) + ctx.Redirect("/register") + return + } + if !ok { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "captcha.error")) + ctx.Redirect("/register") + return + } + + if err := db.Users.Create(ctx.Request().Context(), db.CreateUserOptions{ + Name: f.Name, + Password: f.Password, + Email: f.Email, + Avatar: conf.Upload.DefaultAvatarURL, + Domain: f.Domain, + Background: conf.Upload.DefaultBackground, + Intro: "问你想问的", + Qrcodebackcolor: "#FDF8F0", + Qrcodecolor: "#C45500", + Usernamecolor: "#000000", + Introcolor: "#000000", + Dotscale: "0.35", + BackgroundImage: conf.Upload.DefaultBackgroundImageURL, + Backgroundimagealpha: "0.8", + Qrcodepdpcolor: "#C45500", + Acfunlink: "none", + Bililink: "none", + Weibolink: "none", + Bloglink: "box.shiroko.one", + Xiaohongshulink: "none", + Language: i18n.Resolve(f.Language), // 注册时选择的界面语言;留空回退站点默认 + }); err != nil { + switch { + case errors.Is(err, db.ErrDuplicateEmail): + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "auth.errDuplicateEmail"))) + case errors.Is(err, db.ErrDuplicateDomain): + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "auth.errDuplicateDomain"))) + case errors.Is(err, db.ErrBadCredential): + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "auth.errBadCredential"))) + + default: + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to create new user") + ctx.SetInternalError() + } + + ctx.Success("auth/register") + return + } + + // 成功提示跟随用户注册时选择的语言 + lang := "zh-CN" + if l, ok := ctx.Data["Lang"].(string); ok && l != "" { + lang = l + } + ctx.SetSuccessFlash(i18n.T(lang, "auth.register.success")) + ctx.Redirect("/login") +} diff --git a/route/home.go b/route/home.go new file mode 100644 index 0000000..ba2629a --- /dev/null +++ b/route/home.go @@ -0,0 +1,44 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package route + +import ( + "github.com/sirupsen/logrus" + + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/i18n" + "github.com/tamakyi/TamaBox/internal/stats" +) + +func Home(ctx context.Context) { + if v, err := stats.Get(ctx.Request().Context()); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Warn("Failed to compute site stats") + } else { + ctx.Data["SiteStats"] = v + } + ctx.Success("home") +} + +// SiteStatsAPI 返回首页"提问箱信息统计"的 JSON(服务端 30 分钟缓存), +// 供前端 setInterval 定时刷新,避免重新加载整页。 +func SiteStatsAPI(ctx context.Context) error { + v, err := stats.Get(ctx.Request().Context()) + if err != nil { + return ctx.JSONError(50000, i18n.T(ctx.Lang(), "home.errStats")) + } + return ctx.JSON(v) +} + +func Sponsor(ctx context.Context) { + ctx.Success("sponsor") +} + +func AboutMe(ctx context.Context) { + ctx.Success("about-me") +} + +func ChangeLogs(ctx context.Context) { + ctx.Success("change-logs") +} diff --git a/route/pixel/pixel.go b/route/pixel/pixel.go new file mode 100644 index 0000000..6764dc0 --- /dev/null +++ b/route/pixel/pixel.go @@ -0,0 +1,87 @@ +// Copyright 2024 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package pixel + +import ( + "io" + "net/http" + "path" + "strconv" + "strings" + "time" + + "github.com/sirupsen/logrus" + + "github.com/tamakyi/TamaBox/internal/conf" + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/i18n" +) + +// pixelSafeResponseHeaders 允许从上游透传到客户端的响应头白名单。 +// 绝不透传 Set-Cookie / Set-Cookie2 等,避免上游借像素代理向客户端注入会话或凭证。 +var pixelSafeResponseHeaders = []string{ + "Content-Type", + "Content-Length", + "Content-Encoding", + "Content-Disposition", + "Cache-Control", + "ETag", + "Expires", + "Last-Modified", + "Pragma", + "Vary", +} + +func Index(ctx context.Context) { + ctx.Success("pixel") +} + +func Proxy(ctx context.Context) error { + uri := ctx.Param("**") + + // 路径穿越防护:归一化后必须仍位于 /api/ 之下, + // 否则(如含 ../ 跳出 /api)直接拒绝,防止访问到未授权路径。 + cleaned := path.Clean("/api/" + uri) + if !strings.HasPrefix(cleaned, "/api/") { + return ctx.JSONError(http.StatusBadRequest, i18n.T(ctx.Lang(), "pixel.errPath")) + } + + userID := strconv.Itoa(int(ctx.User.ID)) + + // 仅允许只读 GET:写方法(POST/PUT/DELETE)在路由层已被限制为 GET, + // 此处不再处理请求体,杜绝被用作对上游的越权写入口。 + req, err := http.NewRequest(http.MethodGet, "http://pixel/", nil) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to create request") + return ctx.ServerError() + } + req.URL.Host = conf.Pixel.Host + req.URL.Path = cleaned + req.Header.Set("neko-user-id", userID) + + client := http.Client{Timeout: 10 * time.Second} + resp, err := client.Do(req) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to send request") + return ctx.ServerError() + } + defer func() { _ = resp.Body.Close() }() + + // 仅透传白名单内的安全响应头。 + for _, k := range pixelSafeResponseHeaders { + if v := resp.Header.Get(k); v != "" { + ctx.ResponseWriter().Header().Set(k, v) + } + } + ctx.ResponseWriter().WriteHeader(resp.StatusCode) + + _, err = io.Copy(ctx.ResponseWriter(), resp.Body) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to copy response") + return ctx.ServerError() + } + + return nil +} diff --git a/route/question/follow_up.go b/route/question/follow_up.go new file mode 100644 index 0000000..1712c57 --- /dev/null +++ b/route/question/follow_up.go @@ -0,0 +1,208 @@ +package question + +import ( + stdctx "context" + "fmt" + "unicode/utf8" + + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + + "github.com/tamakyi/TamaBox/internal/conf" + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/db" + "github.com/tamakyi/TamaBox/internal/form" + "github.com/tamakyi/TamaBox/internal/i18n" + "github.com/tamakyi/TamaBox/internal/mail" + "github.com/tamakyi/TamaBox/internal/security/censor" + "github.com/tamakyi/TamaBox/internal/shared" +) + +// isQuestioner 判断当前请求者是否为该提问的提问者。 +// 匿名提问者通过 token(URL 或表单隐藏域)验证;登录提问者通过账号 ID 验证。 +func isQuestioner(ctx context.Context, question *db.Question, token string) bool { + if question.Token != "" && question.Token == token { + return true + } + if ctx.IsLogged && question.AskerUserID != 0 && ctx.User.ID == question.AskerUserID { + return true + } + return false +} + +// PublishFollowUp 提问者在问题被回答后,用 token 继续追问。 +func PublishFollowUp(ctx context.Context, pageUser *db.User, question *db.Question, f form.PublishFollowUpQuestion) { + // govalid 校验失败(追问内容为空)时回显表单,与 AnswerFollowUp 同路径。 + // (旧实现漏掉该早退:required 失败后仍会继续 censor/入库,追问空内容也会被创建。) + if ctx.HasError() { + ctx.Success("question/item") + return + } + + // 追问内容长度上限(conf.Limits.FollowUpContentLen,[limits] 配置段), + // 与前端追问框 maxlength 同源,rune 计数。 + if utf8.RuneCountInString(f.Content) > conf.Limits.FollowUpContentLen { + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "form.followup.contentTooLong", conf.Limits.FollowUpContentLen)), f) + ctx.Success("question/item") + return + } + + token := ctx.Query("t") + if token == "" { + token = f.Token + } + + if !isQuestioner(ctx, question, token) { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "followup.errNoPermission")) + ctx.Redirect("/") + return + } + + // 只能对已回答的问题追问 + if question.Answer == "" { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "followup.errNotAnswered")) + ctx.Redirect(fmt.Sprintf("/_/%s/%d?t=%s", pageUser.Domain, question.ID, question.Token)) + return + } + + // 追问次数限制:先快速预检查(友好提示),CreateIfBelowLimit 内再原子兜底 + // (并发场景下 count-then-create 存在竞态,必须以数据库原子检查为准)。 + count, err := db.FollowUps.CountByQuestionID(ctx.Request().Context(), question.ID) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to count follow ups") + ctx.SetInternalErrorFlash() + ctx.Redirect(fmt.Sprintf("/_/%s/%d?t=%s", pageUser.Domain, question.ID, question.Token)) + return + } + if count >= db.MaxFollowUpCount { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "followup.errLimit", db.MaxFollowUpCount)) + ctx.Redirect(fmt.Sprintf("/_/%s/%d?t=%s", pageUser.Domain, question.ID, question.Token)) + return + } + + // 服务端校验"等主人回复":模板仅在前一条被回复后才展示追问表单, + // 但 POST 可被直接构造绕过,因此必须检查最新一条追问是否已回复。 + latest, err := db.FollowUps.GetLatestByQuestionID(ctx.Request().Context(), question.ID) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get latest follow up") + ctx.SetInternalErrorFlash() + ctx.Redirect(fmt.Sprintf("/_/%s/%d?t=%s", pageUser.Domain, question.ID, question.Token)) + return + } + if latest != nil && latest.Answer == "" { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "followup.errWaitReply")) + ctx.Redirect(fmt.Sprintf("/_/%s/%d?t=%s", pageUser.Domain, question.ID, question.Token)) + return + } + + if ctx.HasError() { + ctx.Success("question/item") + return + } + + // 内容安全检测 + censorResponse, err := censor.Text(ctx.Request().Context(), f.Content) + if err != nil { + // 审核源全部不可用:fail-closed,拒绝发布而非免审放行。 + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to censor follow up text") + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "censor.unavailable")) + ctx.Redirect(fmt.Sprintf("/_/%s/%d?t=%s", pageUser.Domain, question.ID, question.Token)) + return + } + if !censorResponse.Pass { + ctx.SetErrorFlash(censorResponse.ErrorMessage()) + ctx.Redirect(fmt.Sprintf("/_/%s/%d?t=%s", pageUser.Domain, question.ID, question.Token)) + return + } + + created, err := db.FollowUps.CreateIfBelowLimit(ctx.Request().Context(), db.CreateFollowUpOptions{ + QuestionID: question.ID, + Content: f.Content, + }) + if err != nil { + if errors.Is(err, db.ErrFollowUpLimitReached) { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "followup.errLimit", db.MaxFollowUpCount)) + ctx.Redirect(fmt.Sprintf("/_/%s/%d?t=%s", pageUser.Domain, question.ID, question.Token)) + return + } + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to create follow up") + ctx.SetInternalErrorFlash() + ctx.Redirect(fmt.Sprintf("/_/%s/%d?t=%s", pageUser.Domain, question.ID, question.Token)) + return + } + _ = created + + // 邮件通知提问箱主人(开启邮件提醒时) + shared.SafeGo(func() { + if pageUser.Notify == db.NotifyTypeEmail { + if err := mail.SendNewFollowUpMail(pageUser.Email, pageUser.Domain, question.ID, question.Content, f.Content); err != nil { + logrus.WithContext(stdctx.Background()).WithError(err).Error("Failed to send new follow up mail to user") + } + } + }) + + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "followup.flash.sent")) + ctx.Redirect(fmt.Sprintf("/_/%s/%d?t=%s", pageUser.Domain, question.ID, question.Token)) +} + +// AnswerFollowUp 提问箱主人回答某条追问。 +func AnswerFollowUp(ctx context.Context, pageUser *db.User, question *db.Question, f form.AnswerFollowUpQuestion) { + if ctx.User.ID != pageUser.ID { + ctx.Redirect("/") + return + } + + if ctx.HasError() { + ctx.Success("question/item") + return + } + + // 追问的回答内容长度上限:与主回答共用 conf.Limits.AnswerContentLen + // ([limits] 配置段),与前端回复框 maxlength 同源,rune 计数。 + if utf8.RuneCountInString(f.Answer) > conf.Limits.AnswerContentLen { + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "form.followup.answerTooLong", conf.Limits.AnswerContentLen)), f) + ctx.Success("question/item") + return + } + + followUpID := uint(ctx.ParamInt("followUpID")) + + // 内容安全检测 + censorResponse, err := censor.Text(ctx.Request().Context(), f.Answer) + if err != nil { + // 审核源全部不可用:fail-closed,拒绝发布而非免审放行。 + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to censor follow up answer") + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "censor.unavailable")) + ctx.Success("question/item") + return + } + if !censorResponse.Pass { + ctx.SetErrorFlash(censorResponse.ErrorMessage()) + ctx.Success("question/item") + return + } + + if err := db.FollowUps.UpdateAnswerByID(ctx.Request().Context(), question.ID, followUpID, f.Answer); err != nil { + if errors.Is(err, db.ErrFollowUpNotFound) { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "followup.errNotFound")) + ctx.Success("question/item") + return + } + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to answer follow up") + ctx.SetInternalErrorFlash() + ctx.Success("question/item") + return + } + + // 邮件通知提问者(留下邮箱时):复用"您的提问有了回复"模板,带 token 链接 + shared.SafeGo(func() { + if question.ReceiveReplyEmail != "" { + if err := mail.SendNewAnswerMail(question.ReceiveReplyEmail, pageUser.Domain, question.ID, question.Content, f.Answer, question.Token); err != nil { + logrus.WithContext(stdctx.Background()).WithError(err).Error("Failed to send follow up answer mail to questioner") + } + } + }) + + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "followup.flash.answered")) + ctx.Redirect(fmt.Sprintf("/_/%s/%d", pageUser.Domain, question.ID)) +} diff --git a/route/question/page.go b/route/question/page.go new file mode 100644 index 0000000..ab802d6 --- /dev/null +++ b/route/question/page.go @@ -0,0 +1,787 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package question + +import ( + "bytes" + stdctx "context" + "crypto/md5" + "fmt" + "image" + _ "image/gif" + _ "image/jpeg" + _ "image/png" + "io" + "mime/multipart" + "path/filepath" + "strings" + "time" + "unicode/utf8" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/flamego/recaptcha" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + "github.com/wuhan005/govalid" + + "github.com/tamakyi/TamaBox/internal/captcha" + "github.com/tamakyi/TamaBox/internal/conf" + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/db" + "github.com/tamakyi/TamaBox/internal/dbutil" + "github.com/tamakyi/TamaBox/internal/form" + "github.com/tamakyi/TamaBox/internal/i18n" + "github.com/tamakyi/TamaBox/internal/imagecheck" + "github.com/tamakyi/TamaBox/internal/mail" + "github.com/tamakyi/TamaBox/internal/security/censor" + "github.com/tamakyi/TamaBox/internal/shared" + "github.com/tamakyi/TamaBox/internal/storage" + templatepkg "github.com/tamakyi/TamaBox/internal/template" +) + +func Pager(ctx context.Context) { + domain := ctx.Param("domain") + + pageUser, err := db.Users.GetByDomain(ctx.Request().Context(), domain) + if err != nil { + if errors.Is(err, db.ErrUserNotExists) { + ctx.Redirect("/") + return + } else { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get user by domain") + ctx.SetInternalError() + } + ctx.Success("question/page") + return + } + ctx.Map(pageUser) + + // 个人页语言:永远跟随提问箱主人(pageUser)配置的语言,忽略访客 cookie;未配置时回退站点默认语言 + if pageUser.Language != "" { + lang := i18n.Resolve(pageUser.Language) + ctx.Data["Lang"] = lang + ctx.Data["LangCode"] = lang + } + + // 页面密码检查 + if pageUser.PagePassword != "" && !(ctx.IsLogged && ctx.User.ID == pageUser.ID) { + passKey := fmt.Sprintf("page_pass_%d", pageUser.ID) + if authorized, _ := ctx.Session.Get(passKey).(bool); !authorized { + // 记录原始请求地址(含 query,如带 token 的单题链接),验证通过后跳回此处而非默认首页 + ctx.Data["Next"] = ctx.Request().URL.RequestURI() + ctx.Data["PageUser"] = pageUser + ctx.Success("question/password") + return + } + } + + // 分页加载公开已回答的问题(首次加载 20 条,置顶优先) + // 多取 1 条探测是否仍有下一页,供模板决定「加载更多」按钮的初始可见状态, + // 避免内容不足一页时按钮仍然显示、点击后才消失。 + const pageQuestionsPageSize = 20 + pageQuestions, err := db.Questions.GetByUserID(ctx.Request().Context(), pageUser.ID, db.GetQuestionsByUserIDOptions{ + Cursor: &dbutil.Cursor{ + PageSize: pageQuestionsPageSize + 1, // 每页数量 + 1 条探测行 + }, + FilterAnswered: true, // 只显示已回答的问题 + PrivateStatus: 1, // 1 = 仅公开(is_private = false) + PinFirst: true, // 置顶的问题排在最前 + }) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get questions by page id") + ctx.SetInternalError() + ctx.Success("question/page") + return + } + pageQuestionHasMore := false + if len(pageQuestions) > pageQuestionsPageSize { + pageQuestions = pageQuestions[:pageQuestionsPageSize] + pageQuestionHasMore = true + } + + answeredCount, err := db.Questions.Count(ctx.Request().Context(), pageUser.ID, db.GetQuestionsCountOptions{ + FilterAnswered: true, + }) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to count questions") + ctx.SetInternalError() + ctx.Success("question/page") + return + } + + // 页面标题语言与页面语言保持一致:Data["Lang"] 已由 Pager 上方逻辑或 Contexter 解析好 + // (提问箱主人语言 > 站点默认语言 shared.App > i18n.Default;个人页忽略访客 cookie)。 + titleLang := i18n.Default + if l, ok := ctx.Data["Lang"].(string); ok && l != "" { + titleLang = l + } + ctx.SetTitle(fmt.Sprintf("%s - %s", pageUser.Name, i18n.T(titleLang, "site.title"))) + + ctx.Data["IsUserPage"] = true + ctx.Data["IsOwnPage"] = ctx.IsLogged && ctx.User.ID == pageUser.ID + ctx.Data["PageUser"] = pageUser + ctx.Data["PageQuestions"] = pageQuestions + ctx.Data["PageQuestionHasMore"] = pageQuestionHasMore + ctx.Data["AnsweredCount"] = answeredCount + ctx.Data["ChatMaxMessages"] = pageUser.ChatMaxMessages + + // 功能开关(开关 + 定时 + 定量收集)统一由 feature_controls 驱动: + // - 提问:关闭后隐藏提问框并提示原因; + // - 私聊:关闭后隐藏/禁用私聊入口; + // - 投票:关闭后投票 Tab 保留显示但置灰禁用,hover 提示原因(不再隐藏入口)。 + askState := db.FeatureStateOf(ctx.Request().Context(), pageUser.ID, db.FeatureQuestion) + ctx.Data["CanAsk"] = askState.Open && (ctx.IsLogged || pageUser.HarassmentSetting != db.HarassmentSettingTypeRegisterOnly) + ctx.Data["AskState"] = askState + // 二维码下的引导文案随「仅允许注册用户提问」设置联动,避免勾选后仍显示"谁都可以匿名提问"。 + ctx.Data["RegisterOnlyAsk"] = pageUser.HarassmentSetting == db.HarassmentSettingTypeRegisterOnly + if !askState.Open { + ctx.Data["AskClosedMessage"] = i18n.FeatureClosedMessage(titleLang, db.FeatureQuestion, askState.Reason) + } + // 关闭状态下展示更多信息:上次关闭时间 / 下次开放时间(含循环定时)。 + ctx.Data["AskNextOpenAtStr"] = formatFeatureTime(askState.NextOpenAt) + ctx.Data["AskLastCloseAtStr"] = formatFeatureTime(askState.LastCloseAt) + + chatState := db.FeatureStateOf(ctx.Request().Context(), pageUser.ID, db.FeatureChat) + ctx.Data["AllowChat"] = chatState.Open + ctx.Data["ChatState"] = chatState + + voteState := db.FeatureStateOf(ctx.Request().Context(), pageUser.ID, db.FeatureVote) + ctx.Data["VoteEnabled"] = voteState.Open + ctx.Data["VoteState"] = voteState + if !voteState.Open { + // 投票 Tab 置灰禁用时的原因提示(手动关闭 / 未到开放时间 / 已结束 / 已达上限)。 + ctx.Data["VoteClosedMessage"] = i18n.FeatureClosedMessage(titleLang, db.FeatureVote, voteState.Reason) + } + + // 个人主页初始 Tab:默认提问;支持 ?tab=votes 直达投票面板(可分享链接)。 + // hash(#votes)优先级更高,由前端 JS 在渲染后覆盖。 + // 投票功能关闭时投票 Tab 置灰不可点,直达链接 ?tab=votes 回落到提问 Tab, + // 否则会渲染出一个所有面板都隐藏的空页面。 + activeTab := ctx.Query("tab") + if activeTab != "votes" || !voteState.Open { + activeTab = "questions" + } + ctx.Data["ActiveProfileTab"] = activeTab + + // 匿名投票板块:该箱主"进行中"的公开投票(个人主页投票 Tab 展示,最多 20 条)。 + // 箱主关闭投票功能时不展示任何投票(也不再浪费一次查询)。 + pageVotes := []*db.Vote{} + if voteState.Open { + pageVotes, err = db.Votes.ListPublishedPublicByUserID(ctx.Request().Context(), pageUser.ID, 20) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Warn("Failed to list page votes") + pageVotes = []*db.Vote{} + } + } + ctx.Data["PageVotes"] = pageVotes + + // 设置下一页游标(如果有数据)。置顶优先场景下必须使用复合键集游标, + // 否则置顶项与非置顶项 id 交错会造成"加载更多"漏掉介于其间的非置顶项。 + if len(pageQuestions) > 0 { + last := pageQuestions[len(pageQuestions)-1] + ctx.Data["PageQuestionCursor"] = db.EncodePinCursor(last.IsPinned, last.CreatedAt, last.ID) + } else { + ctx.Data["PageQuestionCursor"] = "" + } +} + +// conversationWithFirstMessage 用于在列表展示私聊时附带第一条消息 +type conversationWithFirstMessage struct { + Conversation *db.Conversation + FirstMessage string +} + +// formatFeatureTime 格式化功能开放/关闭时间供模板展示;nil 返回空串。 +func formatFeatureTime(t *time.Time) string { + if t == nil { + return "" + } + return t.Format("2006-01-02 15:04") +} + +func PasswordPage(ctx context.Context) { + domain := ctx.Param("domain") + pageUser, err := db.Users.GetByDomain(ctx.Request().Context(), domain) + if err != nil { + ctx.Redirect("/") + return + } + ctx.Data["PageUser"] = pageUser + // 直接访问密码页(无"上一页")时,验证后回首页 + ctx.Data["Next"] = "/_/" + domain + // 密码页同样遵循提问箱主人配置的语言 + if pageUser.Language != "" { + lang := i18n.Resolve(pageUser.Language) + ctx.Data["Lang"] = lang + ctx.Data["LangCode"] = lang + } + ctx.Success("question/password") +} + +func VerifyPagePassword(ctx context.Context) { + domain := ctx.Param("domain") + pageUser, err := db.Users.GetByDomain(ctx.Request().Context(), domain) + if err != nil { + ctx.Redirect("/") + return + } + password := ctx.Request().FormValue("password") + if pageUser.CheckPagePassword(password) { + passKey := fmt.Sprintf("page_pass_%d", pageUser.ID) + ctx.Session.Set(passKey, true) + // 验证成功后跳回原始页面(如带 token 的单题链接),避免一律回到首页 + next := ctx.Request().FormValue("next") + if next == "" || !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") || strings.Contains(next, "://") { + next = "/_/" + domain + } + ctx.Redirect(next) + } else { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "question.errWrongPassword")) + ctx.Redirect("/_/" + domain + "/password") + } +} + +func List(ctx context.Context) { + ctx.Success("question/list") +} + +func ListAPI(ctx context.Context) error { + domain := ctx.Param("domain") + pageSize := ctx.QueryInt("page_size") + cursorValue := ctx.Query("cursor") + + // 规范化每页大小,并多取 1 条用于探测是否仍有下一页(has_more), + // 使前端在加载完最后一页后能立即隐藏「加载更多」按钮, + // 而不是依赖下一次点击返回空列表来收尾(避免最后一页重复展示)。 + if pageSize < 1 { + pageSize = dbutil.DefaultPageSize + } + if pageSize > dbutil.MaxDefaultPageSize-1 { + pageSize = dbutil.MaxDefaultPageSize - 1 + } + + pageUser, err := db.Users.GetByDomain(ctx.Request().Context(), domain) + if err != nil { + if errors.Is(err, db.ErrUserNotExists) { + return ctx.JSONError(40400, i18n.T(ctx.Lang(), "auth.errUserNotFound")) + } + return ctx.ServerError() + } + + pageQuestions, err := db.Questions.GetByUserID(ctx.Request().Context(), pageUser.ID, db.GetQuestionsByUserIDOptions{ + Cursor: &dbutil.Cursor{ + Value: cursorValue, + PageSize: pageSize + 1, + }, + FilterAnswered: true, + PrivateStatus: 1, // 只返回公开问题 + PinFirst: true, + }) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get questions by page id") + return ctx.ServerError() + } + + // 实际取回条数超过 pageSize 说明还有下一页;裁掉多取的探测行。 + hasMore := false + if len(pageQuestions) > pageSize { + pageQuestions = pageQuestions[:pageSize] + hasMore = true + } + + // 列表 API 返回纯文本内容(剥离 Markdown 符号/排版,与首屏展示一致) + for _, q := range pageQuestions { + q.Content = templatepkg.PlainText(q.Content) + } + + // 响应直接附带服务端编码好的下一页复合键集游标(与 EncodePinCursor 一致)。 + // 不在前端用 Date.getTime()*1e6 自行拼游标:JS 双精度浮点无法精确表示纳秒 + // 级 UnixNano(毫秒以下精度丢失),时间戳相同的提问会在翻页边界被跳过。 + resp := struct { + Data []*db.Question `json:"data"` + NextCursor string `json:"next_cursor"` + HasMore bool `json:"has_more"` + }{Data: pageQuestions, HasMore: hasMore} + if len(pageQuestions) > 0 { + last := pageQuestions[len(pageQuestions)-1] + resp.NextCursor = db.EncodePinCursor(last.IsPinned, last.CreatedAt, last.ID) + } + return ctx.JSON(resp) +} + +func New(ctx context.Context, f form.NewQuestion, pageUser *db.User, recaptcha recaptcha.RecaptchaV3) { + + // 提问密码检查 + if pageUser.AskPassword != "" { + if !pageUser.CheckAskPassword(f.AskPassword) { + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "question.errAskPasswordWrong")), f) + ctx.Success("question/list") + return + } + } + + // 提问功能开关 / 定时 / 定量:任一条件不满足即拒绝普通提问(纵深防御,页面入口已隐藏表单)。 + // 私聊请求不受影响:提问与私聊是相互独立的功能,提问关闭不应阻断已开启的私聊。 + isChatRequest := f.StartChat == "true" && ctx.IsLogged + askState := db.FeatureStateOf(ctx.Request().Context(), pageUser.ID, db.FeatureQuestion) + if !askState.Open && !isChatRequest { + lang := i18n.Default + if l, ok := ctx.Data["Lang"].(string); ok && l != "" { + lang = l + } + ctx.SetErrorFlash(i18n.FeatureClosedMessage(lang, db.FeatureQuestion, askState.Reason)) + ctx.Redirect("/_/" + pageUser.Domain) + return + } + + if !ctx.IsLogged && pageUser.HarassmentSetting == db.HarassmentSettingTypeRegisterOnly { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "question.errLoginRequired")) + ctx.Redirect(fmt.Sprintf("/login?to=%s", ctx.Request().Request.RequestURI)) + return + } + + // ---------- 私聊处理 ---------- + if f.StartChat == "true" && ctx.IsLogged { + + if ctx.User.ID == pageUser.ID { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "question.errSelfChat")) + ctx.Redirect("/_/" + pageUser.Domain) + return + } + + // 私聊功能开关 / 定时 / 定量 + chatState := db.FeatureStateOf(ctx.Request().Context(), pageUser.ID, db.FeatureChat) + if !chatState.Open { + lang := i18n.Default + if l, ok := ctx.Data["Lang"].(string); ok && l != "" { + lang = l + } + ctx.SetErrorFlash(i18n.FeatureClosedMessage(lang, db.FeatureChat, chatState.Reason)) + ctx.Redirect("/_/" + pageUser.Domain) + return + } + + // 检查是否被对方拉黑 + blocked, err := db.Users.IsUserBlocked(ctx.Request().Context(), pageUser.ID, ctx.User.ID) + if err != nil { + logrus.WithError(err).Error("Failed to check block status") + } + if blocked { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "question.errBlockedChat")) + ctx.Redirect("/_/" + pageUser.Domain) + return + } + + // 检查每日消息限制 + if pageUser.DailyMessageLimit > 0 { + todayCount, err := db.Users.CountTodayMessagesFromUser(ctx.Request().Context(), pageUser.ID, ctx.User.ID) + if err != nil { + logrus.WithError(err).Error("Failed to count today messages") + } + if todayCount >= int64(pageUser.DailyMessageLimit) { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "question.errChatDailyLimit", pageUser.DailyMessageLimit)) + ctx.Redirect("/_/" + pageUser.Domain) + return + } + } + + if ctx.HasError() { + ctx.Success("question/list") + return + } + + // 私聊首条消息长度上限:与对话内后续消息一致(conf.Limits.ChatMessageLen, + // [limits] 配置段)。此分支与提问共用同一 content 字段,长度不能按提问上限约束, + // 必须在入口按聊天语义单独校验。 + if utf8.RuneCountInString(f.Content) > conf.Limits.ChatMessageLen { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "chat.errTooLong", conf.Limits.ChatMessageLen)) + ctx.Redirect("/_/" + pageUser.Domain) + return + } + + // 箱主全局屏蔽词(提问/私聊/投票共用一份词表):首条消息同样拦截, + // 防止通过发起私聊绕过提问入口的屏蔽词校验(发送者是对方,非箱主本人)。 + if _, hit := shared.BlockWordHit(pageUser.BlockWords, f.Content); hit { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "chat.errBlockWords")) + ctx.Redirect("/_/" + pageUser.Domain) + return + } + + // 私聊同样需要验证码校验(防止机器人批量发起私聊刷骚扰信息) + ok, err := captcha.Verify(f.Recaptcha, shared.ResolveClientIP(ctx.Request().Request), ctx.Session, recaptcha, ctx.Lang()) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to check captcha") + ctx.SetErrorFlash(err.Error()) + ctx.Redirect("/_/" + pageUser.Domain) + return + } + if !ok { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "captcha.error")) + ctx.Redirect("/_/" + pageUser.Domain) + return + } + + // 同 IP + 相同内容重复拦截(防刷屏) + if !shared.DuplicateGuard.Allow(shared.DuplicateKey(shared.ResolveClientIP(ctx.Request().Request), f.Content)) { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "question.errDuplicateSubmit")) + ctx.Redirect("/_/" + pageUser.Domain) + return + } + + // 内容安全检测 + censorResponse, err := censor.Text(ctx.Request().Context(), f.Content) + if err != nil { + // 审核源全部不可用:fail-closed,拒绝发布而非免审放行。 + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to censor text") + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "censor.unavailable")), f) + ctx.Success("question/list") + return + } + if !censorResponse.Pass { + ctx.SetError(errors.New(censorResponse.ErrorMessage()), f) + ctx.Success("question/list") + return + } + + maxMessages := pageUser.ChatMaxMessages + if maxMessages <= 0 { + // 存量兜底(老数据 / 极端配置):回落到系统硬顶 conf.Limits.ChatMaxMessages + maxMessages = conf.Limits.ChatMaxMessages + } + + conv, err := db.Conversations.Create(ctx.Request().Context(), db.CreateConversationOptions{ + OwnerID: pageUser.ID, + AskerID: ctx.User.ID, + MaxMessages: maxMessages, + }) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to create conversation") + ctx.SetInternalError(f) + ctx.Success("question/list") + return + } + + _, err = db.Messages.Create(ctx.Request().Context(), db.CreateMessageOptions{ + ConversationID: conv.ID, + SenderID: ctx.User.ID, + Content: f.Content, + }) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to create first message") + ctx.SetInternalError(f) + ctx.Success("question/list") + return + } + + if err := db.Conversations.IncrementMessageCount(ctx.Request().Context(), conv.ID); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to increment message count") + } + + // 私聊定量收集:新建会话即计一条(后续往来消息不重复计数) + if err := db.FeatureControls.IncrementQuota(ctx.Request().Context(), pageUser.ID, db.FeatureChat, 1); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Warn("Failed to increment chat quota") + } + + // 请求态数据提前提取,避免 goroutine 在请求结束后访问 ctx.User + askerName := ctx.User.Name + askerEmail := ctx.User.Email + shared.SafeGo(func() { + if pageUser.Notify == db.NotifyTypeEmail { + if err := mail.SendNewConversationMail(pageUser.Email, askerName, pageUser.Domain, conv.Token, f.Content); err != nil { + logrus.WithContext(stdctx.Background()).WithError(err).Error("Failed to send new conversation mail to owner") + } + if err := mail.SendNewConversationMail(askerEmail, askerName, pageUser.Domain, conv.Token, f.Content); err != nil { + logrus.WithContext(stdctx.Background()).WithError(err).Error("Failed to send new conversation mail to asker") + } + } + }) + + chatURL := fmt.Sprintf("/_/%s/chat/%s", pageUser.Domain, conv.Token) + chatAbsURL := fmt.Sprintf("%s%s", strings.TrimRight(conf.App.ExternalURL, "/"), chatURL) + + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "question.flash.chatSent", chatAbsURL)) + ctx.Redirect("/_/" + pageUser.Domain) + return + } + + // ---------- 普通提问 ---------- + + // 提问内容长度上限(conf.Limits.QuestionContentLen,[limits] 配置段), + // 与前端提问框 maxlength 同源。旧实现依赖 govalid maxlen 标签(写死 2000, + // 无法随配置调整),现移到此处以 rune 计数校验。 + if utf8.RuneCountInString(f.Content) > conf.Limits.QuestionContentLen { + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "form.question.contentTooLong", conf.Limits.QuestionContentLen)), f) + ctx.Success("question/list") + return + } + + var receiveReplyEmail string + if f.ReceiveReplyViaEmail != "" { + if errs, ok := govalid.Check(struct { + Email string `valid:"required;email" label:"邮箱地址" msg:"form.email.required"` + }{ + Email: f.ReceiveReplyEmail, + }); !ok { + ctx.SetError(errs[0], f) + ctx.Success("question/list") + return + } + receiveReplyEmail = f.ReceiveReplyEmail + } + + if ctx.HasError() { + ctx.Success("question/list") + return + } + + // Check captcha code (unified: recaptcha, turnstile, or math). + ok, err := captcha.Verify(f.Recaptcha, shared.ResolveClientIP(ctx.Request().Request), ctx.Session, recaptcha, ctx.Lang()) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to check captcha") + ctx.SetErrorFlash(err.Error()) + ctx.Redirect("/_/" + pageUser.Domain) + return + } + if !ok { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "captcha.error")) + ctx.Redirect("/_/" + pageUser.Domain) + return + } + + content := f.Content + isPrivate := f.IsPrivate != "" + + // 统一走 shared.ResolveClientIP:仅 trust_proxy=true 时信任代理头,防止伪造 IP 混入审计记录 + fromIP := shared.ResolveClientIP(ctx.Request().Request) + + // 同 IP + 相同内容重复拦截(防刷屏) + if !shared.DuplicateGuard.Allow(shared.DuplicateKey(fromIP, content)) { + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "question.errDuplicateSubmit")), f) + ctx.Success("question/list") + return + } + + // 箱主全局屏蔽词(逗号分隔,提问/私聊/投票共用一份词表):命中即拒绝。 + if _, hit := shared.BlockWordHit(pageUser.BlockWords, content); hit { + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "question.errBlockWords")), f) + ctx.Success("question/list") + return + } + + censorResponse, err := censor.Text(ctx.Request().Context(), content) + if err != nil { + // 审核源全部不可用:fail-closed,拒绝发布而非免审放行, + // 避免审核服务宕机期间提问内容免审直接公开。 + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to censor text") + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "censor.unavailable")), f) + ctx.Success("question/list") + return + } + if !censorResponse.Pass { + errorMessage := censorResponse.ErrorMessage() + ctx.SetError(errors.New(errorMessage), f) + ctx.Success("question/list") + return + } + + // 统一走 shared.ResolveClientIP(已在重复拦截处解析,此处复用) + var askerUserID uint + if ctx.IsLogged { + askerUserID = ctx.User.ID + } + + question, err := db.Questions.Create(ctx.Request().Context(), db.CreateQuestionOptions{ + FromIP: fromIP, + UserID: pageUser.ID, + Content: content, + ReceiveReplyEmail: receiveReplyEmail, + AskerUserID: askerUserID, + IsPrivate: isPrivate, + }) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to create new question") + ctx.SetInternalError(f) + ctx.Success("question/list") + return + } + + // 提问定量收集:一条提问计一次(含私密提问);追问不重复计数 + if err := db.FeatureControls.IncrementQuota(ctx.Request().Context(), pageUser.ID, db.FeatureQuestion, 1); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Warn("Failed to increment question quota") + } + + if len(f.Images) > 0 { + image := f.Images[0] + if err := uploadImage(ctx, uploadImageOptions{ + Type: db.UploadImageQuestionTypeAsk, + Image: image, + QuestionID: question.ID, + UploaderUserID: askerUserID, + }); err != nil { + if errors.Is(err, ErrUploadImageSizeTooLarge) || errors.Is(err, imagecheck.ErrImageTooLarge) { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "question.errImageTooLarge")) + ctx.Success("question/list") + return + } else { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to upload image") + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "question.errUploadImageFailed")), f) + ctx.Success("question/list") + return + } + } + } + + if err := db.Questions.UpdateCensor(ctx.Request().Context(), question.ID, db.UpdateQuestionCensorOptions{ + ContentCensorMetadata: censorResponse.ToJSON(), + }); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to update question censor result") + } + + shared.SafeGo(func() { + if pageUser.Notify == db.NotifyTypeEmail { + if err := mail.SendNewQuestionMail(pageUser.Email, pageUser.Domain, question.ID, question.Content, question.Token); err != nil { + logrus.WithContext(stdctx.Background()).WithError(err).Error("Failed to send new question mail to user") + } + if err := mail.SendNewQuestionMailToUser(question.ReceiveReplyEmail, pageUser.Domain, question.ID, question.Content, question.Token); err != nil { + logrus.WithContext(stdctx.Background()).WithError(err).Error("Failed to send new question mail to questioner") + } + } + }) + + questionPrivateURL := fmt.Sprintf("/_/%s/%d?t=%s", pageUser.Domain, question.ID, question.Token) + questionPrivateAbsURL := fmt.Sprintf("%s%s", strings.TrimRight(conf.App.ExternalURL, "/"), questionPrivateURL) + + // 提问成功页:强提醒保存私密链接/token(尤其针对未留邮箱的匿名提问者) + ctx.Data["Question"] = question + ctx.Data["PrivateURL"] = questionPrivateURL + ctx.Data["PrivateAbsURL"] = questionPrivateAbsURL + ctx.Data["HasReceiveEmail"] = receiveReplyEmail != "" + titleLang := i18n.Default + if l, ok := ctx.Data["Lang"].(string); ok && l != "" { + titleLang = l + } + ctx.SetTitle(i18n.T(titleLang, "success.pageTitle", i18n.T(titleLang, "site.title"))) + ctx.Success("question/success") +} + +type uploadImageOptions struct { + Type db.UploadImageQuestionType + Image *multipart.FileHeader + QuestionID uint + UploaderUserID uint + IsDeletingPrevious bool +} + +var ErrUploadImageSizeTooLarge = errors.New("图片文件大小不能大于 5Mb") + +func uploadImage(ctx context.Context, opts uploadImageOptions) error { + imgFile := opts.Image + fileName := imgFile.Filename + fileExt := filepath.Ext(fileName) + fileSize := imgFile.Size + if fileSize > 1024*1024*5 { + return ErrUploadImageSizeTooLarge + } + + uploadImageFile, err := imgFile.Open() + if err != nil { + return errors.Wrap(err, "open image") + } + defer func() { _ = uploadImageFile.Close() }() + + // 读取原始文件数据并计算 MD5 + hasher := md5.New() + originalData, err := io.ReadAll(io.TeeReader(uploadImageFile, hasher)) + if err != nil { + return errors.Wrap(err, "read image data") + } + fileMd5 := fmt.Sprintf("%x", hasher.Sum(nil)) + + // 根据格式决定是否转换为 WebP + var uploadData []byte + var contentType string + var uploadKey string + + // 检测原始格式(解码前先校验像素总量,防止解压炸弹) + if err := imagecheck.CheckPixelLimit(bytes.NewReader(originalData)); err != nil { + if errors.Is(err, imagecheck.ErrImageTooLarge) { + return imagecheck.ErrImageTooLarge + } + return errors.Wrap(err, "decode image config") + } + + _, format, err := image.Decode(bytes.NewReader(originalData)) + if err != nil { + return errors.Wrap(err, "decode image") + } + + now := time.Now() + switch format { + case "gif": + // GIF 保持原样上传,不转换(动画 GIF 需要 cwebp 工具支持) + uploadData = originalData + contentType = "image/gif" + uploadKey = fmt.Sprintf("%d/%d/%d%s", now.Year(), now.Month(), now.UnixNano(), fileExt) + default: + // JPEG / PNG 等静态图片转换为 WebP + webpData, err := storage.ConvertStaticImageToWebP(bytes.NewReader(originalData)) + if err != nil { + // 转换失败时回退为原始数据 + logrus.WithError(err).Warn("WebP conversion failed, falling back to original format") + uploadData = originalData + contentType = contentTypeFromFormat(format) + uploadKey = fmt.Sprintf("%d/%d/%d%s", now.Year(), now.Month(), now.UnixNano(), fileExt) + } else { + uploadData = webpData + contentType = "image/webp" + // WebP 无后缀名,与 UploadPictureToS3 风格一致 + uploadKey = fmt.Sprintf("%d/%d/%d%s", now.Year(), now.Month(), now.UnixNano(), ".webp") + } + } + + client, err := storage.GetS3Client() + if err != nil { + return errors.Wrap(err, "get S3 client") + } + if _, err := client.PutObject(ctx.Request().Context(), &s3.PutObjectInput{ + Bucket: aws.String(conf.Upload.ImageBucket), + Key: aws.String(uploadKey), + Body: bytes.NewReader(uploadData), + ContentLength: aws.Int64(int64(len(uploadData))), + ContentType: aws.String(contentType), + }); err != nil { + return errors.Wrap(err, "put object") + } + + _, err = db.UploadImages.Create(ctx.Request().Context(), db.CreateUploadImageOptions{ + Type: opts.Type, + QuestionID: opts.QuestionID, + UploaderUserID: opts.UploaderUserID, + Name: fileName, + FileSize: int64(len(uploadData)), + Md5: fileMd5, + Key: uploadKey, + IsDeletingPrevious: opts.IsDeletingPrevious, + }) + if err != nil { + return errors.Wrap(err, "create upload image") + } + return nil +} + +// contentTypeFromFormat 根据图片格式返回 MIME 类型 +func contentTypeFromFormat(format string) string { + switch format { + case "jpeg": + return "image/jpeg" + case "png": + return "image/png" + case "gif": + return "image/gif" + default: + return "application/octet-stream" + } +} diff --git a/route/question/question.go b/route/question/question.go new file mode 100644 index 0000000..a9c0d00 --- /dev/null +++ b/route/question/question.go @@ -0,0 +1,338 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package question + +import ( + stdctx "context" + "fmt" + "net/url" + "unicode/utf8" + + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + + "github.com/tamakyi/TamaBox/internal/conf" + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/db" + "github.com/tamakyi/TamaBox/internal/form" + "github.com/tamakyi/TamaBox/internal/i18n" + "github.com/tamakyi/TamaBox/internal/imagecheck" + "github.com/tamakyi/TamaBox/internal/mail" + "github.com/tamakyi/TamaBox/internal/security/censor" + "github.com/tamakyi/TamaBox/internal/shared" +) + +func Questioner(ctx context.Context, pageUser *db.User) { + // 从 URL query 读取 token;追问等 POST 请求 token 在表单隐藏域中,需回退读取表单字段。 + // FormValue 同时覆盖 query 与 body(含 multipart),对 GET 请求行为与 Query 一致。 + token := ctx.Query("t") + if token == "" { + token = ctx.Request().FormValue("token") + } + questionID := uint(ctx.ParamInt("questionID")) + question, err := db.Questions.GetByID(ctx.Request().Context(), questionID) + if err != nil { + if !errors.Is(err, db.ErrQuestionNotExist) { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get question by ID") + } + + ctx.Redirect("/") + return + } + ctx.Data["Question"] = question + + askUploadImages, err := db.UploadImages.GetByTypeQuestionID(ctx.Request().Context(), db.UploadImageQuestionTypeAsk, questionID) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get ask upload images") + } + ctx.Data["AskUploadImages"] = askUploadImages + + answerUploadImages, err := db.UploadImages.GetByTypeQuestionID(ctx.Request().Context(), db.UploadImageQuestionTypeAnswer, questionID) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get answer upload images") + } + ctx.Data["AnswerUploadImages"] = answerUploadImages + + // Check the question is belongs to the correct page user. + // If the question has not been answered, we should check the question is belongs to the correct page user. + // The questioner can use the token to view the question. + // 注意:token 为空的未回答/私密问题同样禁止匿名访问(不能因 token 为空而放行)。 + if question.UserID != pageUser.ID || + ((question.Answer == "" || question.IsPrivate) && + (!ctx.IsLogged || ctx.User.ID != question.UserID) && + !(question.Token != "" && question.Token == token)) { + ctx.Redirect("/") + return + } + + // The page's owner or the question's token can have the permission to delete the question. + // Inject the permission into the context. + canDelete := ctx.IsLogged && ctx.User.ID == pageUser.ID + ctx.Map(canDelete) + ctx.Data["CanDelete"] = canDelete + + // ---------- 追问 ---------- + followUps, err := db.FollowUps.GetByQuestionID(ctx.Request().Context(), questionID) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get follow ups") + followUps = []*db.FollowUp{} + } + ctx.Data["FollowUps"] = followUps + + // 提问者身份:token 匹配(匿名)或登录账号匹配(登录用户) + isQuestioner := isQuestioner(ctx, question, token) + ctx.Data["IsQuestioner"] = isQuestioner + + // 是否可追问:已回答 + 提问者 + 追问次数未达上限 + followUpRemaining := 0 + if isQuestioner && question.Answer != "" { + count, err := db.FollowUps.CountByQuestionID(ctx.Request().Context(), questionID) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to count follow ups") + } else { + followUpRemaining = db.MaxFollowUpCount - int(count) + } + } + // 是否可追问:已回答 + 提问者 + 追问次数未达上限 + 上一条追问已被主人回复 + // (主人尚未回复上一条追问时,提问者不应继续发起新的追问) + // 等待提示同样仅对提问者展示——主人/旁观者看到的应是回复框或正常内容。 + waitingFollowUpReply := false + if isQuestioner && len(followUps) > 0 && followUps[len(followUps)-1].Answer == "" { + waitingFollowUpReply = true + } + canFollowUp := isQuestioner && question.Answer != "" && followUpRemaining > 0 && !waitingFollowUpReply + ctx.Data["CanFollowUp"] = canFollowUp + ctx.Data["WaitingFollowUpReply"] = waitingFollowUpReply + ctx.Data["FollowUpRemaining"] = followUpRemaining + ctx.Data["FollowUpLimit"] = db.MaxFollowUpCount + // 供追问表单隐藏域回传(匿名提问者必须携带 token) + ctx.Data["QuestionToken"] = token + + // 返回来源:admin=从管理后台(/user/questions)进入;空=从提问箱主页(/_/domain)或直接访问, + // 默认返回提问箱主页。详情页底部"返回xxx的提问箱"按钮据此决定跳转目标。 + backFrom := ctx.Query("from") + ctx.Data["BackFrom"] = backFrom + // 从后台返回时,把进入时携带的筛选参数(sort/status/type/read/q)原样回传, + // 使"返回"跳回带筛选条件的后台列表,避免丢失已选的筛选/搜索条件。 + if backFrom == "admin" { + backQuery := url.Values{} + for _, key := range []string{"sort", "status", "type", "read", "q"} { + if v := ctx.Query(key); v != "" { + backQuery.Set(key, v) + } + } + backTo := "/user/questions" + if qs := backQuery.Encode(); qs != "" { + backTo += "?" + qs + } + ctx.Data["BackTo"] = backTo + } + + ctx.Map(question) +} + +func Item(ctx context.Context) { + ctx.Success("question/item") +} + +func PublishAnswer(ctx context.Context, pageUser *db.User, question *db.Question, f form.PublishAnswerQuestion) { + if ctx.HasError() { + ctx.Success("question/item") + return + } + + // 回答内容长度上限(conf.Limits.AnswerContentLen,[limits] 配置段), + // 与前端回答框 maxlength 同源(发布与编辑共用,rune 计数)。 + if utf8.RuneCountInString(f.Answer) > conf.Limits.AnswerContentLen { + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "form.answer.contentTooLong", conf.Limits.AnswerContentLen)), f) + ctx.Success("question/item") + return + } + + if ctx.User.ID != pageUser.ID { + ctx.Redirect("/") + return + } + + // 纵深防御:确认该提问归属当前页面箱主(Questioner 中间件已保证,这里二次校验防中间件改动引入越权)。 + if question.UserID != pageUser.ID { + ctx.Redirect("/") + return + } + + answer := f.Answer + + // 🚨 Content security check. + censorResponse, err := censor.Text(ctx.Request().Context(), answer) + if err != nil { + // 审核源全部不可用:fail-closed,拒绝发布而非免审放行。 + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to censor text") + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "censor.unavailable")), f) + ctx.Success("question/item") + return + } + if !censorResponse.Pass { + errorMessage := censorResponse.ErrorMessage() + ctx.SetError(errors.New(errorMessage), f) + ctx.Success("question/item") + return + } + + if len(f.Images) > 0 { + image := f.Images[0] + + if err := uploadImage(ctx, uploadImageOptions{ + Type: db.UploadImageQuestionTypeAnswer, + Image: image, + QuestionID: question.ID, + UploaderUserID: ctx.User.ID, + IsDeletingPrevious: true, + }); err != nil { + if errors.Is(err, ErrUploadImageSizeTooLarge) || errors.Is(err, imagecheck.ErrImageTooLarge) { + ctx.SetErrorFlash(err.Error()) + ctx.Success("question/item") + return + } else { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to upload image") + } + } + } + + if err := db.Questions.AnswerByID(ctx.Request().Context(), question.ID, f.Answer); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to answer question") + ctx.SetInternalError(f) + ctx.Success("question/item") + return + } + + // Update censor result. + if err := db.Questions.UpdateCensor(ctx.Request().Context(), question.ID, db.UpdateQuestionCensorOptions{ + AnswerCensorMetadata: censorResponse.ToJSON(), + }); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to update answer censor result") + } + + shared.SafeGo(func() { + if question.ReceiveReplyEmail != "" && question.Answer == "" { // We only send the email when the question has not been answered. + // Send notification to questioner. + if err := mail.SendNewAnswerMail(question.ReceiveReplyEmail, pageUser.Domain, question.ID, question.Content, f.Answer, question.Token); err != nil { + logrus.WithContext(stdctx.Background()).WithError(err).Error("Failed to send receive reply mail to questioner") + } + } + }) + + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "question.flash.answered")) + ctx.Redirect(fmt.Sprintf("/_/%s/%d", pageUser.Domain, question.ID)) +} + +func Delete(ctx context.Context, pageUser *db.User, question *db.Question, canDelete bool) { + if !canDelete { + ctx.Redirect("/_/" + pageUser.Domain) + return + } + + if err := db.Questions.DeleteByID(ctx.Request().Context(), question.ID); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to delete question") + ctx.SetInternalError() + ctx.Success("question/item") + return + } + + ctx.Redirect("/_/" + pageUser.Domain) +} + +func SetPrivate(ctx context.Context, pageUser *db.User, question *db.Question, canDelete bool) { + if !canDelete { + ctx.Redirect("/_/" + pageUser.Domain) + return + } + + if err := db.Questions.SetPrivate(ctx.Request().Context(), question.ID); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to set question private") + ctx.SetInternalError() + ctx.Success("question/item") + return + } + + ctx.Redirect(fmt.Sprintf("/_/%s/%d", pageUser.Domain, question.ID)) +} + +func SetPublic(ctx context.Context, pageUser *db.User, question *db.Question, canDelete bool) { + if !canDelete { + ctx.Redirect("/_/" + pageUser.Domain) + return + } + + if err := db.Questions.SetPublic(ctx.Request().Context(), question.ID); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to set question public") + ctx.SetInternalError() + ctx.Success("question/item") + return + } + + ctx.Redirect(fmt.Sprintf("/_/%s/%d", pageUser.Domain, question.ID)) +} + +// TogglePin 置顶/取消置顶(仅提问箱主人,操作入口在我的提问管理页)。 +func TogglePin(ctx context.Context, pageUser *db.User, question *db.Question, canDelete bool) { + if !canDelete { + ctx.Redirect("/_/" + pageUser.Domain) + return + } + + if err := db.Questions.SetPinned(ctx.Request().Context(), question.ID, !question.IsPinned); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to toggle question pinned") + ctx.SetInternalError() + ctx.Success("question/item") + return + } + + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "question.flash.operated")) + ctx.Redirect("/user/questions") +} + +// SetRead 手动标记提问为已读,跳转回管理列表并定位到该条。 +func SetRead(ctx context.Context, pageUser *db.User, question *db.Question, canDelete bool) { + if !canDelete { + ctx.Redirect("/_/" + pageUser.Domain) + return + } + + if err := db.Questions.SetRead(ctx.Request().Context(), question.ID); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to set question read") + ctx.SetInternalError() + ctx.Success("question/item") + return + } + + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "question.flash.markedRead")) + ctx.Redirect(fmt.Sprintf("/user/questions#question-%d", question.ID)) +} + +// SetUnread 手动标记提问为未读。已回答的提问锁定为已读,不可改回未读。 +// 跳转与 SetRead 一致,回到管理列表并定位到该条,保证"已读/未读"操作路径统一。 +func SetUnread(ctx context.Context, pageUser *db.User, question *db.Question, canDelete bool) { + if !canDelete { + ctx.Redirect("/_/" + pageUser.Domain) + return + } + + // 已回答的问题锁定为已读:上层直接拦截,避免误导用户。 + if question.Answer != "" { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "question.errAnsweredLocked")) + ctx.Redirect(fmt.Sprintf("/user/questions#question-%d", question.ID)) + return + } + + if err := db.Questions.SetUnread(ctx.Request().Context(), question.ID); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to set question unread") + ctx.SetInternalError() + ctx.Success("question/item") + return + } + + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "question.flash.markedUnread")) + ctx.Redirect(fmt.Sprintf("/user/questions#question-%d", question.ID)) +} diff --git a/route/question/share.go b/route/question/share.go new file mode 100644 index 0000000..40fcfd0 --- /dev/null +++ b/route/question/share.go @@ -0,0 +1,970 @@ +package question + +import ( + "bytes" + stdctx "context" + "crypto/md5" + "fmt" + "image" + "image/color" + "image/draw" + "image/jpeg" + "net" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "sync" + "time" + "unicode" + + "github.com/disintegration/imaging" + "github.com/golang/freetype" + "github.com/golang/freetype/truetype" + "github.com/sirupsen/logrus" + qrcode "github.com/skip2/go-qrcode" + + "github.com/tamakyi/TamaBox/internal/conf" + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/db" + "github.com/tamakyi/TamaBox/internal/shared" + "github.com/tamakyi/TamaBox/internal/template" +) + +// 卡片尺寸与留白 +const ( + CardWidth = 960 + CardHeight = 540 + Margin = 15 +) + +// 内容区域边界 +const ( + ContentX = Margin + ContentY = Margin + ContentW = CardWidth - 2*Margin + ContentH = CardHeight - 2*Margin +) + +// 头像参数 +const ( + AvatarSize = 112 + AvatarCX = ContentX + 90 + AvatarCY = ContentY + 90 + AvatarRingW = 6 + AvatarRingR = AvatarSize/2 + AvatarRingW +) + +// 左侧文字区域 +const ( + TextStartX = AvatarCX + AvatarRingR + 30 + TextStartY = ContentY + 75 +) + +// 右侧二维码卡片尺寸 +const ( + QRCardW = 270 + QRCardH = 315 + QRCardX = ContentX + ContentW - QRCardW - 15 + QRCardY = ContentY + (ContentH-QRCardH)/2 +) + +// 二维码尺寸 +const ( + QRCodeSize = 165 + QRCodeX = (QRCardW - QRCodeSize) / 2 +) + +// 社交信息 +const ( + SocialIconW = 24 + SocialIconH = 24 + SocialTextX = TextStartX + SocialIconW + 8 + SocialLineH = 32 +) + +// 底部水印 +const ( + FooterY = ContentY + ContentH - 20 +) + +// 字体大小 +const ( + FontSizeName = 36 + FontSizeIntro = 20 + FontSizeLink = 15 + FontSizeSocial = 17 + FontSizeQRHint = 17 + FontSizeFooter = 14 +) + +// 颜色系统 +var ( + ColorWhite = color.RGBA{255, 255, 255, 255} + ColorBlack = color.RGBA{0, 0, 0, 255} + ColorDarkText = color.RGBA{30, 30, 30, 255} + ColorGrayText = color.RGBA{100, 100, 100, 255} + ColorSocialGray = color.RGBA{80, 80, 80, 255} + ColorHintGray = color.RGBA{90, 90, 90, 255} + ColorFooterGray = color.RGBA{150, 150, 150, 255} + OverlayColor = color.NRGBA{R: 255, G: 255, B: 255, A: 165} +) + +// 全局字体缓存 +var ( + fontOnce sync.Once + fontCache *truetype.Font + fontErr error +) + +func getFont() (*truetype.Font, error) { + fontOnce.Do(func() { + fontBytes, err := os.ReadFile(conf.App.FontPath) + if err != nil { + fontErr = err + return + } + fontCache, fontErr = freetype.ParseFont(fontBytes) + }) + return fontCache, fontErr +} + +// shareDialer 与 shareDialContext:SSRF 防护——解析域名后校验所有解析 IP 均非内网, +// 再交由 shared.DialFirstReachable 对公网候选 IP 并发拨号取最先成功者(happy-eyeballs 风格)。 +// 防 DNS rebinding(IP 字面量直连、无二次解析)的同时,避免固定拨单一 IP 抽中劣化边缘 +// 导致分享卡缺图(分享图源同样在 Cloudflare/R2,链路质量差时多 IP 容错尤为必要)。 +var shareDialer = &net.Dialer{Timeout: 8 * time.Second, KeepAlive: 30 * time.Second} + +// shareDialMaxCandidates 限制并发拨号扇出上限。 +const shareDialMaxCandidates = 6 + +func shareDialContext(ctx stdctx.Context, network, addr string) (net.Conn, error) { + host, port, err := net.SplitHostPort(addr) + if err != nil { + return nil, err + } + ips, err := net.LookupIP(host) + if err != nil { + return nil, err + } + var candidates []net.IP + for _, ip := range ips { + if isBlockedIP(ip) { + return nil, fmt.Errorf("blocked ip address: %s", ip) + } + candidates = append(candidates, ip) + } + if len(candidates) == 0 { + return nil, fmt.Errorf("no public ip address resolved for %s", host) + } + return shared.DialFirstReachable(ctx, shareDialer, network, candidates, port, shareDialMaxCandidates) +} + +// 全局 HTTP 客户端:连接池复用,避免每次请求都重新建立 TCP/TLS 连接。 +// 超时预算说明:分享卡图源(头像/背景/社交图标)同样位于 Cloudflare/R2,服务器到该链路 +// 质量差(实测单次约 6.5s),总预算放宽以容纳多 IP 并发拨号与慢速首字节;R2 图缺失时 +// 分享卡会静默降级(无头像/背景),宁可等待也不轻易放弃。 +var shareHTTPClient = &http.Client{ + Timeout: 20 * time.Second, + Transport: &http.Transport{ + MaxIdleConns: 100, + MaxIdleConnsPerHost: 10, + IdleConnTimeout: 90 * time.Second, + TLSHandshakeTimeout: 8 * time.Second, + ResponseHeaderTimeout: 8 * time.Second, + DialContext: shareDialContext, + }, + // SSRF 防护:重定向逐跳校验,防止 302 跳转到内网地址(如 169.254.169.254 云元数据)绕过初始校验 + CheckRedirect: func(req *http.Request, via []*http.Request) error { + if len(via) >= 5 { + return fmt.Errorf("too many redirects") + } + if isBlockedImageURL(req.URL.String()) { + return fmt.Errorf("blocked redirect to %s", req.URL) + } + return nil + }, +} + +// ttlCache 是一个简单的并发安全带 TTL 缓存。 +// 带 maxItems 条数上限,超限时先清过期、再淘汰最早过期的一条, +// 防止低配服务器(1C1G)上缓存无限膨胀。 +type ttlCache struct { + mu sync.Mutex + items map[string]ttlCacheItem + maxItems int +} + +type ttlCacheItem struct { + value interface{} + expiresAt time.Time +} + +func newTTLCache(maxItems int) *ttlCache { + c := &ttlCache{items: make(map[string]ttlCacheItem), maxItems: maxItems} + // 常驻清理循环:每轮迭代单独 recover,panic 后循环不中断 + go func() { + for range time.Tick(5 * time.Minute) { + func() { + defer func() { + if r := recover(); r != nil { + logrus.WithField("panic", r).Error("ttlCache cleanup panic recovered") + } + }() + c.cleanup() + }() + } + }() + return c +} + +func (c *ttlCache) Get(key string) (interface{}, bool) { + c.mu.Lock() + defer c.mu.Unlock() + item, ok := c.items[key] + if !ok { + return nil, false + } + if time.Now().After(item.expiresAt) { + delete(c.items, key) + return nil, false + } + return item.value, true +} + +func (c *ttlCache) Set(key string, value interface{}, ttl time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + + // 超限时先清过期,仍满则淘汰最早过期的一条 + if len(c.items) >= c.maxItems { + now := time.Now() + for k, item := range c.items { + if now.After(item.expiresAt) { + delete(c.items, k) + } + } + if len(c.items) >= c.maxItems { + var victim string + var earliest time.Time + first := true + for k, item := range c.items { + if first || item.expiresAt.Before(earliest) { + earliest = item.expiresAt + victim = k + first = false + } + } + if victim != "" { + delete(c.items, victim) + } + } + } + + c.items[key] = ttlCacheItem{value: value, expiresAt: time.Now().Add(ttl)} +} + +func (c *ttlCache) cleanup() { + c.mu.Lock() + defer c.mu.Unlock() + now := time.Now() + for k, item := range c.items { + if now.After(item.expiresAt) { + delete(c.items, k) + } + } +} + +// 远程图片缓存(背景图、头像、社交图标),TTL 1 小时。 +// 存的是解码后的 image.Image,最吃内存(1280×720 RGBA ≈ 3.7MB/张), +// 1C1G 环境下限制为 24 条:正常站点同一时刻活跃用户远小于此值。 +// 社交图标 URL 固定不变,基本永远命中;头像/背景变更时最多延迟 1 小时生效。 +var imageCache = newTTLCache(24) + +// 分享图结果缓存,TTL 30 分钟。key 含用户资料指纹,资料变更后自动失效。 +// 存的是 PNG 编码字节(约 0.2~1MB/张),限制 32 条,总内存 ≤ 32MB。 +var shareCardCache = newTTLCache(32) + +func ShareCard(ctx context.Context) { + domain := ctx.Param("domain") + user, err := db.Users.GetByDomain(ctx.Request().Context(), domain) + if err != nil { + ctx.Redirect("/") + return + } + + // 命中缓存直接返回,避免重复下载图片与重新绘制 + cacheKey := shareCardCacheKey(user) + if cached, ok := shareCardCache.Get(cacheKey); ok { + writeShareCardResponse(ctx, cached.([]byte)) + return + } + + canvas := image.NewRGBA(image.Rect(0, 0, CardWidth, CardHeight)) + + // 1. 背景 + draw.Draw(canvas, canvas.Bounds(), &image.Uniform{ColorWhite}, image.Point{}, draw.Src) + innerRect := image.Rect(ContentX, ContentY, ContentX+ContentW, ContentY+ContentH) + + // ---- 并发下载所有远程图片 ---- + var ( + bgImg image.Image + avImg image.Image + ) + icons := []struct { + show bool + url string + icon string + }{ + {user.Acfunlink != "" && user.Acfunlink != "none", user.Acfunlink, "https://r2.337845818.best/tamabox/icon/social/ailicili.png"}, + {user.Bililink != "" && user.Bililink != "none", user.Bililink, "https://r2.337845818.best/tamabox/icon/social/bili.png"}, + {user.Weibolink != "" && user.Weibolink != "none", user.Weibolink, "https://r2.337845818.best/tamabox/icon/social/weibo.png"}, + {user.Bloglink != "" && user.Bloglink != "none", user.Bloglink, "https://r2.337845818.best/tamabox/icon/social/blog.png"}, + {user.Xiaohongshulink != "" && user.Xiaohongshulink != "none", user.Xiaohongshulink, "https://r2.337845818.best/tamabox/icon/social/xiaohongshu.png"}, + } + iconImgs := make([]image.Image, len(icons)) + + var wg sync.WaitGroup + + // 背景图 + bgURL := user.Background + if bgURL == "" { + bgURL = conf.App.ShareBackground + } + wg.Add(1) + shared.SafeGo(func() { + defer wg.Done() + img, err := loadImage(bgURL, ContentW, ContentH) + if err == nil { + bgImg = img + } + }) + + // 头像 + wg.Add(1) + shared.SafeGo(func() { + defer wg.Done() + img, err := loadImage(user.Avatar, AvatarSize, AvatarSize) + if err == nil { + avImg = img + } + }) + + // 社交图标 + for i, item := range icons { + if !item.show { + continue + } + idx, iconURL := i, item.icon + wg.Add(1) + shared.SafeGo(func() { + defer wg.Done() + img, err := loadImage(iconURL, SocialIconW, SocialIconH) + if err == nil { + iconImgs[idx] = img + } + }) + } + + wg.Wait() + // ---- 下载结束 ---- + + // 绘制背景 + if bgImg != nil { + draw.Draw(canvas, innerRect, bgImg, image.Point{}, draw.Src) + } + overlay := image.NewUniform(OverlayColor) + draw.Draw(canvas, innerRect, overlay, image.Point{}, draw.Over) + + // 2. 加载字体(复用缓存) + ft, err := getFont() + if err != nil { + http.Error(ctx.ResponseWriter(), "分享图生成失败:字体文件未配置或无法加载", http.StatusInternalServerError) + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to load font for share card") + return + } + fontCtx := freetype.NewContext() + fontCtx.SetFont(ft) + fontCtx.SetFontSize(24) + fontCtx.SetDPI(72) + + // 3. 头像 + drawCircleFilled(canvas, AvatarCX, AvatarCY, AvatarRingR, ColorWhite) + if avImg != nil { + avImg = imaging.Fill(avImg, AvatarSize, AvatarSize, imaging.Center, imaging.Lanczos) + mask := image.NewAlpha(image.Rect(0, 0, AvatarSize, AvatarSize)) + drawCircle(mask, AvatarSize/2, AvatarSize/2, AvatarSize/2, color.Alpha{255}) + draw.DrawMask(canvas, + image.Rect(AvatarCX-AvatarSize/2, AvatarCY-AvatarSize/2, AvatarCX+AvatarSize/2, AvatarCY+AvatarSize/2), + avImg, image.Point{}, mask, image.Point{}, draw.Over) + } else { + mask := image.NewAlpha(image.Rect(0, 0, AvatarSize, AvatarSize)) + drawCircle(mask, AvatarSize/2, AvatarSize/2, AvatarSize/2, color.Alpha{255}) + draw.DrawMask(canvas, + image.Rect(AvatarCX-AvatarSize/2, AvatarCY-AvatarSize/2, AvatarCX+AvatarSize/2, AvatarCY+AvatarSize/2), + &image.Uniform{color.Gray{180}}, image.Point{}, mask, image.Point{}, draw.Over) + } + + // 4. 左侧文字 + // 文字区裁剪边界:左侧文字不得侵入右侧二维码卡片(QRCardX 左侧留 20px 间距)。 + leftClip := image.Rect(TextStartX, ContentY, QRCardX-20, ContentY+ContentH) + leftMaxW := QRCardX - TextStartX - 60 + y := TextStartY + drawTextWithShadow(canvas, user.Name, TextStartX, y, FontSizeName, ColorDarkText, color.NRGBA{0, 0, 0, 50}, 1, fontCtx) + y += int(FontSizeName) + 15 + // 简介最多 4 行,超出截断加省略号,避免长简介向下覆盖社交区/水印 + y = drawTextMultilineLimited(canvas, user.Intro, TextStartX, y, leftMaxW, FontSizeIntro, ColorGrayText, fontCtx, 46, 4, leftClip) + y += 30 + + // 5. 社交信息 + socialY := y + 22 + for i, item := range icons { + if !item.show || iconImgs[i] == nil { + continue + } + draw.Draw(canvas, + image.Rect(TextStartX, socialY, TextStartX+SocialIconW, socialY+SocialIconH), + iconImgs[i], image.Point{}, draw.Over) + drawTextClipped(canvas, item.url, SocialTextX, socialY+SocialIconH-6, FontSizeSocial, ColorSocialGray, fontCtx, leftClip) + socialY += SocialLineH + } + + // 6. 右侧二维码卡片 + cardRect := image.Rect(QRCardX, QRCardY, QRCardX+QRCardW, QRCardY+QRCardH) + cardCenterX := QRCardX + QRCardW/2 + + drawRoundedRect(canvas, cardRect, color.NRGBA{245, 245, 245, 255}, 18) + drawRoundedRect(canvas, cardRect, ColorWhite, 18) + + boxURL := fmt.Sprintf("%s/_/%s", conf.App.ExternalURL, user.Domain) + qr, err := generateQR(boxURL, user, avImg) + if err != nil { + http.Error(ctx.ResponseWriter(), "二维码生成失败", http.StatusInternalServerError) + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to generate QR code") + return + } + qrResized := imaging.Resize(qr, QRCodeSize, QRCodeSize, imaging.NearestNeighbor) + + const ( + qrToHintGap = 26 + hintLineHeight = 17 + hintToSepGap = 21 + sepHeight = 1 + sepToLinkGap = 21 + linkLineHeight = 15 + ) + totalContentH := QRCodeSize + qrToHintGap + hintLineHeight + hintToSepGap + sepHeight + sepToLinkGap + linkLineHeight + startY := QRCardY + (QRCardH-totalContentH)/2 + + qrDrawX := QRCardX + QRCodeX + qrDrawY := startY + draw.Draw(canvas, image.Rect(qrDrawX, qrDrawY, qrDrawX+QRCodeSize, qrDrawY+QRCodeSize), qrResized, image.Point{}, draw.Over) + + hintY := qrDrawY + QRCodeSize + qrToHintGap + hintLineHeight + drawTextCentered(canvas, "扫码向我匿名提问", cardCenterX, hintY, FontSizeQRHint, ColorHintGray, fontCtx) + + sepY := hintY + hintToSepGap + drawLine(canvas, cardCenterX-90, sepY, cardCenterX+90, sepY, color.NRGBA{200, 200, 200, 180}) + + linkY := sepY + sepToLinkGap + linkLineHeight + linkText := boxURL + linkFontSize := float64(FontSizeLink) + availableW := QRCardW - 45 + actualW := measureTextWidth(linkText, linkFontSize) + if actualW > float64(availableW) { + linkFontSize = linkFontSize * float64(availableW) / actualW + } + drawTextCentered(canvas, linkText, cardCenterX, linkY, linkFontSize, ColorDarkText, fontCtx) + + // 7. 底部水印 + drawTextCentered(canvas, "Powered by 狼的提问箱", CardWidth/2, FooterY, FontSizeFooter, ColorFooterGray, fontCtx) + + // 8. 输出(缓存 + 响应) + buf := new(bytes.Buffer) + if err := jpeg.Encode(buf, canvas, &jpeg.Options{Quality: 88}); err != nil { + http.Error(ctx.ResponseWriter(), "图片生成失败", http.StatusInternalServerError) + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to encode share card PNG") + return + } + + shareCardCache.Set(cacheKey, buf.Bytes(), time.Hour) + writeShareCardResponse(ctx, buf.Bytes()) +} + +// writeShareCardResponse 统一输出分享图响应。 +// 加 Cache-Control 让浏览器与 CDN(如 Cloudflare)缓存,进一步减轻服务器压力。 +func writeShareCardResponse(ctx context.Context, data []byte) { + ctx.ResponseWriter().Header().Set("Content-Type", "image/jpeg") + ctx.ResponseWriter().Header().Set("Content-Disposition", "attachment; filename=\"share.jpg\"") + ctx.ResponseWriter().Header().Set("Content-Length", strconv.Itoa(len(data))) + ctx.ResponseWriter().Header().Set("Cache-Control", "public, max-age=300") + ctx.ResponseWriter().WriteHeader(http.StatusOK) + _, _ = ctx.ResponseWriter().Write(data) +} + +// shareCardCacheKey 基于用户资料生成缓存指纹。 +// 资料(名称/简介/头像/背景/社交链接)任何一项变更都会导致 key 变化,缓存自动失效。 +func shareCardCacheKey(user *db.User) string { + h := md5.New() + fmt.Fprintf(h, "%s|%s|%s|%s|%s|%s|%s|%s|%s|%s", + user.Domain, user.Name, user.Intro, user.Avatar, user.Background, + user.Acfunlink, user.Bililink, user.Weibolink, user.Bloglink, user.Xiaohongshulink) + return fmt.Sprintf("sharecard:%x", h.Sum(nil)) +} + +// ---------- 工具函数 ---------- + +// maxImagePixels 限制远程图片解码后的最大像素总量(4096×4096≈67MB RGBA), +// 防止恶意超大图耗尽服务器内存。 +const maxImagePixels = 4096 * 4096 + +// isBlockedImageURL SSRF 防护:仅允许 http/https,且主机不能解析到私网/环回等内网地址。 +func isBlockedImageURL(rawURL string) bool { + u, err := url.Parse(rawURL) + if err != nil { + return true + } + if u.Scheme != "http" && u.Scheme != "https" { + return true + } + host := u.Hostname() + if host == "" { + return true + } + // 直接是 IP 字面量:私网/环回/链路本地/未指定/组播一律拒绝 + if ip := net.ParseIP(host); ip != nil { + return isBlockedIP(ip) + } + // 域名:解析出任一内网 IP 即拒绝 + ips, err := net.LookupIP(host) + if err != nil { + // 解析失败交给 HTTP 层报错(不阻断),避免 DNS 临时故障误伤正常图片 + return false + } + for _, ip := range ips { + if isBlockedIP(ip) { + return true + } + } + return false +} + +func isBlockedIP(ip net.IP) bool { + return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || + ip.IsLinkLocalMulticast() || ip.IsUnspecified() || ip.IsMulticast() +} + +func loadImage(url string, w, h int) (image.Image, error) { + // SSRF 防护:拒绝非 http/https 与内网地址(127.0.0.1、10.x、192.168.x 等) + if isBlockedImageURL(url) { + return nil, fmt.Errorf("blocked image url: %s", url) + } + + key := fmt.Sprintf("%s|%dx%d", url, w, h) + if cached, ok := imageCache.Get(key); ok { + return cached.(image.Image), nil + } + + resp, err := shareHTTPClient.Get(url) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("bad status: %s", resp.Status) + } + img, _, err := image.Decode(resp.Body) + if err != nil { + return nil, err + } + // 解码后限制像素总量,防止超大图耗尽内存 + b := img.Bounds() + if b.Dx()*b.Dy() > maxImagePixels { + return nil, fmt.Errorf("image too large: %dx%d", b.Dx(), b.Dy()) + } + filled := imaging.Fill(img, w, h, imaging.Center, imaging.Lanczos) + imageCache.Set(key, filled, time.Hour) + return filled, nil +} + +func drawCircle(mask *image.Alpha, cx, cy, r int, c color.Alpha) { + for x := -r; x <= r; x++ { + for y := -r; y <= r; y++ { + if x*x+y*y <= r*r { + mask.SetAlpha(cx+x, cy+y, c) + } + } + } +} + +func drawCircleFilled(dst *image.RGBA, cx, cy, r int, clr color.Color) { + for x := -r; x <= r; x++ { + for y := -r; y <= r; y++ { + if x*x+y*y <= r*r { + dst.Set(cx+x, cy+y, clr) + } + } + } +} + +func drawRoundedRect(dst *image.RGBA, rect image.Rectangle, clr color.Color, radius int) { + draw.Draw(dst, image.Rect(rect.Min.X+radius, rect.Min.Y, rect.Max.X-radius, rect.Max.Y), + &image.Uniform{clr}, image.Point{}, draw.Over) + draw.Draw(dst, image.Rect(rect.Min.X, rect.Min.Y+radius, rect.Max.X, rect.Max.Y-radius), + &image.Uniform{clr}, image.Point{}, draw.Over) + drawCircleFilledRGBA(dst, rect.Min.X+radius, rect.Min.Y+radius, radius, clr) + drawCircleFilledRGBA(dst, rect.Max.X-radius, rect.Min.Y+radius, radius, clr) + drawCircleFilledRGBA(dst, rect.Min.X+radius, rect.Max.Y-radius, radius, clr) + drawCircleFilledRGBA(dst, rect.Max.X-radius, rect.Max.Y-radius, radius, clr) +} + +func drawCircleFilledRGBA(dst *image.RGBA, cx, cy, r int, clr color.Color) { + for x := -r; x <= r; x++ { + for y := -r; y <= r; y++ { + if x*x+y*y <= r*r { + dst.Set(cx+x, cy+y, clr) + } + } + } +} + +func drawLine(dst *image.RGBA, x1, y1, x2, y2 int, clr color.Color) { + if y1 != y2 { + return + } + for x := x1; x <= x2; x++ { + dst.Set(x, y1, clr) + } +} + +func drawText(dst *image.RGBA, text string, x, y int, fontSize float64, col color.Color, ftCtx *freetype.Context) { + ftCtx.SetClip(dst.Bounds()) + ftCtx.SetSrc(image.NewUniform(col)) + ftCtx.SetFontSize(fontSize) + ftCtx.SetDst(dst) + _, _ = ftCtx.DrawString(text, freetype.Pt(x, y)) +} + +// drawTextClipped 同 drawText,但将绘制裁剪到 clip 区域。 +// 用于左侧文字区:即使宽度估算偏差导致某行文字偏宽,也只会被裁掉,不会侵入右侧二维码卡片。 +func drawTextClipped(dst *image.RGBA, text string, x, y int, fontSize float64, col color.Color, ftCtx *freetype.Context, clip image.Rectangle) { + ftCtx.SetClip(clip) + ftCtx.SetSrc(image.NewUniform(col)) + ftCtx.SetFontSize(fontSize) + ftCtx.SetDst(dst) + _, _ = ftCtx.DrawString(text, freetype.Pt(x, y)) +} + +// drawTextWithShadow 先绘制偏移阴影再绘制原色文字,增强在复杂背景上的可读性。 +func drawTextWithShadow(dst *image.RGBA, text string, x, y int, fontSize float64, col, shadow color.Color, offset int, ftCtx *freetype.Context) { + drawText(dst, text, x+offset, y+offset, fontSize, shadow, ftCtx) + drawText(dst, text, x, y, fontSize, col, ftCtx) +} + +func splitText(text string, fontSize float64, maxWidth int) []string { + var lines []string + var currentLine []rune + var currentWidth float64 + for _, r := range text { + charW := charPixelWidth(r, fontSize) + if currentWidth+charW > float64(maxWidth) && len(currentLine) > 0 { + lines = append(lines, string(currentLine)) + currentLine = []rune{r} + currentWidth = charW + } else { + currentLine = append(currentLine, r) + currentWidth += charW + } + } + if len(currentLine) > 0 { + lines = append(lines, string(currentLine)) + } + return lines +} + +func charPixelWidth(r rune, fontSize float64) float64 { + // 宽度系数取「保守上界」:中文字体是方形,实际渲染宽度≈fontSize; + // 若估算偏窄,splitText 换行后的行宽会超出 maxWidth,文字侵入相邻区域。 + // 这里按实际宽度的上界估算,保证 splitText 的行数是安全的(宁可多换行,配合行数截断)。 + if unicode.Is(unicode.Han, r) || unicode.Is(unicode.Punct, r) || unicode.Is(unicode.Symbol, r) { + return fontSize * 1.0 + } + return fontSize * 0.62 +} + +// measureTextWidth 用逐字符宽度估算(与 splitText 的 charPixelWidth 一致), +// 避免每次测量都创建 freetype.Context 并执行 DrawString(显著降低生成耗时)。 +func measureTextWidth(text string, fontSize float64) float64 { + return measureTextEstimate(text, fontSize) +} + +func measureTextEstimate(text string, fontSize float64) float64 { + total := 0.0 + for _, r := range text { + total += charPixelWidth(r, fontSize) + } + return total +} + +func drawTextCentered(dst *image.RGBA, text string, cx, y int, fontSize float64, col color.Color, ftCtx *freetype.Context) { + ftCtx.SetClip(dst.Bounds()) + ftCtx.SetSrc(image.NewUniform(col)) + ftCtx.SetFontSize(fontSize) + actualW := measureTextWidth(text, fontSize) + x := cx - int(actualW/2) + if x < 0 { + x = 0 + } + ftCtx.SetDst(dst) + _, _ = ftCtx.DrawString(text, freetype.Pt(x, y)) +} + +func generateQR(content string, user *db.User, logoImg image.Image) (image.Image, error) { + qr, err := qrcode.New(content, qrcode.High) + if err != nil { + return nil, err + } + + // 强制传统黑白,忽略用户所有颜色设置 + qr.BackgroundColor = color.RGBA{255, 255, 255, 255} + qr.ForegroundColor = color.RGBA{0, 0, 0, 255} + + qrPaletted := qr.Image(256) + rgba := image.NewRGBA(qrPaletted.Bounds()) + draw.Draw(rgba, rgba.Bounds(), qrPaletted, image.Point{}, draw.Src) + + if logoImg != nil { + logo := imaging.Fill(logoImg, 48, 48, imaging.Center, imaging.Lanczos) + bounds := rgba.Bounds() + logoPos := image.Pt( + bounds.Min.X+(bounds.Dx()-logo.Bounds().Dx())/2, + bounds.Min.Y+(bounds.Dy()-logo.Bounds().Dy())/2, + ) + draw.Draw(rgba, logo.Bounds().Add(logoPos), logo, image.Point{}, draw.Over) + } + return rgba, nil +} + +// ---------- 单题分享图 ---------- + +// 单题分享图布局常量(1280x720) +const ( + QContentX = 45 + QContentY = 45 + QContentW = CardWidth - 2*QContentX + QContentH = CardHeight - 2*QContentY + + QAvatarSize = 33 + QAvatarX = QContentX + 2 + QAvatarY = QContentY + 2 + QNameX = QAvatarX + QAvatarSize + 12 + QNameY = QContentY + 28 + + QSepY = QContentY + 50 + + QLabelFont = 20.0 + QQuestionFont = 26.0 + QQuestionLineH = 34 + QQuestionMaxLine = 3 + QAnswerFont = 22.0 + QAnswerLineH = 30 + QAnswerMaxLine = 7 + + // 右侧二维码卡片 + QQRCardW = 210 + QQRCardH = 255 + QQRCardX = QContentX + QContentW - QQRCardW + QQRCardY = QContentY + (QContentH-QQRCardH)/2 + QQRSize = 128 + QQRCodeX = (QQRCardW - QQRSize) / 2 + + // 内容区最大宽度(左侧,避开二维码卡片) + QTextMaxW = QQRCardX - QContentX - 30 + + QWatermarkY = CardHeight - 30 +) + +// 单题分享图结果缓存,TTL 30 分钟,上限 16 条(1C1G 内存友好)。 +var questionShareCache = newTTLCache(16) + +// QuestionShareCard 生成单个问题(问题+回答)的分享卡片图。 +func QuestionShareCard(ctx context.Context) { + domain := ctx.Param("domain") + user, err := db.Users.GetByDomain(ctx.Request().Context(), domain) + if err != nil { + ctx.Redirect("/") + return + } + + questionID := uint(ctx.ParamInt("questionID")) + question, err := db.Questions.GetByID(ctx.Request().Context(), questionID) + if err != nil { + ctx.Redirect("/") + return + } + + // 仅公开且已回答的问题可以生成分享图(Questioner 中间件已挡住私密/未回答,这里再兜底一次) + if question.UserID != user.ID || question.Answer == "" || question.IsPrivate { + ctx.Redirect("/") + return + } + + cacheKey := questionShareCardCacheKey(user, question) + if cached, ok := questionShareCache.Get(cacheKey); ok { + writeShareCardResponse(ctx, cached.([]byte)) + return + } + + canvas := image.NewRGBA(image.Rect(0, 0, CardWidth, CardHeight)) + innerRect := image.Rect(QContentX, QContentY, QContentX+QContentW, QContentY+QContentH) + + // ---- 并发加载背景与头像 ---- + var ( + bgImg image.Image + avImg image.Image + ) + var wg sync.WaitGroup + bgURL := user.Background + if bgURL == "" { + bgURL = conf.App.ShareBackground + } + wg.Add(1) + shared.SafeGo(func() { + defer wg.Done() + img, err := loadImage(bgURL, QContentW, QContentH) + if err == nil { + bgImg = img + } + }) + wg.Add(1) + shared.SafeGo(func() { + defer wg.Done() + img, err := loadImage(user.Avatar, QAvatarSize, QAvatarSize) + if err == nil { + avImg = img + } + }) + wg.Wait() + + // 背景 + 白色遮罩 + draw.Draw(canvas, canvas.Bounds(), &image.Uniform{ColorWhite}, image.Point{}, draw.Src) + if bgImg != nil { + draw.Draw(canvas, innerRect, bgImg, image.Point{}, draw.Src) + } + draw.Draw(canvas, innerRect, image.NewUniform(OverlayColor), image.Point{}, draw.Over) + + // 字体 + ft, err := getFont() + if err != nil { + http.Error(ctx.ResponseWriter(), "分享图生成失败:字体文件未配置或无法加载", http.StatusInternalServerError) + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to load font for question share card") + return + } + fontCtx := freetype.NewContext() + fontCtx.SetFont(ft) + fontCtx.SetFontSize(24) + fontCtx.SetDPI(72) + + // 头部:头像 + 名字 + drawCircleFilled(canvas, QAvatarX+QAvatarSize/2, QAvatarY+QAvatarSize/2, QAvatarSize/2+2, ColorWhite) + if avImg != nil { + avImg = imaging.Fill(avImg, QAvatarSize, QAvatarSize, imaging.Center, imaging.Lanczos) + mask := image.NewAlpha(image.Rect(0, 0, QAvatarSize, QAvatarSize)) + drawCircle(mask, QAvatarSize/2, QAvatarSize/2, QAvatarSize/2, color.Alpha{255}) + draw.DrawMask(canvas, + image.Rect(QAvatarX, QAvatarY, QAvatarX+QAvatarSize, QAvatarY+QAvatarSize), + avImg, image.Point{}, mask, image.Point{}, draw.Over) + } else { + mask := image.NewAlpha(image.Rect(0, 0, QAvatarSize, QAvatarSize)) + drawCircle(mask, QAvatarSize/2, QAvatarSize/2, QAvatarSize/2, color.Alpha{255}) + draw.DrawMask(canvas, + image.Rect(QAvatarX, QAvatarY, QAvatarX+QAvatarSize, QAvatarY+QAvatarSize), + &image.Uniform{color.Gray{180}}, image.Point{}, mask, image.Point{}, draw.Over) + } + drawTextWithShadow(canvas, user.Name+" 的提问箱", QNameX, QNameY, 22, ColorDarkText, color.NRGBA{0, 0, 0, 45}, 1, fontCtx) + + // 分隔线 + drawLine(canvas, QContentX+2, QSepY, QContentX+QContentW-2, QSepY, color.NRGBA{190, 190, 190, 200}) + + // 左侧文字区裁剪边界:问题/回答文字不得侵入右侧二维码卡片(QQRCardX 左侧留 10px 间距)。 + qLeftClip := image.Rect(QContentX, QContentY, QQRCardX-10, QContentY+QContentH) + + // 问题区 + labelY := QSepY + 32 + drawText(canvas, "提问", QContentX+2, labelY, QLabelFont, ColorGrayText, fontCtx) + + textY := labelY + 30 + textY = drawTextMultilineLimited(canvas, sanitizeText(template.MarkdownToPlainText(question.Content)), QContentX+2, textY, QTextMaxW, QQuestionFont, ColorDarkText, fontCtx, QQuestionLineH, QQuestionMaxLine, qLeftClip) + + // 回答区 + labelY = textY + 22 + drawText(canvas, "回答", QContentX+2, labelY, QLabelFont, ColorGrayText, fontCtx) + + textY = labelY + 28 + textY = drawTextMultilineLimited(canvas, sanitizeText(template.MarkdownToPlainText(question.Answer)), QContentX+2, textY, QTextMaxW, QAnswerFont, ColorDarkText, fontCtx, QAnswerLineH, QAnswerMaxLine, qLeftClip) + _ = textY + + // 右侧二维码卡片 + cardRect := image.Rect(QQRCardX, QQRCardY, QQRCardX+QQRCardW, QQRCardY+QQRCardH) + drawRoundedRect(canvas, cardRect, color.NRGBA{245, 245, 245, 255}, 20) + drawRoundedRect(canvas, cardRect, ColorWhite, 20) + + questionURL := fmt.Sprintf("%s/_/%s/%d", conf.App.ExternalURL, user.Domain, question.ID) + qr, err := generateQR(questionURL, user, avImg) + if err != nil { + http.Error(ctx.ResponseWriter(), "二维码生成失败", http.StatusInternalServerError) + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to generate QR code for question share card") + return + } + qrResized := imaging.Resize(qr, QQRSize, QQRSize, imaging.NearestNeighbor) + qrDrawX := QQRCardX + QQRCodeX + // 二维码与提示语整体垂直居中(已删除底部冗余的长链接,卡片更简洁) + qrDrawY := QQRCardY + 40 + draw.Draw(canvas, image.Rect(qrDrawX, qrDrawY, qrDrawX+QQRSize, qrDrawY+QQRSize), qrResized, image.Point{}, draw.Over) + + hintY := qrDrawY + QQRSize + 30 + drawTextCentered(canvas, "扫码查看回答", QQRCardX+QQRCardW/2, hintY, 17, ColorHintGray, fontCtx) + + // 底部水印 + drawTextCentered(canvas, "Powered by 狼的提问箱", CardWidth/2, QWatermarkY, FontSizeFooter, ColorFooterGray, fontCtx) + + // 输出(缓存 + 响应) + buf := new(bytes.Buffer) + if err := jpeg.Encode(buf, canvas, &jpeg.Options{Quality: 88}); err != nil { + http.Error(ctx.ResponseWriter(), "图片生成失败", http.StatusInternalServerError) + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to encode question share card PNG") + return + } + + questionShareCache.Set(cacheKey, buf.Bytes(), time.Hour) + writeShareCardResponse(ctx, buf.Bytes()) +} + +// questionShareCardCacheKey 基于问题内容与用户资料生成缓存指纹,内容/资料变更自动失效。 +func questionShareCardCacheKey(user *db.User, question *db.Question) string { + h := md5.New() + fmt.Fprintf(h, "q|%d|%s|%s|%s|%s|%s", question.ID, question.Content, question.Answer, user.Name, user.Avatar, user.Background) + return fmt.Sprintf("qshare:%x", h.Sum(nil)) +} + +// sanitizeText 将换行符替换为空格,避免绘图时排版错乱。 +func sanitizeText(text string) string { + return strings.ReplaceAll(text, "\n", " ") +} + +// drawTextMultilineLimited 多行绘制,超过 maxLines 行时截断并追加省略号。 +// clip 限定绘制区域,防止估算换行偏差导致文字溢出到相邻元素(如右侧二维码卡片)。 +func drawTextMultilineLimited(dst *image.RGBA, text string, x, y int, maxWidth int, fontSize float64, col color.Color, ftCtx *freetype.Context, lineHeight int, maxLines int, clip image.Rectangle) int { + lines := splitText(text, fontSize, maxWidth) + if len(lines) > maxLines { + lines = lines[:maxLines] + lines[maxLines-1] = lines[maxLines-1] + "…" + } + curY := y + for _, line := range lines { + drawTextClipped(dst, line, x, curY, fontSize, col, ftCtx, clip) + curY += lineHeight + } + return curY +} diff --git a/route/service/proxy.go b/route/service/proxy.go new file mode 100644 index 0000000..6d96987 --- /dev/null +++ b/route/service/proxy.go @@ -0,0 +1,148 @@ +package service + +import ( + "crypto/tls" + "net/http" + "net/http/httputil" + "net/url" + "path" + "strconv" + "strings" + "sync" + "time" + + "github.com/sirupsen/logrus" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/trace" + + "github.com/tamakyi/TamaBox/internal/conf" + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/i18n" +) + +// serviceTransport 复用的共享 Transport,避免每条请求新建导致连接无法复用、 +// 且无超时的资源泄漏。带响应头/空闲连接超时,防止后端挂死时请求无限期阻塞。 +var ( + serviceTransportOnce sync.Once + serviceTransport http.RoundTripper +) + +func getServiceTransport() http.RoundTripper { + serviceTransportOnce.Do(func() { + serviceTransport = &http.Transport{ + // 默认校验证书;仅当配置 tls_insecure_skip_verify=true(内网自签名证书后端)时跳过。 + TLSClientConfig: &tls.Config{InsecureSkipVerify: conf.Service.TLSInsecureSkipVerify}, + ResponseHeaderTimeout: 15 * time.Second, + IdleConnTimeout: 30 * time.Second, + ExpectContinueTimeout: 2 * time.Second, + MaxIdleConns: 100, + MaxIdleConnsPerHost: 10, + } + }) + return serviceTransport +} + +// singleJoiningSlash 将基础路径与附加路径安全拼接,避免双斜杠或丢失分隔符。 +func singleJoiningSlash(a, b string) string { + aslash := strings.HasSuffix(a, "/") + bslash := strings.HasPrefix(b, "/") + switch { + case aslash && bslash: + return a + b[1:] + case !aslash && !bslash: + return a + "/" + b + } + return a + b +} + +func Proxy(ctx context.Context) error { + span := trace.SpanFromContext(ctx.Request().Context()) + + var userID uint + if ctx.IsLogged { + userID = ctx.User.ID + } + + if span.SpanContext().IsValid() { + span.SetAttributes( + attribute.Int("nekobox.service.user-id", int(userID)), + ) + } + + uri := ctx.Param("**") + basePath := strings.Split(uri, "/")[0] + forwardPath := strings.TrimPrefix(uri, basePath) + + var forwardURLStr string + for _, backend := range conf.Service.Backends { + if backend.Prefix == basePath { + forwardURLStr = backend.ForwardURL + break + } + } + if len(forwardURLStr) == 0 { + return ctx.JSONError(http.StatusNotFound, i18n.T(ctx.Lang(), "proxy.errNotFound")) + } + + forwardURL, err := url.Parse(forwardURLStr) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to parse forward URL") + return ctx.JSONError(http.StatusInternalServerError, i18n.T(ctx.Lang(), "proxy.errInternal")) + } + + // 路径穿越防护:先用 path.Clean 归一化,剥离 ../ 等相对段, + // 确保转发路径始终相对于后端基址,不会被 ../ 越出白名单前缀。 + forwardPath = path.Clean(forwardPath) + if !strings.HasPrefix(forwardPath, "/") { + forwardPath = "/" + forwardPath + } + + reverseProxy := httputil.ReverseProxy{ + Director: func(req *http.Request) { + req.URL = forwardURL + req.URL.Path = singleJoiningSlash(forwardURL.Path, forwardPath) + // 透传原始查询串(此前静默丢弃,导致带参请求后端收不到 query)。 + req.URL.RawQuery = ctx.Request().URL.RawQuery + req.Host = forwardURL.Host + + // 安全加固:不透传用户浏览器带来的敏感请求头给后端。 + // 后端通过 X-NekoBox-User-ID 识别用户身份,不应接收用户的会话 + // Cookie / 鉴权头,否则可能被用于横向越权或凭证泄露。 + // 同时清除客户端伪造的 X-Forwarded-*,避免请求头注入。 + req.Header.Del("Cookie") + req.Header.Del("Authorization") + req.Header.Del("Proxy-Authorization") + req.Header.Del("X-Forwarded-For") + req.Header.Del("X-Forwarded-Host") + req.Header.Del("X-Forwarded-Proto") + + traceHeaders := http.Header{} + otel.GetTextMapPropagator().Inject(ctx.Request().Context(), propagation.HeaderCarrier(traceHeaders)) + for key := range traceHeaders { + req.Header.Set(key, traceHeaders.Get(key)) + } + + req.Header.Set("X-NekoBox-From", "nekobox-gateway") + req.Header.Set("X-NekoBox-User-ID", strconv.Itoa(int(userID))) + }, + Transport: getServiceTransport(), + ErrorHandler: func(writer http.ResponseWriter, request *http.Request, err error) { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to handle reverse proxy request") + _ = ctx.JSONError(http.StatusInternalServerError, i18n.T(ctx.Lang(), "proxy.errInternal")) + }, + } + + // 审计日志:记录每一次反代转发(谁、哪个前缀、哪条路径、转发到哪个后端), + // 便于事后排查异常访问与越权探测。 + logrus.WithContext(ctx.Request().Context()).WithFields(logrus.Fields{ + "user_id": userID, + "prefix": basePath, + "path": forwardPath, + "backend": forwardURLStr, + }).Info("Service proxy forwarding request") + + reverseProxy.ServeHTTP(ctx.ResponseWriter(), ctx.Request().Request) + return nil +} diff --git a/route/user/explore.go b/route/user/explore.go new file mode 100644 index 0000000..c7372ed --- /dev/null +++ b/route/user/explore.go @@ -0,0 +1,299 @@ +// Copyright 2026 tamakyi. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package user + +import ( + stdctx "context" + "encoding/json" + "strconv" + "strings" + "time" + + "github.com/flamego/cache" + "github.com/sirupsen/logrus" + + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/db" + "github.com/tamakyi/TamaBox/internal/dbutil" + "github.com/tamakyi/TamaBox/internal/i18n" +) + +// hotVotesCacheKey 探索页热门投票缓存 key(缓存 60s,避免每次 COUNT 聚合)。 +// v2:改用独立 DTO 缓存,修复 db.Vote.LinkToken 因 json:"-" 在 Redis 序列化时丢失、 +// 导致热门投票链接退化为 /vote/ 的问题。 +// v3:额外保留 UserID,用于按箱主的投票功能开关过滤。 +const hotVotesCacheKey = "explore:hot_votes:v3" + +// hotVoteCacheItem 热门投票缓存条目:独立 DTO,显式保留 LinkToken(db.Vote 的 +// LinkToken 带 json:"-" 标签,直接 Marshal Vote 会丢失,缓存命中后链接失效)。 +type hotVoteCacheItem struct { + ID uint `json:"id"` + UserID uint `json:"user_id"` + Title string `json:"title"` + Type string `json:"type"` + LinkToken string `json:"link_token"` + CreatedAt time.Time `json:"created_at"` +} + +var tagColors = []string{ + "uk-label-success", + "uk-label-warning", + "uk-label-danger", + "uk-label-primary", + "uk-label-secondary", +} + +type exploreUser struct { + *db.User + TagList []string + TagColors []string +} + +// getHotVotesCached 读取探索页热门投票,带 Redis 缓存(60s)。 +// 存储格式为 JSON []byte,避免 gob 序列化对模型类型注册的依赖。 +func getHotVotesCached(ctx context.Context, c cache.Cache) ([]*db.Vote, error) { + if v, err := c.Get(stdctx.Background(), hotVotesCacheKey); err == nil { + if data, ok := v.([]byte); ok { + var items []*hotVoteCacheItem + if json.Unmarshal(data, &items) == nil && len(items) > 0 { + votes := make([]*db.Vote, 0, len(items)) + for _, it := range items { + votes = append(votes, &db.Vote{ + Model: dbutil.Model{ID: it.ID, CreatedAt: it.CreatedAt}, + UserID: it.UserID, + Title: it.Title, + Type: it.Type, + LinkToken: it.LinkToken, + }) + } + return votes, nil + } + } + } + + votes, err := db.Votes.GetHot(ctx.Request().Context(), 6) + if err != nil { + return nil, err + } + items := make([]*hotVoteCacheItem, 0, len(votes)) + for _, v := range votes { + items = append(items, &hotVoteCacheItem{ + ID: v.ID, + UserID: v.UserID, + Title: v.Title, + Type: v.Type, + LinkToken: v.LinkToken, + CreatedAt: v.CreatedAt, + }) + } + if data, err := json.Marshal(items); err == nil { + _ = c.Set(stdctx.Background(), hotVotesCacheKey, data, 60*time.Second) + } + return votes, nil +} + +// filterVotesByOwnerFeature 过滤掉箱主已关闭投票功能的投票(开关 / 定时 / 定量收集), +// 避免探索页出现点了打不开的死链。功能配置批量加载,避免逐条查询造成 N+1; +// 加载失败时按原样返回,依赖表抖动不应导致探索页空白。 +func filterVotesByOwnerFeature(ctx context.Context, votes []*db.Vote) []*db.Vote { + if len(votes) == 0 { + return votes + } + + ownerIDs := make([]uint, 0, len(votes)) + seen := make(map[uint]bool, len(votes)) + for _, v := range votes { + if !seen[v.UserID] { + seen[v.UserID] = true + ownerIDs = append(ownerIDs, v.UserID) + } + } + + controls, err := db.FeatureControls.ListByUserIDs(ctx.Request().Context(), ownerIDs, db.FeatureVote) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Warn("Failed to batch load vote feature controls") + return votes + } + + now := time.Now() + out := make([]*db.Vote, 0, len(votes)) + for _, v := range votes { + fc, ok := controls[v.UserID] + if !ok { + fc = db.DefaultFeatureControl(v.UserID, db.FeatureVote) + } + if fc.Evaluate(now).Open { + out = append(out, v) + } + } + return out +} + +// Explore 显示用户列表,支持分页和排序 +func Explore(ctx context.Context, c cache.Cache) { + keyword := ctx.Query("q") + sort := ctx.Query("sort") + // 白名单校验排序方式 + if sort != "latest" && sort != "oldest" { + sort = "latest" + } + + pageStr := ctx.Query("page") + page := 1 + if pageStr != "" { + if p, err := strconv.Atoi(pageStr); err == nil && p > 0 { + page = p + } + } + pageSize := 20 + + var users []*db.User + var total int64 + var err error + + if keyword != "" { + users, total, err = db.Users.GetByTag(ctx.Request().Context(), keyword, page, pageSize, sort) + } else { + users, total, err = db.Users.GetShowInHome(ctx.Request().Context(), page, pageSize, sort) + } + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get users for explore") + ctx.SetInternalError() // 设置内部错误并渲染页面 + ctx.Success("user/explore") + return + } + + // 热门投票板块(Redis 缓存 60s) + hotVotes, err := getHotVotesCached(ctx, c) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Warn("Failed to get hot votes") + hotVotes = []*db.Vote{} + } + ctx.Data["HotVotes"] = filterVotesByOwnerFeature(ctx, hotVotes) + + allVotes, err := db.Votes.ListPublishedPublic(ctx.Request().Context(), 30) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Warn("Failed to get public votes for explore") + allVotes = []*db.Vote{} + } + ctx.Data["AllVotes"] = filterVotesByOwnerFeature(ctx, allVotes) + + // 计算总页数(向上取整) + totalPages := (int(total) + pageSize - 1) / pageSize + + // 页面越界保护 + if page > totalPages && totalPages > 0 { + page = totalPages + } + + // 构建带有标签颜色的用户列表 + exploreUsers := make([]*exploreUser, 0, len(users)) + for _, u := range users { + var tags []string + if u.Tags != "" { + tags = strings.Split(u.Tags, ",") + } + tagColorsList := make([]string, len(tags)) + for i := range tags { + tagColorsList[i] = tagColors[i%len(tagColors)] + } + exploreUsers = append(exploreUsers, &exploreUser{ + User: u, + TagList: tags, + TagColors: tagColorsList, + }) + } + + ctx.Data["Users"] = exploreUsers + ctx.Data["Keyword"] = keyword + ctx.Data["Sort"] = sort + ctx.Data["Page"] = page + ctx.Data["TotalPages"] = totalPages + ctx.Data["PrevPage"] = page - 1 + ctx.Data["NextPage"] = page + 1 + + // 热门标签榜:统计展示在首页用户的高频标签 + hotTags, err := db.Users.GetHotTags(ctx.Request().Context(), 12) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Warn("Failed to get hot tags") + hotTags = []string{} + } + ctx.Data["HotTags"] = hotTags + + // 服务端直接获取随机推荐,避免前端 AJAX 往返导致"加载中"等待 + randomUsers, err := db.Users.GetRandom(ctx.Request().Context(), 6) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Warn("Failed to get random users for sidebar") + } + recommendUsers := make([]*exploreUser, 0, len(randomUsers)) + for _, u := range randomUsers { + var tags []string + if u.Tags != "" { + tags = strings.Split(u.Tags, ",") + } + tagColorsList := make([]string, len(tags)) + for i := range tags { + tagColorsList[i] = tagColors[i%len(tagColors)] + } + recommendUsers = append(recommendUsers, &exploreUser{ + User: u, + TagList: tags, + TagColors: tagColorsList, + }) + } + ctx.Data["RecommendUsers"] = recommendUsers + + lang := i18n.Default + if l, ok := ctx.Data["Lang"].(string); ok && l != "" { + lang = l + } + ctx.SetTitle(i18n.T(lang, "nav.explore") + " - " + i18n.T(lang, "site.title")) + ctx.Success("user/explore") +} + +// RandomRecommend 返回6个随机推荐用户(JSON格式) +// 前端期望的响应格式:{ "code": 0, "data": [...] } +func RandomRecommend(ctx context.Context) { + users, err := db.Users.GetRandomFresh(ctx.Request().Context(), 6) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get random users") + ctx.JSONError(50000, i18n.T(ctx.Lang(), "explore.errRandomUser")) + return + } + + type recommendUser struct { + ID uint `json:"id"` + Name string `json:"name"` + Domain string `json:"domain"` + Avatar string `json:"avatar"` + Intro string `json:"intro"` + TagList []string `json:"tag_list"` + TagColor []string `json:"tag_color"` + } + + result := make([]recommendUser, 0, len(users)) + for _, u := range users { + var tags []string + if u.Tags != "" { + tags = strings.Split(u.Tags, ",") + } + tagColorsList := make([]string, len(tags)) + for i := range tags { + tagColorsList[i] = tagColors[i%len(tagColors)] + } + result = append(result, recommendUser{ + ID: u.ID, + Name: u.Name, + Domain: u.Domain, + Avatar: u.Avatar, + Intro: u.Intro, + TagList: tags, + TagColor: tagColorsList, + }) + } + + // Context.JSON 已统一包装 code/data/message,这里只传业务数据,避免嵌套响应。 + ctx.JSON(result) +} diff --git a/route/user/features.go b/route/user/features.go new file mode 100644 index 0000000..4ec471b --- /dev/null +++ b/route/user/features.go @@ -0,0 +1,351 @@ +// Copyright 2026 tamakyi. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package user + +import ( + "sort" + "strconv" + "strings" + "time" + + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/db" + "github.com/tamakyi/TamaBox/internal/i18n" +) + +// featureTimeLayout 与 的取值格式一致。 +const featureTimeLayout = "2006-01-02T15:04" + +// 账号设置页的面板标识:第一个是用户设置,其余三个与受控功能一一对应, +// 因此保存后可以直接用功能标识回跳到对应的功能面板。 +const ( + ProfileTabAccount = "account" + ProfileTabQuestion = db.FeatureQuestion + ProfileTabChat = db.FeatureChat + ProfileTabVote = db.FeatureVote +) + +// profileURLWithTab 账号设置页 + 指定面板的回跳地址,用于保存后停留在原面板。 +func profileURLWithTab(tab string) string { + return "/user/profile?tab=" + ProfileTab(tab) +} + +// ProfileTab 归一化账号设置页的 tab 参数,非法值回落到用户设置面板。 +func ProfileTab(tab string) string { + switch tab { + case ProfileTabQuestion, ProfileTabChat, ProfileTabVote: + return tab + } + return ProfileTabAccount +} + +// featureView 功能管理面板里单个功能的展示模型(配置 + 实时状态 + 已格式化的时间串)。 +// +// 面板以「点 = 本功能」的方式渲染到部分模板 user/feature-control-form, +// 因此把渲染所需的语言与 CSRF 令牌一并带上,部分模板内无需访问根数据。 +type featureView struct { + Key string + LangCode string + NameText string + StatusText string + CSRFTokenHTML interface{} + Control *db.FeatureControl + State db.FeatureState + OpenAtStr string + CloseAtStr string + QuotaResetAtStr string + ScheduleDays string // 逗号分隔周几(0=周日…6=周六),模板据此勾选开放日 + ScheduleStart string // "HH:MM" + ScheduleEnd string // "HH:MM" + Mode string // 收集模式:always(长期开放)/ window(定时收集)/ recurring(循环定时) +} + +// 收集模式取值(表单 mode 字段)。三种模式在保存时互斥: +// 只保留所选模式的字段,其余清空,避免「一次性窗口 AND 循环定时」叠加 +// 导致一次性关闭时间成为永久硬边界、难以恢复长期开放。 +const ( + FeatureModeAlways = "always" // 长期开放:不限时间 + FeatureModeWindow = "window" // 定时收集:一次性开放 / 关闭窗口 + FeatureModeRecurring = "recurring" // 循环定时:每周循环 +) + +// inferFeatureMode 根据字段组合推断收集模式: +// 有循环定时配置 → recurring;有一性次时间 → window;否则 → always。 +// 用于渲染面板时从已保存配置还原模式,以及旧表单提交未携带 mode 时的兜底。 +func inferFeatureMode(openAt, closeAt *time.Time, scheduleDays, scheduleStart, scheduleEnd string) string { + if scheduleDays != "" || (scheduleStart != "" && scheduleEnd != "") { + return FeatureModeRecurring + } + if openAt != nil || closeAt != nil { + return FeatureModeWindow + } + return FeatureModeAlways +} + +// resolveLang 取当前请求已解析好的语言代码(由 Contexter 写入 Data)。 +func resolveLang(ctx context.Context) string { + if l, ok := ctx.Data["Lang"].(string); ok && l != "" { + return l + } + return i18n.Default +} + +// buildFeatureViews 读取全部受控功能的配置,按功能标识建索引; +// 尚未落库的功能用默认值补齐,保证三个功能面板始终有数据可渲染。 +func buildFeatureViews(ctx context.Context, userID uint) map[string]*featureView { + lang := resolveLang(ctx) + now := time.Now() + csrf := ctx.Data["CSRFTokenHTML"] + + existing := map[string]*db.FeatureControl{} + if list, err := db.FeatureControls.ListByUserID(ctx.Request().Context(), userID); err == nil { + for _, fc := range list { + existing[fc.Feature] = fc + } + } else { + logrus.WithContext(ctx.Request().Context()).WithError(err).Warn("Failed to list feature controls") + } + + views := make(map[string]*featureView, len(db.FeatureKeys)) + for _, key := range db.FeatureKeys { + fc, ok := existing[key] + if !ok { + fc = db.DefaultFeatureControl(userID, key) + } + state := fc.Evaluate(now) + mode := inferFeatureMode(fc.OpenAt, fc.CloseAt, fc.ScheduleDays, fc.ScheduleStart, fc.ScheduleEnd) + v := &featureView{ + Key: key, + LangCode: lang, + NameText: i18n.FeatureName(lang, key), + StatusText: i18n.FeatureStatusText(lang, state.Reason), + CSRFTokenHTML: csrf, + Control: fc, + State: state, + Mode: mode, + } + if fc.OpenAt != nil { + v.OpenAtStr = fc.OpenAt.Format(featureTimeLayout) + } + if fc.CloseAt != nil { + v.CloseAtStr = fc.CloseAt.Format(featureTimeLayout) + } + if fc.QuotaResetAt != nil { + v.QuotaResetAtStr = fc.QuotaResetAt.Format("2006-01-02 15:04") + } + v.ScheduleDays = fc.ScheduleDays + v.ScheduleStart = fc.ScheduleStart + v.ScheduleEnd = fc.ScheduleEnd + views[key] = v + } + return views +} + +// InjectFeatureViews 把三个功能的配置注入账号设置页(用户设置面板不需要,但一并注入开销可忽略)。 +// 供 Profile 与保存失败后重渲染的场景复用。 +func InjectFeatureViews(ctx context.Context) { + views := buildFeatureViews(ctx, ctx.User.ID) + ctx.Data["FeatureQuestion"] = views[db.FeatureQuestion] + ctx.Data["FeatureChat"] = views[db.FeatureChat] + ctx.Data["FeatureVote"] = views[db.FeatureVote] + ctx.Data["QuotaLimitMax"] = db.QuotaLimitMax +} + +// FeaturesUpdate 保存单个功能的开关 / 定时 / 定量设置。 +// 每个功能面板各自一张表单,只提交自己的字段,保存后回跳到该面板。 +func FeaturesUpdate(ctx context.Context) { + lang := resolveLang(ctx) + key := strings.TrimSpace(ctx.Request().FormValue("feature")) + if !db.IsValidFeature(key) { + ctx.SetErrorFlash(i18n.T(lang, "feature.errInvalid")) + ctx.Redirect(profileURLWithTab(ProfileTabAccount)) + return + } + + name := i18n.FeatureName(lang, key) + tab := ProfileTab(key) + + openAt, err := parseTimeInput(ctx, strings.TrimSpace(ctx.Request().FormValue("open_at"))) + if err != nil { + ctx.SetErrorFlash(i18n.T(lang, "feature.errTime", name)) + ctx.Redirect(profileURLWithTab(tab)) + return + } + closeAt, err := parseTimeInput(ctx, strings.TrimSpace(ctx.Request().FormValue("close_at"))) + if err != nil { + ctx.SetErrorFlash(i18n.T(lang, "feature.errTime", name)) + ctx.Redirect(profileURLWithTab(tab)) + return + } + + quota, err := parseQuotaLimit(strings.TrimSpace(ctx.Request().FormValue("quota_limit"))) + if err != nil { + ctx.SetErrorFlash(i18n.T(lang, "feature.errQuota", name)) + ctx.Redirect(profileURLWithTab(tab)) + return + } + + // 循环定时:开放日(逗号分隔周几)+ 每日时间段(HH:MM,需成对填写) + scheduleDays := normalizeScheduleDays(ctx.Request().FormValue("schedule_days")) + scheduleStart := strings.TrimSpace(ctx.Request().FormValue("schedule_start")) + scheduleEnd := strings.TrimSpace(ctx.Request().FormValue("schedule_end")) + + // 收集模式三选一;未携带 mode(旧表单重放等)时按提交字段推断,保持兼容。 + mode := strings.TrimSpace(ctx.Request().FormValue("mode")) + switch mode { + case FeatureModeAlways, FeatureModeWindow, FeatureModeRecurring: + default: + mode = inferFeatureMode(openAt, closeAt, scheduleDays, scheduleStart, scheduleEnd) + } + + // 模式互斥:清理未选模式的字段,一次性窗口与循环定时不再叠加 + // (旧版叠加语义下,一次性关闭时间过后功能永久结束,难以恢复长期开放)。 + switch mode { + case FeatureModeAlways: + openAt, closeAt = nil, nil + scheduleDays, scheduleStart, scheduleEnd = "", "", "" + case FeatureModeWindow: + scheduleDays, scheduleStart, scheduleEnd = "", "", "" + case FeatureModeRecurring: + openAt, closeAt = nil, nil + } + + if mode == FeatureModeWindow && openAt != nil && closeAt != nil && !closeAt.After(*openAt) { + ctx.SetErrorFlash(i18n.T(lang, "feature.errTimeRange", name)) + ctx.Redirect(profileURLWithTab(tab)) + return + } + if mode == FeatureModeRecurring { + if (scheduleStart == "") != (scheduleEnd == "") { + ctx.SetErrorFlash(i18n.T(lang, "feature.errScheduleHalf", name)) + ctx.Redirect(profileURLWithTab(tab)) + return + } + if scheduleStart != "" { + startM, err := parseHHMM(scheduleStart) + if err != nil { + ctx.SetErrorFlash(i18n.T(lang, "feature.errScheduleTime", name)) + ctx.Redirect(profileURLWithTab(tab)) + return + } + endM, err := parseHHMM(scheduleEnd) + if err != nil { + ctx.SetErrorFlash(i18n.T(lang, "feature.errScheduleTime", name)) + ctx.Redirect(profileURLWithTab(tab)) + return + } + if endM <= startM { + ctx.SetErrorFlash(i18n.T(lang, "feature.errScheduleRange", name)) + ctx.Redirect(profileURLWithTab(tab)) + return + } + } + } + + // 私聊不提供收集上限:会话是双向对话(已有单会话消息数上限), + // 限制「新建会话数」对箱主意义不大。UI 已隐藏该字段, + // 这里强制清零,防止历史残留的上限让私聊「莫名关闭」。 + if key == db.FeatureChat { + quota = 0 + } + + if err := db.FeatureControls.Save(ctx.Request().Context(), ctx.User.ID, key, db.UpdateFeatureControlOptions{ + Enabled: ctx.Request().FormValue("enabled") == "on", + OpenAt: openAt, + CloseAt: closeAt, + ScheduleDays: scheduleDays, + ScheduleStart: scheduleStart, + ScheduleEnd: scheduleEnd, + QuotaLimit: quota, + }); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err). + Errorf("Failed to save feature control %q", key) + ctx.SetInternalErrorFlash() + ctx.Redirect(profileURLWithTab(tab)) + return + } + + // 私聊开关与 users.allow_chat 双向同步:后者仍被邮件通知等既有逻辑读取, + // 保持两处一致,避免功能面板与旧字段表现不一致。 + if key == db.FeatureChat { + if err := db.Users.UpdateAllowChat(ctx.Request().Context(), ctx.User.ID, ctx.Request().FormValue("enabled") == "on"); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Warn("Failed to sync users.allow_chat") + } + } + + ctx.SetSuccessFlash(i18n.T(lang, "feature.saved")) + ctx.Redirect(profileURLWithTab(tab)) +} + +// FeatureResetQuota 清零某功能的收集计数,开启下一轮定量收集。 +func FeatureResetQuota(ctx context.Context) { + lang := resolveLang(ctx) + key := strings.TrimSpace(ctx.Request().FormValue("feature")) + if !db.IsValidFeature(key) { + ctx.SetErrorFlash(i18n.T(lang, "feature.errInvalid")) + ctx.Redirect(profileURLWithTab(ProfileTabAccount)) + return + } + + if err := db.FeatureControls.ResetQuota(ctx.Request().Context(), ctx.User.ID, key); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err). + Errorf("Failed to reset feature quota %q", key) + ctx.SetInternalErrorFlash() + ctx.Redirect(profileURLWithTab(key)) + return + } + + ctx.SetSuccessFlash(i18n.T(lang, "feature.quotaReset", i18n.FeatureName(lang, key))) + ctx.Redirect(profileURLWithTab(key)) +} + +// parseQuotaLimit 解析收集上限:空串与 0 均表示不限制。 +func parseQuotaLimit(s string) (int64, error) { + if s == "" { + return 0, nil + } + n, err := strconv.ParseInt(s, 10, 64) + if err != nil || n < 0 { + return 0, errors.New("invalid quota limit") + } + if n > db.QuotaLimitMax { + return 0, errors.New("quota limit too large") + } + return n, nil +} + +// normalizeScheduleDays 归一化循环定时的开放日:只保留 0-6 的合法周几并去重、排序。 +// 复选框多选值形如 ["0","2","4"](time.Weekday:0=周日…6=周六)。 +func normalizeScheduleDays(raw string) string { + seen := make(map[int]bool) + var days []string + for _, part := range strings.Split(raw, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + n, err := strconv.Atoi(part) + if err != nil || n < 0 || n > 6 || seen[n] { + continue + } + seen[n] = true + days = append(days, strconv.Itoa(n)) + } + // 按周几排序,保证存储稳定、展示一致 + sort.Strings(days) + return strings.Join(days, ",") +} + +// parseHHMM 解析 "HH:MM" 为当天第几分钟(与 db 包内同名函数逻辑一致,路由层用于校验表单)。 +func parseHHMM(s string) (int, error) { + t, err := time.Parse("15:04", strings.TrimSpace(s)) + if err != nil { + return 0, errors.New("invalid HH:MM") + } + return t.Hour()*60 + t.Minute(), nil +} diff --git a/route/user/harassment.go b/route/user/harassment.go new file mode 100644 index 0000000..08c6e13 --- /dev/null +++ b/route/user/harassment.go @@ -0,0 +1,139 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package user + +import ( + "strings" + + "github.com/sirupsen/logrus" + "github.com/tamakyi/TamaBox/internal/conf" + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/db" + "github.com/tamakyi/TamaBox/internal/form" + "github.com/tamakyi/TamaBox/internal/i18n" +) + +// returnTab 表单提交后回跳的账号设置面板:屏蔽词设置已分散展示在 +// 提问/私聊/投票三个面板,action 携带 ?tab= 来源参数,保存后停留原面板。 +func returnTab(ctx context.Context) string { + return profileURLWithTab(ProfileTab(ctx.Query("tab"))) +} + +// abortOnFormError 处理表单校验/反序列化失败:返回 true 表示已中止本次写入。 +// +// 背景:form.Bind 在反序列化失败(如请求体超限、body 畸形)时只置位错误并继续执行 +// handler 链(flamego 语义:响应未写即自动续链),零值结构体会照常进入业务动作—— +// 对不检查 ctx.HasError() 的 handler,会把用户既有配置静默清空/关闭,例如: +// - UpdateHarassment:RegisterOnly="" → 防骚扰被改回 none(关闭"仅允许注册用户"); +// - UpdateBlockWords:BlockWords="" → 全部屏蔽词被清空; +// - UpdateTags:Tags="" → 标签被清空、ShowInHome 被关; +// - UpdatePagePassword / UpdateAskPassword:Password="" → 访问/提问密码被解除。 +// +// 错误信息已由 Bind 经 context.SetError 写入 Data["Error"](govalid 校验错误已按界面 +// 语言翻译,解析错误为原文),此处转入 flash,保证 PRG 重定向后仍能向用户展示。 +func abortOnFormError(ctx context.Context, redirectTo string) bool { + if !ctx.HasError() { + return false + } + if msg, ok := ctx.Data["Error"].(string); ok && msg != "" { + ctx.SetErrorFlash(msg) + } + ctx.Redirect(redirectTo) + return true +} + +// UpdateHarassment 仅更新「防骚扰类型」(none / register_only,即"仅允许注册用户向我提问")。 +// 只写 harassment_setting 列;全局屏蔽词已拆分为独立入口 UpdateBlockWords, +// 二者互不覆盖(此前同一个表单一次写两列,面板拆分后单侧保存会误清空另一侧)。 +func UpdateHarassment(ctx context.Context, f form.UpdateHarassment) { + // 反序列化失败(如请求体超限)时零值 RegisterOnly="" 会把防骚扰静默改回 none + // (若此前为 register_only)——先中止,不触碰现有设置。 + if abortOnFormError(ctx, returnTab(ctx)) { + return + } + + harassmentSettingType := db.HarassmentSettingNone + if f.RegisterOnly != "" { + harassmentSettingType = db.HarassmentSettingTypeRegisterOnly + } + + if err := db.Users.UpdateHarassmentType(ctx.Request().Context(), ctx.User.ID, harassmentSettingType); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to update harassment setting") + ctx.SetInternalErrorFlash() + ctx.Redirect(returnTab(ctx)) + return + } + + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "admin.flash.harassmentUpdated")) + ctx.Redirect(returnTab(ctx)) +} + +// UpdateBlockWords 更新全局屏蔽词表:提问、私聊(对方发给我的消息)与投票 +// 提交的开放文本共用同一份词表(users.block_words)。 +func UpdateBlockWords(ctx context.Context, f form.UpdateBlockWords) { + // 反序列化失败(如请求体超限)时零值 BlockWords="" 会经 sanitizeBlockWords 得到 + // 空词表,静默清空用户全部屏蔽词——先中止,不触碰现有词表。 + if abortOnFormError(ctx, returnTab(ctx)) { + return + } + + words, errKey, errWord := sanitizeBlockWords(f.BlockWords) + if errKey != "" { + if errKey == "admin.flash.blockWordTooLong" { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), errKey, errWord)) + } else { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), errKey)) + } + ctx.Redirect(returnTab(ctx)) + return + } + + if err := db.Users.UpdateBlockWords(ctx.Request().Context(), ctx.User.ID, strings.Join(words, ",")); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to update block words") + ctx.SetInternalErrorFlash() + ctx.Redirect(returnTab(ctx)) + return + } + + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "admin.flash.blockWordsUpdated")) + ctx.Redirect(returnTab(ctx)) +} + +// sanitizeBlockWords 把输入的屏蔽词串规整为去重后的词表: +// - 全角逗号转半角;逐词 TrimSpace;跳过空词与重复词。 +// - 单词长度按字符(rune)计数,超限(conf.Limits.MaxBlockWordLen)返回超长提示; +// - 词总数超限(conf.Limits.MaxBlockWords)返回数量提示。 +// +// 成功时 errKey 为空,errWord 为触发超长的具体词(供 flash 展示)。 +func sanitizeBlockWords(raw string) (words []string, errKey string, errWord string) { + blockWords := strings.ReplaceAll(raw, ",", ",") + blockWords = strings.TrimSpace(blockWords) + + words = make([]string, 0) + wordSet := make(map[string]struct{}) + for _, word := range strings.Split(blockWords, ",") { + word := strings.TrimSpace(word) + if word == "" { + continue + } + if _, ok := wordSet[word]; ok { + continue + } + wordSet[word] = struct{}{} + + // 按字符(rune)计数:早期用 len(word) 按字节计数,中文一词 3 字节, + // 导致中文屏蔽词实际只能输 3 个字,与界面文案「最大长度为 10」不符。 + // 上限取自 conf.Limits.MaxBlockWordLen([limits] 配置段)。 + if len([]rune(word)) > conf.Limits.MaxBlockWordLen { + return nil, "admin.flash.blockWordTooLong", word + } + words = append(words, word) + } + + if len(words) > conf.Limits.MaxBlockWords { + return nil, "admin.flash.blockWordsTooMany", "" + } + return words, "", "" +} diff --git a/route/user/password.go b/route/user/password.go new file mode 100644 index 0000000..9fb0aab --- /dev/null +++ b/route/user/password.go @@ -0,0 +1,56 @@ +// Copyright 2026 tamakyi. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package user + +import ( + "github.com/sirupsen/logrus" + + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/db" + "github.com/tamakyi/TamaBox/internal/form" + "github.com/tamakyi/TamaBox/internal/i18n" +) + +// UpdatePagePassword 更新页面访问密码 +func UpdatePagePassword(ctx context.Context, f form.UpdatePagePassword) { + // 反序列化失败(如请求体超限)时零值 Password="" 会把密码静默解除——先中止, + // 不触碰现有密码。govalid 校验失败(如密码超长)同样在此拦截,避免绕过前端限制。 + if abortOnFormError(ctx, "/user/profile") { + return + } + + if err := db.Users.UpdatePagePassword(ctx.Request().Context(), ctx.User.ID, f.Password); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to update page password") + ctx.SetInternalErrorFlash() + } else { + if f.Password == "" { + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "admin.flash.pagePwdOff")) + } else { + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "admin.flash.pagePwdUpdated")) + } + } + ctx.Redirect("/user/profile") +} + +// UpdateAskPassword 更新提问密码 +func UpdateAskPassword(ctx context.Context, f form.UpdateAskPassword) { + // 同上:反序列化失败或校验失败时零值 Password="" 会把提问密码静默解除。 + if abortOnFormError(ctx, profileURLWithTab(ProfileTabQuestion)) { + return + } + + if err := db.Users.UpdateAskPassword(ctx.Request().Context(), ctx.User.ID, f.Password); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to update ask password") + ctx.SetInternalErrorFlash() + } else { + if f.Password == "" { + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "admin.flash.askPwdOff")) + } else { + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "admin.flash.askPwdUpdated")) + } + } + // 提问密码属于提问功能的专属设置,保存后回到「提问」面板 + ctx.Redirect(profileURLWithTab(ProfileTabQuestion)) +} diff --git a/route/user/profile.go b/route/user/profile.go new file mode 100644 index 0000000..1a53e43 --- /dev/null +++ b/route/user/profile.go @@ -0,0 +1,599 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package user + +import ( + "encoding/json" + "fmt" + "net/url" + "strconv" + "time" + + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + "github.com/xuri/excelize/v2" + + "github.com/tamakyi/TamaBox/internal/conf" + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/db" + "github.com/tamakyi/TamaBox/internal/form" + "github.com/tamakyi/TamaBox/internal/i18n" + "github.com/tamakyi/TamaBox/internal/imagecheck" + "github.com/tamakyi/TamaBox/internal/storage" +) + +// Profile 账号设置页。按面板分区: +// - account:用户设置(个人信息 / 个性化 / 社交 / 密码 / 导出 / 停用账号); +// - question / chat / vote:三个功能的管理(开关 + 定时 + 定量 + 各自的专属设置)。 +// +// 面板由 ?tab= 指定,非法值回落到用户设置,保证分享链接不会渲染出空页面。 +func Profile(ctx context.Context) { + ctx.Data["HasPagePassword"] = ctx.User.PagePassword != "" + ctx.Data["HasAskPassword"] = ctx.User.AskPassword != "" + ctx.Data["ActiveProfileTab"] = ProfileTab(ctx.Query("tab")) + ctx.Data["TagLimits"] = tagLimits() + ctx.Data["ChatLimits"] = chatLimits() + InjectFeatureViews(ctx) + ctx.Success("user/profile") +} + +// tagLimits 标签与屏蔽词的数量 / 长度上限,供前端标签块输入组件做实时提示。 +// 数值来自 conf.Limits([limits] 配置段),后端校验引用同一份配置。 +func tagLimits() map[string]int { + return map[string]int{ + "MaxTags": conf.Limits.MaxTags, + "MaxTagLen": conf.Limits.MaxTagLen, + "MaxBlockWords": conf.Limits.MaxBlockWords, + "MaxBlockWordLen": conf.Limits.MaxBlockWordLen, + } +} + +// chatLimits 私聊面板的数值上下界,供设置表单的 number 输入框做 min/max 提示。 +// 同样来自 conf.Limits:会话条数硬顶与每日条数可设上限。 +func chatLimits() map[string]int { + return map[string]int{ + "MaxChatMessages": conf.Limits.ChatMaxMessages, + "DailyMessageLimitMax": conf.Limits.DailyMessageLimitMax, + } +} + +func ProfileAPI(ctx context.Context) error { + return ctx.JSON(ctx.User) +} + +func UpdateProfile(ctx context.Context, f form.UpdateProfile) { + if ctx.HasError() { + ctx.Success("user/profile") + return + } + + // 获取当前用户信息,用于保留未修改的字段 + currentUser, err := db.Users.GetByID(ctx.Request().Context(), ctx.User.ID) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get current user") + ctx.SetInternalErrorFlash() + ctx.Redirect("/user/profile") + return + } + + // 处理头像上传(强制 1:1,见 storage.UploadAvatarToS3) + avatarURL := currentUser.Avatar // 默认使用原值 + avatarFile, avatarFileHeader, err := ctx.Request().FormFile("avatar") + if err == nil { + defer avatarFile.Close() + if avatarFileHeader.Size > storage.MaxAvatarSize { + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "profile.err.avatarTooLarge"))) + ctx.Success("user/profile") + return + } + uploadedURL, err := storage.UploadAvatarToS3(avatarFile, avatarFileHeader) + if err != nil { + if errors.Is(err, imagecheck.ErrImageTooLarge) { + ctx.SetErrorFlash(err.Error()) + ctx.Success("user/profile") + return + } + if errors.Is(err, imagecheck.ErrBadAspectRatio) { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "profile.err.avatarRatio")) + ctx.Success("user/profile") + return + } + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to upload avatar") + } else { + avatarURL = uploadedURL + } + } + + // 从表单读取 UseCustomQRColor 并转换为布尔值 + useCustomQRColor := f.UseCustomQRColor == "on" + + // 处理背景上传(强制 16:9,见 storage.UploadBackgroundToS3) + backgroundURL := currentUser.Background // 默认使用原值 + backgroundFile, backgroundFileHeader, err := ctx.Request().FormFile("background") + if err == nil { + defer backgroundFile.Close() + if backgroundFileHeader.Size > storage.MaxBackgroundSize { + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "profile.err.backgroundTooLarge"))) + ctx.Success("user/profile") + return + } + uploadedURL, err := storage.UploadBackgroundToS3(backgroundFile, backgroundFileHeader) + if err != nil { + if errors.Is(err, imagecheck.ErrImageTooLarge) { + ctx.SetErrorFlash(err.Error()) + ctx.Success("user/profile") + return + } + if errors.Is(err, imagecheck.ErrBadAspectRatio) { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "profile.err.backgroundRatio")) + ctx.Success("user/profile") + return + } + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to upload background") + } else { + backgroundURL = uploadedURL + } + } + + // 处理二维码背景图上传 + backgroundImageURL := currentUser.BackgroundImage // 默认使用原值 + backgroundimageFile, backgroundimageFileHeader, err := ctx.Request().FormFile("backgroundimage") + if err == nil { + defer backgroundimageFile.Close() + if backgroundimageFileHeader.Size > storage.MaxBackgroundSize { + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "profile.err.backgroundTooLarge"))) + ctx.Success("user/profile") + return + } + uploadedURL, err := storage.UploadPictureToS3(backgroundimageFile, backgroundimageFileHeader) + if err != nil { + if errors.Is(err, imagecheck.ErrImageTooLarge) { + ctx.SetErrorFlash(err.Error()) + ctx.Success("user/profile") + return + } + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to upload QRbackgroundImage") + } else { + backgroundImageURL = uploadedURL + } + } + + // 密码修改逻辑(新密码非空时强制至少 8 位)。 + // 是否真的改了密码会决定保存成功后的去向:改密则清会话登出(见文件尾部保存分支)。 + passwordChanged := false + if f.NewPassword != "" { + if len(f.NewPassword) < 8 { + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "profile.err.newPasswordTooShort"))) + ctx.Success("user/profile") + return + } + if err := db.Users.ChangePassword(ctx.Request().Context(), ctx.User.ID, f.OldPassword, f.NewPassword); err != nil { + if errors.Is(err, db.ErrBadCredential) { + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "profile.err.badOldPassword"))) + } else { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to update password") + ctx.SetInternalError() + } + ctx.Success("user/profile") + return + } + passwordChanged = true + } + + // 通知类型 + var notify db.NotifyType + if f.NotifyEmail != "" { + notify = db.NotifyTypeEmail + } else { + notify = db.NotifyTypeNone + } + + // 构建更新选项 + if err := db.Users.Update(ctx.Request().Context(), ctx.User.ID, db.UpdateUserOptions{ + Name: f.Name, + Avatar: avatarURL, + Background: backgroundURL, + Intro: f.Intro, + Qrcodebackcolor: f.Qrcodebackcolor, + Qrcodecolor: f.Qrcodecolor, + Dotscale: f.Dotscale, + BackgroundImage: backgroundImageURL, + Backgroundimagealpha: f.Backgroundimagealpha, + Usernamecolor: f.Usernamecolor, + Introcolor: f.Introcolor, + Qrcodepdpcolor: f.Qrcodepdpcolor, + Acfunlink: f.Acfunlink, + Bililink: f.Bililink, + Weibolink: f.Weibolink, + Xiaohongshulink: f.Xiaohongshulink, + Bloglink: f.Bloglink, + UseCustomQRColor: useCustomQRColor, + Notify: notify, + Language: i18n.Resolve(f.Language), + }); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to update user profile") + if passwordChanged { + // 密码已落库且版本号已 +1:当前会话在下次请求即失效, + // 主动清会话并给出明确提示后回登录页,避免用户被「请先登录」含糊文案打断。 + ctx.Session.Flush() + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "profile.flash.passwordChanged")) + ctx.Redirect("/login") + return + } + ctx.SetInternalErrorFlash() + } else if passwordChanged { + // 密码修改成功且其余资料也保存成功:强制登出重登。 + // 顺序与 DeactivateProfileAction 保持一致:先 Flush 会话再写入 flash,随后跳登录页。 + ctx.Session.Flush() + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "profile.flash.passwordChanged")) + ctx.Redirect("/login") + return + } else { + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "admin.flash.profileUpdated")) + } + ctx.Redirect("/user/profile") +} + +// 更新私聊设置(手动读取表单,不使用 form.Bind) +// +// 注意:私聊的「开启 / 关闭」由账号设置页「私聊」面板统一控制(feature_controls,含定时与定量), +// 此处不再从表单读取开关值——否则移除复选框后每次保存都会把开关重置为关闭。 +// users.allow_chat 仍按功能管理的当前值回写,保持两处一致。 +func UpdateChatSettings(ctx context.Context) { + maxMessagesStr := ctx.Request().FormValue("chat_max_messages") + dailyLimitStr := ctx.Request().FormValue("chat_daily_limit") + + maxMessages, err := strconv.Atoi(maxMessagesStr) + if err != nil || maxMessages < 1 { + maxMessages = 1 + } + // 会话条数上限:用户只能在自己的设置里取 1..系统硬顶(conf.Limits.ChatMaxMessages) + if maxMessages > conf.Limits.ChatMaxMessages { + maxMessages = conf.Limits.ChatMaxMessages + } + + dailyLimit, _ := strconv.Atoi(dailyLimitStr) + if dailyLimit < 0 { + dailyLimit = 0 + } + // 每日条数:0 = 不限制;否则取 1..conf.Limits.DailyMessageLimitMax + if dailyLimit > conf.Limits.DailyMessageLimitMax { + dailyLimit = conf.Limits.DailyMessageLimitMax + } + + allowChat := db.FeatureOpen(ctx.Request().Context(), ctx.User.ID, db.FeatureChat) + if err := db.Users.UpdateChatSettings(ctx.Request().Context(), ctx.User.ID, allowChat, maxMessages); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to update chat settings") + ctx.SetInternalErrorFlash() + } else { + // 更新每日限制 + if err := db.Users.UpdateDailyMessageLimit(ctx.Request().Context(), ctx.User.ID, dailyLimit); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to update daily limit") + } + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "admin.flash.chatUpdated")) + } + ctx.Redirect(profileURLWithTab(ProfileTabChat)) +} + +func ExportProfile(ctx context.Context) { + user, err := db.Users.GetByID(ctx.Request().Context(), ctx.User.ID) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get user") + + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "admin.export.errUser"))) + ctx.Success("user/profile") + return + } + + questions, err := db.Questions.GetByUserID(ctx.Request().Context(), user.ID, db.GetQuestionsByUserIDOptions{ + FilterAnswered: false, + ShowPrivate: true, + }) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get questions") + + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "admin.export.errQuestion"))) + ctx.Success("user/profile") + return + } + + f, err := createExportExcelFile(user, questions) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to create excel file") + + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "admin.export.errCreateExcel"))) + ctx.Success("user/profile") + return + } + + fileName := fmt.Sprintf("狼的提问箱账号信息导出-%s-%s.xlsx", user.Domain, time.Now().Format("20060102150405")) + ctx.ResponseWriter().Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") + ctx.ResponseWriter().Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+url.QueryEscape(fileName)) + + if err := f.Write(ctx.ResponseWriter()); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to write excel file") + + ctx.SetError(errors.New(i18n.T(ctx.Lang(), "admin.export.errWriteExcel"))) + ctx.Success("user/profile") + return + } +} + +func createXLSXStreamWriter(xlsx *excelize.File, sheet string, headers []string) (*excelize.StreamWriter, error) { + xlsx.NewSheet(sheet) + sw, err := xlsx.NewStreamWriter(sheet) + if err != nil { + return nil, errors.Wrap(err, "new stream writer") + } + + cols := make([]interface{}, 0, len(headers)) + for _, c := range headers { + cols = append(cols, c) + } + err = sw.SetRow("A1", cols) + if err != nil { + return nil, errors.Wrap(err, "set header row") + } + return sw, nil +} + +// sanitizeCell 防止表格软件公式注入:以 = + - @ (或控制字符)开头的单元格内容会在 +// Excel/CSV 中被当作公式执行,可能导致数据外泄或代码执行。前置单引号可让表格软件 +// 将其按纯文本处理(显示时自动隐藏该引号)。 +func sanitizeCell(s string) string { + if s == "" { + return s + } + r := []rune(s) + switch r[0] { + case '=', '+', '-', '@', '\t', '\r', '\n': + return "'" + s + } + return s +} + +func createExportExcelFile(user *db.User, questions []*db.Question) (*excelize.File, error) { + f := excelize.NewFile() + + sw, err := createXLSXStreamWriter(f, "账号信息", nil) + if err != nil { + return nil, errors.Wrap(err, "create xlsx stream writer: 提问") + } + // Set personal information sheet. + personalData := [][]interface{}{ + {"狼的提问箱 账号信息导出", fmt.Sprintf("导出时间 %s", time.Now().Format("2006-01-02 15:04:05"))}, + {"电子邮箱", user.Email}, + {"昵称", user.Name}, + {"个性域名", user.Domain}, + {"AcFun主页", user.Acfunlink}, + {"Bili主页", user.Bililink}, + {"微博主页", user.Weibolink}, + {"小红书主页", user.Xiaohongshulink}, + {"个人博客主页", user.Bloglink}, + {"介绍", user.Intro}, + {"二维码背景色", user.Qrcodebackcolor}, + {"二维码前景色", user.Qrcodecolor}, + {"二维码点大小", user.Dotscale}, + {"昵称颜色", user.Usernamecolor}, + {"介绍颜色", user.Introcolor}, + {"二维码探测图形颜色", user.Qrcodepdpcolor}, + {"头像 URL", user.Avatar}, + {"背景图 URL", user.Background}, + {"注册时间", user.CreatedAt}, + } + currentRow := 1 + for _, row := range personalData { + // personalData 是 [][]interface{}:字符串需净化防公式注入, + // 非字符串(如 CreatedAt 的 time.Time)原样写入,交给 excelize 处理。 + vals := make([]interface{}, len(row)) + for i, v := range row { + if s, ok := v.(string); ok { + vals[i] = sanitizeCell(s) + } else { + vals[i] = v + } + } + cell, _ := excelize.CoordinatesToCellName(1, currentRow) + _ = sw.SetRow(cell, vals) + currentRow++ + } + if err := sw.Flush(); err != nil { + return nil, errors.Wrap(err, "flush personal data") + } + + // Set questions sheet. + sw, err = createXLSXStreamWriter(f, "提问", []string{"提问时间", "问题", "回答"}) + if err != nil { + return nil, errors.Wrap(err, "create xlsx stream writer: 提问") + } + + currentRow = 2 // Include header row. + for _, question := range questions { + question := question + vals := []interface{}{question.CreatedAt, sanitizeCell(question.Content), sanitizeCell(question.Answer)} + cell, _ := excelize.CoordinatesToCellName(1, currentRow) + _ = sw.SetRow(cell, vals) + currentRow++ + } + if err := sw.Flush(); err != nil { + return nil, errors.Wrap(err, "flush personal data") + } + + f.SetActiveSheet(f.GetSheetIndex("提问")) + f.DeleteSheet("Sheet1") // Delete default sheet. + + return f, nil +} + +func DeactivateProfile(ctx context.Context) { + ctx.Success("user/deactivate") +} + +// ExportProfileJSON 以 JSON 格式全量导出账号数据(用户信息 + 提问/回答/追问 + 私聊消息), +// 符合可携带权要求,供用户备份/迁移。 +func ExportProfileJSON(ctx context.Context) { + user, err := db.Users.GetByID(ctx.Request().Context(), ctx.User.ID) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get user") + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "admin.export.errUser")) + ctx.Redirect("/user/profile") + return + } + + // 用户提问(含私密) + questions, err := db.Questions.GetByUserID(ctx.Request().Context(), user.ID, db.GetQuestionsByUserIDOptions{ + FilterAnswered: false, + ShowPrivate: true, + }) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get questions for export") + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "admin.export.errQuestion")) + ctx.Redirect("/user/profile") + return + } + + type exportedQuestion struct { + ID uint `json:"id"` + Content string `json:"content"` + Answer string `json:"answer"` + IsPrivate bool `json:"is_private"` + IsPinned bool `json:"is_pinned"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + FollowUps []*db.FollowUp `json:"follow_ups"` + Images []string `json:"images"` + } + + // 批量拉取所有提问的追问与图片(IN 查询 + 内存分组),避免逐题查询造成 N+1。 + questionIDs := make([]uint, 0, len(questions)) + for _, q := range questions { + questionIDs = append(questionIDs, q.ID) + } + followUpMap, err := db.FollowUps.GetByQuestionIDs(ctx.Request().Context(), questionIDs) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to batch get follow ups for export") + followUpMap = make(map[uint][]*db.FollowUp) + } + imageMap, err := db.UploadImages.GetByQuestionIDs(ctx.Request().Context(), questionIDs) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to batch get images for export") + imageMap = make(map[uint][]*db.UploadImage) + } + + exportQuestions := make([]exportedQuestion, 0, len(questions)) + for _, q := range questions { + followUps := followUpMap[q.ID] + if followUps == nil { + followUps = []*db.FollowUp{} + } + imgs := imageMap[q.ID] + imageURLs := make([]string, 0, len(imgs)) + for _, img := range imgs { + imageURLs = append(imageURLs, img.Key) + } + exportQuestions = append(exportQuestions, exportedQuestion{ + ID: q.ID, + Content: q.Content, + Answer: q.Answer, + IsPrivate: q.IsPrivate, + IsPinned: q.IsPinned, + CreatedAt: q.CreatedAt, + UpdatedAt: q.UpdatedAt, + FollowUps: followUps, + Images: imageURLs, + }) + } + + // 私聊会话与消息 + type exportedMessage struct { + Content string `json:"content"` + SenderID uint `json:"sender_id"` + CreatedAt time.Time `json:"created_at"` + } + type exportedConversation struct { + OwnerID uint `json:"owner_id"` + AskerID uint `json:"asker_id"` + IsClosed bool `json:"is_closed"` + CreatedAt time.Time `json:"created_at"` + Messages []exportedMessage `json:"messages"` + } + + exportConvs := make([]exportedConversation, 0) + allConvs := make([]*db.Conversation, 0) + if owned, err := db.Conversations.ListByOwner(ctx.Request().Context(), user.ID, 0, 0); err == nil { + allConvs = append(allConvs, owned...) + } + if asked, err := db.Conversations.ListByAsker(ctx.Request().Context(), user.ID, 0, 0); err == nil { + allConvs = append(allConvs, asked...) + } + // 去重并收集会话 ID,批量拉取全部消息(IN 查询 + 内存分组),避免逐会话查询造成 N+1。 + seen := make(map[uint]bool) + dedupedConvs := make([]*db.Conversation, 0, len(allConvs)) + convIDs := make([]uint, 0, len(allConvs)) + for _, conv := range allConvs { + if seen[conv.ID] { + continue + } + seen[conv.ID] = true + dedupedConvs = append(dedupedConvs, conv) + convIDs = append(convIDs, conv.ID) + } + msgMap, err := db.Messages.GetAllByConversationIDs(ctx.Request().Context(), convIDs) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to batch get messages for export") + msgMap = make(map[uint][]*db.Message) + } + for _, conv := range dedupedConvs { + msgs := msgMap[conv.ID] + if msgs == nil { + msgs = []*db.Message{} + } + exportMsgs := make([]exportedMessage, 0, len(msgs)) + for _, m := range msgs { + exportMsgs = append(exportMsgs, exportedMessage{ + Content: m.Content, + SenderID: m.SenderID, + CreatedAt: m.CreatedAt, + }) + } + exportConvs = append(exportConvs, exportedConversation{ + OwnerID: conv.OwnerID, + AskerID: conv.AskerID, + IsClosed: conv.IsClosed, + CreatedAt: conv.CreatedAt, + Messages: exportMsgs, + }) + } + + payload := map[string]interface{}{ + "exported_at": time.Now().Format(time.RFC3339), + "version": 1, + "user": user, + "questions": exportQuestions, + "conversations": exportConvs, + } + + fileName := fmt.Sprintf("提问箱账号数据-%s-%s.json", user.Domain, time.Now().Format("20060102150405")) + ctx.ResponseWriter().Header().Set("Content-Type", "application/json; charset=utf-8") + ctx.ResponseWriter().Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+url.QueryEscape(fileName)) + + enc := json.NewEncoder(ctx.ResponseWriter()) + enc.SetIndent("", " ") + if err := enc.Encode(payload); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to encode JSON export") + } +} + +func DeactivateProfileAction(ctx context.Context) { + if err := db.Users.Deactivate(ctx.Request().Context(), ctx.User.ID); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to deactivate user") + ctx.SetInternalError() + ctx.Success("user/deactivate") + return + } + ctx.Session.Flush() + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "admin.flash.deactivated")) + ctx.Redirect("/login") +} diff --git a/route/user/question.go b/route/user/question.go new file mode 100644 index 0000000..0fcebf0 --- /dev/null +++ b/route/user/question.go @@ -0,0 +1,480 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package user + +import ( + "fmt" + "net/url" + "sort" + "strconv" + "strings" + "time" + + "github.com/sirupsen/logrus" + + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/db" + "github.com/tamakyi/TamaBox/internal/dbutil" +) + +type conversationDetail struct { + Conversation *db.Conversation + OwnerDomain string + OwnerName string + FirstMessage string + IsBlocked bool +} + +type receivedItem struct { + Type string // "question_public", "question_private", "chat" + CreatedAt time.Time + Content string + Link string + IsAnswered bool + IsRead bool // 仅对普通提问有效:有效已读 = is_read=true 或已回答 + IsPrivate bool // 仅对普通提问有效 + IsBlocked bool // 仅对私聊有效 + QuestionID uint // 仅对普通提问有效,用于置顶操作 + IsPinned bool // 仅对普通提问有效 + PinLink string // 仅对普通提问有效:置顶/取消置顶操作链接 +} + +// QuestionList 用户后台提问列表(支持筛选与全文搜索) +func QuestionList(ctx context.Context) { + // 获取筛选参数 + sortParam := ctx.Query("sort") + if sortParam != "latest" && sortParam != "oldest" { + sortParam = "latest" + } + statusParam := ctx.Query("status") + if statusParam != "all" && statusParam != "answered" && statusParam != "unanswered" { + statusParam = "all" + } + typeParam := ctx.Query("type") + // 私聊已独立成"私聊"标签页(见 ReceivedChats),不再参与提问列表的类型筛选; + // 旧的 type=chat 链接统一归一为"全部",避免空列表。 + if typeParam != "all" && typeParam != "public" && typeParam != "private_question" { + typeParam = "all" + } + readParam := ctx.Query("read") + if readParam != "all" && readParam != "read" && readParam != "unread" { + readParam = "all" + } + keyword := strings.TrimSpace(ctx.Query("q")) + + // 映射排序方向 + sortOrder := "DESC" + if sortParam == "oldest" { + sortOrder = "ASC" + } + + // 映射回答状态 + answeredStatus := 0 // 全部 + if statusParam == "answered" { + answeredStatus = 1 + } else if statusParam == "unanswered" { + answeredStatus = 2 + } + + // 映射阅读状态 + readStatus := 0 // 全部 + if readParam == "read" { + readStatus = 1 + } else if readParam == "unread" { + readStatus = 2 + } + + // 管理后台进入问题详情的链接:携带 from=admin 及当前筛选参数, + // 使详情页底部「返回」按钮跳回带筛选条件的后台列表(保留 sort/status/type/read/q)。 + adminLinkQuery := url.Values{} + adminLinkQuery.Set("from", "admin") + if sortParam != "latest" { + adminLinkQuery.Set("sort", sortParam) + } + if statusParam != "all" { + adminLinkQuery.Set("status", statusParam) + } + if typeParam != "all" { + adminLinkQuery.Set("type", typeParam) + } + if readParam != "all" { + adminLinkQuery.Set("read", readParam) + } + if keyword != "" { + adminLinkQuery.Set("q", keyword) + } + adminLinkQueryStr := adminLinkQuery.Encode() + + var receivedItems []receivedItem + + // 1. 获取普通提问 + var questions []*db.Question + if keyword != "" { + results, err := db.Questions.SearchByUserID(ctx.Request().Context(), ctx.User.ID, keyword) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to search questions") + } else { + questions = results + } + } else if typeParam == "all" || typeParam == "public" || typeParam == "private_question" { + privateStatus := 0 // 全部 + if typeParam == "public" { + privateStatus = 1 // 仅公开 + } else if typeParam == "private_question" { + privateStatus = 2 // 仅私密 + } + + // 游标分页:每页固定大小,游标为上一页最后一条提问 ID(默认按创建时间倒序, + // 与 db.GetQuestionsByUserID 的 id < cursor 游标一致)。避免全量返回。 + questionsPageSize := 50 + qCursor := parseCursorUint(ctx.Query("q_cursor")) + qOpts := db.GetQuestionsByUserIDOptions{ + AnsweredStatus: answeredStatus, + PrivateStatus: privateStatus, + // PrivateStatus=0("全部")时必须显式声明含私密:store 层的旧调用兼容分支 + // 会把 "ShowPrivate=false 且未指定 PrivateStatus" 当作仅公开过滤, + // 导致私密提问在"全部"类型下不可见(与统计看板/内存过滤逻辑不一致)。 + ShowPrivate: true, + ReadStatus: readStatus, + SortOrder: sortOrder, + Cursor: &dbutil.Cursor{PageSize: questionsPageSize}, + } + if qCursor > 0 { + qOpts.Cursor.Value = qCursor + } + + var qs []*db.Question + var qErr error + qs, qErr = db.Questions.GetByUserID(ctx.Request().Context(), ctx.User.ID, qOpts) + if qErr != nil { + logrus.WithContext(ctx.Request().Context()).WithError(qErr).Error("Failed to get questions by user ID") + } else { + questions = qs + } + // 提问"加载更多"(仅非搜索路径支持游标分页):满页且仍有更多时暴露下一页游标 + if qErr == nil && len(qs) >= questionsPageSize { + lastQID := qs[len(qs)-1].ID + ctx.Data["HasMoreQuestions"] = true + ctx.Data["QuestionLoadMoreURL"] = buildQListPageURL(ctx.Request().URL.Query(), "q_cursor", strconv.FormatUint(uint64(lastQID), 10), "") + } else { + ctx.Data["HasMoreQuestions"] = false + } + } + + // 搜索场景下关键词已在 SQL 中匹配,但类型/状态筛选需在此统一应用, + // 使"搜索 + 筛选"可组合(完善筛选逻辑)。非搜索场景下此处与 SQL 过滤结果一致。 + for _, q := range questions { + if answeredStatus == 1 && q.Answer == "" { + continue + } + if answeredStatus == 2 && q.Answer != "" { + continue + } + if typeParam == "public" && q.IsPrivate { + continue + } + if typeParam == "private_question" && !q.IsPrivate { + continue + } + // 有效已读 = 手动已读(is_read) 或 已回答(answer != "") + isRead := q.IsRead || q.Answer != "" + if readStatus == 1 && !isRead { + continue + } + if readStatus == 2 && isRead { + continue + } + itemType := "question_public" + if q.IsPrivate { + itemType = "question_private" + } + receivedItems = append(receivedItems, receivedItem{ + Type: itemType, + CreatedAt: q.CreatedAt, + Content: q.Content, + Link: "/_/" + ctx.User.Domain + "/" + fmt.Sprint(q.ID) + "?" + adminLinkQueryStr, + IsAnswered: q.Answer != "", + IsRead: isRead, + IsPrivate: q.IsPrivate, + QuestionID: q.ID, + IsPinned: q.IsPinned, + PinLink: "/_/" + ctx.User.Domain + "/" + fmt.Sprint(q.ID) + "/pin", + }) + } + + // 2. 私聊会话:独立"私聊"标签页展示(ReceivedChats),不再混入提问列表。 + // 会话没有回答状态/阅读状态概念,不受提问的 sort/status/type/read/q 筛选影响。 + // 私聊列表分页(游标=offset),避免一次拉取全部会话造成内存/DB 压力。 + chatPageSize := 50 + chatOffset := parseCursorUint(ctx.Query("chat_cursor")) + + var receivedChats []receivedItem + convs, err := db.Conversations.ListByOwner(ctx.Request().Context(), ctx.User.ID, chatPageSize, int(chatOffset)) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get owned conversations") + } else if len(convs) > 0 { + // 批量获取首条消息 + convIDs := make([]uint, len(convs)) + for i, c := range convs { + convIDs[i] = c.ID + } + firstMsgMap, err := db.Messages.GetFirstMessagesByConversationIDs(ctx.Request().Context(), convIDs) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to batch get first messages") + firstMsgMap = make(map[uint]string) + } + + // 批量判断"我拉黑了哪些 asker",避免循环 IsUserBlocked 造成 N+1。 + askerIDs := make([]uint, 0, len(convs)) + for _, c := range convs { + askerIDs = append(askerIDs, c.AskerID) + } + blockedMap, err := db.Users.BlockedByUser(ctx.Request().Context(), ctx.User.ID, askerIDs) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to batch check blocked askers") + blockedMap = make(map[uint]bool) + } + + for _, conv := range convs { + receivedChats = append(receivedChats, receivedItem{ + Type: "chat", + CreatedAt: conv.CreatedAt, + Content: firstMsgMap[conv.ID], + Link: "/_/" + ctx.User.Domain + "/chat/" + conv.Token, + IsBlocked: blockedMap[conv.AskerID], + }) + } + } + ctx.Data["ReceivedChats"] = receivedChats + + // 私聊总数与"加载更多"判定(基于真实总数,而非当前页长度) + chatTotalReceived, cntErr := db.Conversations.CountByOwner(ctx.Request().Context(), ctx.User.ID) + if cntErr != nil { + logrus.WithContext(ctx.Request().Context()).WithError(cntErr).Error("Failed to count owned conversations") + chatTotalReceived = int64(len(convs)) + } + hasMoreChats := chatTotalReceived > 0 && (chatOffset+uint(len(convs)) < uint(chatTotalReceived)) + if hasMoreChats { + nextOffset := chatOffset + uint(len(convs)) + ctx.Data["ChatLoadMoreURL"] = buildQListPageURL(ctx.Request().URL.Query(), "chat_cursor", strconv.FormatUint(uint64(nextOffset), 10), "chats") + } + ctx.Data["HasMoreChats"] = hasMoreChats + + // 排序(搜索时保留搜索结果的倒序,不混合排序) + if keyword == "" { + sort.Slice(receivedItems, func(i, j int) bool { + if sortParam == "latest" { + return receivedItems[i].CreatedAt.After(receivedItems[j].CreatedAt) + } + return receivedItems[i].CreatedAt.Before(receivedItems[j].CreatedAt) + }) + } + + // ---------- 提问箱统计看板 ---------- + // 独立统计(不受筛选影响),供管理页顶部展示。全部用 COUNT 查询,避免全量拉取问题记录。 + totalCount, _ := db.Questions.Count(ctx.Request().Context(), ctx.User.ID, db.GetQuestionsCountOptions{ShowPrivate: true}) + answeredCount, _ := db.Questions.Count(ctx.Request().Context(), ctx.User.ID, db.GetQuestionsCountOptions{FilterAnswered: true, ShowPrivate: true}) + unansweredCount := totalCount - answeredCount + + isPrivateTrue := true + privateCount, _ := db.Questions.Count(ctx.Request().Context(), ctx.User.ID, db.GetQuestionsCountOptions{ShowPrivate: true, IsPrivate: &isPrivateTrue}) + isPinnedTrue := true + pinnedCount, _ := db.Questions.Count(ctx.Request().Context(), ctx.User.ID, db.GetQuestionsCountOptions{ShowPrivate: true, IsPinned: &isPinnedTrue}) + + // 阅读状态统计(不受其他筛选影响):已读 = is_read=true 或已回答;未读 = 其余。 + readCount, _ := db.Questions.Count(ctx.Request().Context(), ctx.User.ID, db.GetQuestionsCountOptions{ShowPrivate: true, ReadStatus: 1}) + unreadCount, _ := db.Questions.Count(ctx.Request().Context(), ctx.User.ID, db.GetQuestionsCountOptions{ShowPrivate: true, ReadStatus: 2}) + + ctx.Data["Stats"] = map[string]int64{ + "total": totalCount, + "answered": answeredCount, + "unanswered": unansweredCount, + "read": readCount, + "unread": unreadCount, + "private": privateCount, + "pinned": pinnedCount, + } + // 我创建的投票(提问箱「投票」面板用)—— 与投票管理列表共用富信息条目, + // 含参与数、有效状态(draft/published/not_started/ended/archived)、剩余时间等。 + // 分页:每页固定大小,游标为上一页最后一条投票 ID(按创建时间倒序),避免全量返回。 + votesPageSize := 50 + voteCursor := parseCursorUint(ctx.Query("vote_cursor")) + voteListOpts := db.ListVotesOptions{Cursor: &dbutil.Cursor{PageSize: votesPageSize}} + if voteCursor > 0 { + voteListOpts.Cursor.Value = voteCursor + } + myVotesRaw, err := db.Votes.ListByUserID(ctx.Request().Context(), ctx.User.ID, voteListOpts) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get my votes") + myVotesRaw = []*db.Vote{} + } + myVotes := buildVoteItems(ctx, myVotesRaw) + ctx.Data["MyVotes"] = myVotes + + // 投票统计看板(不受筛选影响):总数(真实全量计数)+ 本页有效进行中数 + voteTotal, _ := db.Votes.CountByUserID(ctx.Request().Context(), ctx.User.ID) + votePublished := int64(0) + for _, it := range myVotes { + if it.EffectiveStatus == db.VoteStatusPublished { + votePublished++ + } + } + ctx.Data["VoteStats"] = map[string]int64{ + "total": voteTotal, + "published": votePublished, + } + // 投票"加载更多":本页满页且仍有更多时暴露下一页游标(保留筛选参数并跳回投票面板) + if len(myVotesRaw) >= votesPageSize { + lastID := myVotesRaw[len(myVotesRaw)-1].ID + ctx.Data["HasMoreVotes"] = true + ctx.Data["VoteLoadMoreURL"] = buildQListPageURL(ctx.Request().URL.Query(), "vote_cursor", strconv.FormatUint(uint64(lastID), 10), "votes") + } else { + ctx.Data["HasMoreVotes"] = false + } + + ctx.Data["Keyword"] = keyword + + ctx.Data["ReceivedItems"] = receivedItems + ctx.Data["SelectedSort"] = sortParam + ctx.Data["SelectedStatus"] = statusParam + ctx.Data["SelectedRead"] = readParam + ctx.Data["SelectedType"] = typeParam + + // 我发起的私聊 — 同样使用批量查询与分页(复用 chat_cursor 游标) + askerConvs, err := db.Conversations.ListByAsker(ctx.Request().Context(), ctx.User.ID, chatPageSize, int(chatOffset)) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get asked conversations") + askerConvs = []*db.Conversation{} + } + var askerDetails []conversationDetail + if len(askerConvs) > 0 { + askerConvIDs := make([]uint, len(askerConvs)) + for i, c := range askerConvs { + askerConvIDs[i] = c.ID + } + askerFirstMsgMap, err := db.Messages.GetFirstMessagesByConversationIDs(ctx.Request().Context(), askerConvIDs) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to batch get first messages for asker") + askerFirstMsgMap = make(map[uint]string) + } + + // 批量查询所有 owner(去重),避免逐个 GetByID 造成 N+1;拉黑状态用批量关联表查询。 + ownerIDSet := make(map[uint]struct{}) + ownerIDs := make([]uint, 0, len(askerConvs)) + for _, conv := range askerConvs { + if _, ok := ownerIDSet[conv.OwnerID]; !ok { + ownerIDSet[conv.OwnerID] = struct{}{} + ownerIDs = append(ownerIDs, conv.OwnerID) + } + } + ownerMap := make(map[uint]*db.User) + if owners, err := db.Users.GetByIDs(ctx.Request().Context(), ownerIDs); err == nil { + for _, u := range owners { + ownerMap[u.ID] = u + } + } else { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to batch get owners") + } + + // 批量判断"哪些 owner 拉黑了我",避免循环查询。 + blockedByMap, err := db.Users.BlockedByAnyOf(ctx.Request().Context(), ownerIDs, ctx.User.ID) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to batch check blocked by owners") + blockedByMap = make(map[uint]bool) + } + + for _, conv := range askerConvs { + firstMsg := askerFirstMsgMap[conv.ID] + ownerDomain := "unknown" + ownerName := "未知用户" + if owner, ok := ownerMap[conv.OwnerID]; ok { + ownerDomain = owner.Domain + ownerName = owner.Name + } + askerDetails = append(askerDetails, conversationDetail{ + Conversation: conv, + OwnerDomain: ownerDomain, + OwnerName: ownerName, + FirstMessage: firstMsg, + IsBlocked: blockedByMap[conv.OwnerID], + }) + } + } + ctx.Data["ConversationDetails"] = askerDetails + + // 我发起的私聊总数与"加载更多"判定 + askerTotal, cntErr := db.Conversations.CountByAsker(ctx.Request().Context(), ctx.User.ID) + if cntErr != nil { + logrus.WithContext(ctx.Request().Context()).WithError(cntErr).Error("Failed to count asked conversations") + askerTotal = int64(len(askerConvs)) + } + hasMoreAsked := askerTotal > 0 && (chatOffset+uint(len(askerConvs)) < uint(askerTotal)) + if hasMoreAsked { + nextOffset := chatOffset + uint(len(askerConvs)) + ctx.Data["AskedChatsLoadMoreURL"] = buildQListPageURL(ctx.Request().URL.Query(), "chat_cursor", strconv.FormatUint(uint64(nextOffset), 10), "chats") + } + ctx.Data["HasMoreAskedChats"] = hasMoreAsked + + // ---------- 私聊统计看板 ---------- + // 与提问/投票看板一致,展示在「私聊」面板的顶部。全部基于已加载的会话切片计算, + // 不触发额外数据库查询:总数 = 我收到的(作为箱主) + 我发起的(作为提问者); + // 已关闭 = 两端会话中 is_closed=true 的计数。 + chatClosed := int64(0) + for _, c := range convs { + if c.IsClosed { + chatClosed++ + } + } + for _, c := range askerConvs { + if c.IsClosed { + chatClosed++ + } + } + ctx.Data["ChatStats"] = map[string]int64{ + "total": chatTotalReceived + askerTotal, + "received": chatTotalReceived, + "initiated": askerTotal, + "closed": chatClosed, + } + + ctx.Success("user/question-list") +} + +// parseCursorUint 将游标字符串安全解析为 uint;空或非法返回 0(表示从头分页)。 +func parseCursorUint(s string) uint { + s = strings.TrimSpace(s) + if s == "" { + return 0 + } + id, err := strconv.ParseUint(s, 10, 64) + if err != nil || id == 0 { + return 0 + } + return uint(id) +} + +// buildQListPageURL 在保留当前筛选/搜索参数的基础上构造"加载更多"链接, +// 并追加锚点(anchor 指定跳转到的面板;空串表示默认提问面板)。 +// 用于投票/提问列表的游标分页,避免丢失已选的 sort/status/type/q 等筛选条件。 +func buildQListPageURL(current url.Values, key, val, anchor string) string { + q := url.Values{} + for k, vs := range current { + q[k] = vs + } + if val != "" { + q.Set(key, val) + } else { + q.Del(key) + } + qs := q.Encode() + path := "/user/questions" + if qs != "" { + path += "?" + qs + } + if anchor != "" { + path += "#" + anchor + } + return path +} diff --git a/route/user/tags.go b/route/user/tags.go new file mode 100644 index 0000000..0909d27 --- /dev/null +++ b/route/user/tags.go @@ -0,0 +1,73 @@ +// Copyright 2026 tamakyi. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package user + +import ( + "strings" + + "github.com/sirupsen/logrus" + + "github.com/tamakyi/TamaBox/internal/conf" + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/db" + "github.com/tamakyi/TamaBox/internal/form" + "github.com/tamakyi/TamaBox/internal/i18n" +) + +func UpdateTags(ctx context.Context, f form.UpdateTags) { + // 反序列化失败(如请求体超限)时零值 Tags="" / ShowInHome="" 会静默清空标签、 + // 关闭首页展示——先中止,不触碰现有标签。 + if abortOnFormError(ctx, "/user/profile") { + return + } + + tagsStr := f.Tags + tagsStr = strings.ReplaceAll(tagsStr, ",", ",") + tagsStr = strings.TrimSpace(tagsStr) + + words := make([]string, 0) + wordSet := make(map[string]struct{}) + for _, tag := range strings.Split(tagsStr, ",") { + tag = strings.TrimSpace(tag) + if tag == "" { + continue + } + if _, ok := wordSet[tag]; ok { + continue + } + wordSet[tag] = struct{}{} + + if len([]rune(tag)) > conf.Limits.MaxTagLen { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "admin.flash.tagTooLong", tag)) + ctx.Redirect("/user/profile") + return + } + words = append(words, tag) + } + + if len(words) > conf.Limits.MaxTags { + ctx.SetErrorFlash(i18n.T(ctx.Lang(), "admin.flash.tagsTooMany")) + ctx.Redirect("/user/profile") + return + } + + showInHome := false + if f.ShowInHome == "on" || f.ShowInHome == "1" || f.ShowInHome == "true" { + showInHome = true + } + + if err := db.Users.UpdateTags(ctx.Request().Context(), ctx.User.ID, db.UpdateTagsOptions{ + Tags: strings.Join(words, ","), + ShowInHome: showInHome, + }); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to update tags") + ctx.SetInternalErrorFlash() + ctx.Redirect("/user/profile") + return + } + + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "admin.flash.tagsUpdated")) + ctx.Redirect("/user/profile") +} diff --git a/route/user/vote.go b/route/user/vote.go new file mode 100644 index 0000000..7faba14 --- /dev/null +++ b/route/user/vote.go @@ -0,0 +1,1318 @@ +// Copyright 2026 tamakyi. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package user + +import ( + "encoding/csv" + "encoding/json" + "fmt" + "net/http" + "sort" + "strconv" + "strings" + "time" + + "go.opentelemetry.io/otel/trace" + + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + "gorm.io/datatypes" + + "github.com/tamakyi/TamaBox/internal/cache" + "github.com/tamakyi/TamaBox/internal/conf" + "github.com/tamakyi/TamaBox/internal/context" + "github.com/tamakyi/TamaBox/internal/db" + "github.com/tamakyi/TamaBox/internal/i18n" + "github.com/tamakyi/TamaBox/internal/security/censor" + votepkg "github.com/tamakyi/TamaBox/route/vote" +) + +// voteTextRepliesCache 箱主表单投票"回复明细"(逐条文本)的短 TTL 缓存。 +// 该视图仅在箱主结果页展示,且需在 Go 层逐条 json.Unmarshal 全部提交记录(O(N)), +// 缓存可显著降低重算开销;结果页非强一致,30s 陈旧可接受。 +var voteTextRepliesCache = cache.NewTTLCache(64) + +// voteTextRepliesCacheTTL 回复明细缓存有效期。 +const voteTextRepliesCacheTTL = 30 * time.Second + +// ---------------- 表单解析 ---------------- + +// voteFormFieldInput 表单字段的前端输入结构(vote-form.html 中的 JS 数组)。 +type voteFormFieldInput struct { + FieldType string `json:"field_type"` + Label string `json:"label"` + Required bool `json:"required"` + MaxLength int `json:"max_length"` + Options []string `json:"options"` // 选项数组(select/radio/checkbox/rank),前端逐条添加 + AllowCustom bool `json:"allow_custom"` // 允许补充自定义选项(radio/select/checkbox) +} + +// voteForm 解析后的完整表单(含选项与表单字段)。 +type voteForm struct { + opts db.CreateVoteOptions + options []string + formFields []db.CreateVoteFormFieldOptions + censorMetadata datatypes.JSON // 标题审核结果 +} + +// censorCheck 对单段文本做内容审核。 +// fail-closed:审核服务异常时拒绝发布(与提问/回答流程一致); +// 未开启 EnableTextCensor 时 censor.Text 直接放行,不影响开发环境。 +func censorCheck(ctx context.Context, text string) error { + resp, err := censor.Text(ctx.Request().Context(), text) + if err != nil { + return errors.New(i18n.T(ctx.Lang(), "censor.unavailable")) + } + if !resp.Pass { + return errors.New(resp.ErrorMessage()) + } + return nil +} + +// parseTimeInput 解析 "YYYY-MM-DDTHH:MM"(HTML datetime-local 格式),空字符串返回 nil。 +// 使用 time.Local 解析:datetime-local 提交的是无时区信息的时间串,按服务端本地时区解释, +// 与 Evaluate 中 time.Now() 的比较基准保持一致(旧的 time.Parse 会解析成 UTC,产生时区偏移)。 +func parseTimeInput(ctx context.Context, s string) (*time.Time, error) { + s = strings.TrimSpace(s) + if s == "" { + return nil, nil + } + t, err := time.ParseInLocation("2006-01-02T15:04", s, time.Local) + if err != nil { + return nil, errors.New(i18n.T(ctx.Lang(), "vote.err.timeFormat")) + } + return &t, nil +} + +// parseVoteForm 手动解析投票表单(完整:元信息 + 类型 + 选项/字段)。 +// 说明:不使用 form.Bind —— Bind 的反射绑定会把 string 直接赋给 int 字段导致 panic, +// 且选项/表单字段数组需要 JSON 解析,手动解析更安全。 +// draft=true 时放宽“选项/字段数量”与内容审核要求(详见 parseVoteMeta/parseOptions/parseFormFields), +// 使草稿可随时暂存、不丢失已填内容。 +func parseVoteForm(ctx context.Context, draft bool) (*voteForm, error) { + form, err := parseVoteMeta(ctx, draft) + if err != nil { + return nil, err + } + + voteType := strings.TrimSpace(ctx.Request().FormValue("type")) + switch voteType { + case db.VoteTypeSingle, db.VoteTypeMultiple, db.VoteTypeRating, db.VoteTypeRank, db.VoteTypeForm: + default: + return nil, errors.New(i18n.T(ctx.Lang(), "vote.err.type")) + } + form.opts.Type = voteType + + maxChoices := 1 + if voteType == db.VoteTypeMultiple { + maxChoices, _ = strconv.Atoi(strings.TrimSpace(ctx.Request().FormValue("max_choices"))) + if maxChoices < 1 { + maxChoices = 1 + } + if maxChoices > 20 { + return nil, errors.New(i18n.T(ctx.Lang(), "vote.err.maxChoicesLimit")) + } + } + form.opts.MaxChoices = maxChoices + + // 选项 / 表单字段解析与校验 + if voteType == db.VoteTypeForm { + if err := parseFormFields(ctx, form, draft); err != nil { + return nil, err + } + } else { + if err := parseOptions(ctx, form, voteType, maxChoices, draft); err != nil { + return nil, err + } + } + + return form, nil +} + +// parseVoteMetaForm 仅解析元信息(发布后编辑用):标题/描述/可见性/范围/结果策略/ +// 自定义开关/时间窗/防刷/验证码。类型与选项/字段发布后不可修改(避免破坏历史数据归因)。 +func parseVoteMetaForm(ctx context.Context) (*voteForm, error) { + return parseVoteMeta(ctx, false) +} + +// parseVoteMeta 解析投票元信息(不含类型与选项/字段)。 +// draft=true 时放宽校验并跳过内容审核:草稿为私有内容,保存时不应因审核服务抖动而丢失; +// 审核统一在发布(VotePublish)时执行,确保对外公开内容仍受管控。 +func parseVoteMeta(ctx context.Context, draft bool) (*voteForm, error) { + get := func(name string) string { return strings.TrimSpace(ctx.Request().FormValue(name)) } + + title := get("title") + // 草稿允许暂存空标题(发布前再补全);非草稿必须填写 + if title == "" && !draft { + return nil, errors.New(i18n.T(ctx.Lang(), "vote.err.titleRequired")) + } + if len([]rune(title)) > 100 { + return nil, errors.New(i18n.T(ctx.Lang(), "vote.err.titleTooLong")) + } + description := get("description") + if len([]rune(description)) > 5000 { + return nil, errors.New(i18n.T(ctx.Lang(), "vote.err.descriptionTooLong")) + } + + // 内容审核(fail-closed):非草稿执行;草稿跳过(见上说明) + var censorMeta datatypes.JSON + if !draft { + titleCensor, err := censor.Text(ctx.Request().Context(), title) + if err != nil { + return nil, errors.New("内容审核服务暂时不可用,请稍后再试") + } + if !titleCensor.Pass { + return nil, errors.New(titleCensor.ErrorMessage()) + } + censorMeta = datatypes.JSON(titleCensor.ToJSON()) + if description != "" { + if err := censorCheck(ctx, description); err != nil { + return nil, err + } + } + } + + visibility := get("visibility") + switch visibility { + case db.VoteVisibilityPublic, db.VoteVisibilityLinkOnly: + default: + return nil, errors.New(i18n.T(ctx.Lang(), "vote.err.visibility")) + } + + voterScope := get("voter_scope") + switch voterScope { + case db.VoteVoterScopeAnyone, db.VoteVoterScopeRegisteredOnly: + default: + return nil, errors.New(i18n.T(ctx.Lang(), "vote.err.voterScope")) + } + + showResult := get("show_result") + switch showResult { + case db.VoteShowResultAfterVote, db.VoteShowResultAfterEnd, db.VoteShowResultOwnerOnly: + default: + return nil, errors.New(i18n.T(ctx.Lang(), "vote.err.showResult")) + } + + allowCustom := get("allow_custom") == "on" + // 匿名投票始终要求验证码(决策 #3 / P2-2):忽略客户端开关,强制开启,关闭复选框无法解除。 + requireCaptcha := true + + // 该策略由业务规则固定为一人一票;不从客户端读取已废弃的配置字段, + // 避免旧页面或手工请求写入与数据库约束冲突的多票语义。 + maxVotes := 1 + + startAt, err := parseTimeInput(ctx, get("start_at")) + if err != nil { + return nil, err + } + endAt, err := parseTimeInput(ctx, get("end_at")) + if err != nil { + return nil, err + } + if startAt != nil && endAt != nil && !endAt.After(*startAt) { + return nil, errors.New(i18n.T(ctx.Lang(), "vote.err.timeRange")) + } + + // 定量收集上限:收集到指定份数后自动结束该投票(0 = 不限制) + quotaLimit, err := parseQuotaLimit(get("quota_limit")) + if err != nil { + return nil, errors.New(i18n.T(ctx.Lang(), "vote.err.quota")) + } + + return &voteForm{ + opts: db.CreateVoteOptions{ + UserID: ctx.User.ID, + Title: title, + Description: description, + Visibility: visibility, + VoterScope: voterScope, + ShowResult: showResult, + AllowCustom: allowCustom, + StartAt: startAt, + EndAt: endAt, + MaxVotesPerFingerprint: maxVotes, + RequireCaptcha: requireCaptcha, + QuotaLimit: int(quotaLimit), + }, + censorMetadata: censorMeta, + }, nil +} + +func parseOptions(ctx context.Context, form *voteForm, voteType string, maxChoices int, draft bool) error { + raw := strings.TrimSpace(ctx.Request().FormValue("options")) + if raw == "" { + // 草稿允许暂未添加选项;非草稿必须至少 2 个 + if !draft { + return errors.New(i18n.T(ctx.Lang(), "vote.err.optionsTooFew")) + } + form.options = nil + return nil + } + var options []string + if err := json.Unmarshal([]byte(raw), &options); err != nil { + return errors.New(i18n.T(ctx.Lang(), "vote.err.optionsFormat")) + } + + cleaned := make([]string, 0, len(options)) + for _, o := range options { + o = strings.TrimSpace(o) + if o == "" { + continue + } + if len([]rune(o)) > conf.Limits.VoteOptionLen { + return errors.New(i18n.T(ctx.Lang(), "vote.err.optionTooLong", conf.Limits.VoteOptionLen)) + } + // 选项内容审核(fail-closed):草稿跳过,发布时统一审核 + if !draft { + if err := censorCheck(ctx, o); err != nil { + return err + } + } + cleaned = append(cleaned, o) + } + + // 评分题不需要选项(固定 1-10 分) + if voteType == db.VoteTypeRating { + form.options = nil + return nil + } + + // 草稿允许暂存少于 2 个选项;非草稿必须至少 2 个 + if !draft && len(cleaned) < 2 { + return errors.New(i18n.T(ctx.Lang(), "vote.err.optionsTooFew")) + } + if voteType == db.VoteTypeMultiple && maxChoices > len(cleaned) { + return errors.New(i18n.T(ctx.Lang(), "vote.err.maxChoicesExceed")) + } + form.options = cleaned + return nil +} + +func parseFormFields(ctx context.Context, form *voteForm, draft bool) error { + raw := strings.TrimSpace(ctx.Request().FormValue("form_fields")) + if raw == "" { + // 草稿允许暂未添加字段;非草稿必须至少 1 个 + if !draft { + return errors.New(i18n.T(ctx.Lang(), "vote.err.fieldsTooFew")) + } + return nil + } + var inputs []voteFormFieldInput + if err := json.Unmarshal([]byte(raw), &inputs); err != nil { + return errors.New(i18n.T(ctx.Lang(), "vote.err.fieldsFormat")) + } + if len(inputs) == 0 { + if !draft { + return errors.New(i18n.T(ctx.Lang(), "vote.err.fieldsTooFew")) + } + return nil + } + if len(inputs) > 50 { + return errors.New(i18n.T(ctx.Lang(), "vote.err.fieldsTooMany")) + } + + // label 必须唯一:FormData 以 label 为 key,重复会导致提交数据互相覆盖 + seenLabels := make(map[string]bool, len(inputs)) + for i, in := range inputs { + switch in.FieldType { + case db.VoteFormFieldTypeText, db.VoteFormFieldTypeTextarea, db.VoteFormFieldTypeSelect, + db.VoteFormFieldTypeRadio, db.VoteFormFieldTypeCheckbox, db.VoteFormFieldTypeNumber, + db.VoteFormFieldTypeRating, db.VoteFormFieldTypeRank: + default: + return errors.New(i18n.T(ctx.Lang(), "vote.err.fieldType")) + } + label := strings.TrimSpace(in.Label) + if label == "" { + return errors.New(i18n.T(ctx.Lang(), "vote.err.fieldLabelMissing", i+1)) + } + if len([]rune(label)) > 100 { + return errors.New(i18n.T(ctx.Lang(), "vote.err.fieldLabelTooLong", i+1)) + } + if seenLabels[label] { + return errors.New(i18n.T(ctx.Lang(), "vote.err.fieldLabelDuplicate", label)) + } + seenLabels[label] = true + if in.MaxLength < 0 || in.MaxLength > 2000 { + return errors.New(i18n.T(ctx.Lang(), "vote.err.fieldMaxLength", i+1)) + } + // 字段标签审核(fail-closed):草稿跳过,发布时统一审核 + if !draft { + if err := censorCheck(ctx, label); err != nil { + return err + } + } + + field := db.CreateVoteFormFieldOptions{ + FieldType: in.FieldType, + Label: label, + Required: in.Required, + MaxLength: in.MaxLength, + SortOrder: i, + AllowCustom: in.AllowCustom, + } + + switch in.FieldType { + case db.VoteFormFieldTypeSelect, db.VoteFormFieldTypeRadio, db.VoteFormFieldTypeCheckbox, db.VoteFormFieldTypeRank: + var opts []string + for _, raw := range in.Options { + opts = append(opts, splitOptionTokens(raw)...) + } + // "其他"保留标记不允许作为预设选项内容(参与端用它触发自定义输入) + for _, o := range opts { + if o == db.CustomFieldMarker { + return errors.New(i18n.T(ctx.Lang(), "vote.err.fieldReservedOption", i+1, label)) + } + // 单个选项长度与单选/多选选项同规则(vote-form.html 前端 maxlength 同源, + // 此前仅有前端软限制,这里补齐后端兜底校验) + if len([]rune(o)) > conf.Limits.VoteOptionLen { + return errors.New(i18n.T(ctx.Lang(), "vote.err.optionTooLong", conf.Limits.VoteOptionLen)) + } + } + if len(opts) < 1 { + // 草稿允许暂未填写字段选项;非草稿必须至少 1 个 + if !draft { + return errors.New(i18n.T(ctx.Lang(), "vote.err.fieldOptionsTooFew", i+1, label)) + } + } + if in.FieldType == db.VoteFormFieldTypeRank && len(opts) < 2 { + if !draft { + return errors.New(i18n.T(ctx.Lang(), "vote.err.fieldRankTooFew", i+1, label)) + } + } + // 预置选项审核:草稿跳过,发布时统一审核 + if !draft { + for _, o := range opts { + if err := censorCheck(ctx, o); err != nil { + return err + } + } + } + optsJSON, err := json.Marshal(opts) + if err != nil { + return errors.New(i18n.T(ctx.Lang(), "vote.err.fieldSerialize")) + } + field.Options = string(optsJSON) + } + form.formFields = append(form.formFields, field) + } + return nil +} + +// ---------------- 归属校验 ---------------- + +// getOwnedVote 获取当前登录用户拥有的投票,校验归属。 +func getOwnedVote(ctx context.Context, voteIDStr string) (*db.Vote, error) { + voteID, err := strconv.ParseUint(voteIDStr, 10, 64) + if err != nil { + return nil, errors.New(i18n.T(ctx.Lang(), "vote.err.invalidID")) + } + vote, err := db.Votes.GetByID(ctx.Request().Context(), uint(voteID)) + if err != nil { + return nil, errors.New(i18n.T(ctx.Lang(), "vote.err.notExist")) + } + if vote.UserID != ctx.User.ID { + return nil, errors.New(i18n.T(ctx.Lang(), "vote.err.noPermission")) + } + return vote, nil +} + +// ---------------- 处理器 ---------------- + +// VoteList 投票管理列表(含每票参与数统计)。 +// effectiveVoteStatus 计算投票的有效展示状态(status + 时间窗联合判断): +// published 且未到开始时间 → 未开始;published 且已过结束时间 → 已结束; +// 其余与 status 字段一致。管理列表据此展示,避免"已过结束时间仍显示进行中"。 +func effectiveVoteStatus(v *db.Vote, now time.Time) string { + if v.Status != db.VoteStatusPublished { + return v.Status + } + if v.StartAt != nil && now.Before(*v.StartAt) { + return db.VoteStatusNotStarted + } + if v.EndAt != nil && !now.Before(*v.EndAt) { + return db.VoteStatusEnded + } + return db.VoteStatusPublished +} + +// formatRemaining 格式化投票剩余时间(如"剩余 2 天 3 小时"),多语言文案。 +func formatRemaining(lang string, endAt time.Time, now time.Time) string { + d := endAt.Sub(now) + if d <= 0 { + return "" + } + days := int(d.Hours()) / 24 + hours := int(d.Hours()) % 24 + mins := int(d.Minutes()) % 60 + parts := []string{} + if days > 0 { + parts = append(parts, fmt.Sprintf("%d%s", days, i18n.T(lang, "vote.durationDay"))) + } + if hours > 0 { + parts = append(parts, fmt.Sprintf("%d%s", hours, i18n.T(lang, "vote.durationHour"))) + } + if mins > 0 && days == 0 { + parts = append(parts, fmt.Sprintf("%d%s", mins, i18n.T(lang, "vote.durationMinute"))) + } + if len(parts) == 0 { + return "" + } + return i18n.T(lang, "vote.remainLabel") + strings.Join(parts, " ") +} + +// voteItem 管理面板/投票列表所需的富信息条目(参与数、有效状态、剩余时间)。 +type voteItem struct { + *db.Vote + SubmissionCount int64 + OptionCount int64 + EffectiveStatus string + RemainingText string // 有效进行中:剩余时间;无结束时间:无限期;其余为空 +} + +// buildVoteItems 将投票列表转换为管理面板所需的富信息条目。 +// QuestionList 的「我的提问箱 · 投票」面板与此前独立的投票管理列表共用,避免重复统计逻辑。 +// +// 性能:参与数与选项数通过 CountByVoteIDs 批量聚合(2 条 WHERE vote_id IN (...)), +// 替代原先对每票各发 2 次 COUNT 的 N+1 查询,N 张投票从 2N 条 SQL 降为 2 条。 +func buildVoteItems(ctx context.Context, votes []*db.Vote) []*voteItem { + lang := i18n.Default + if l, ok := ctx.Data["Lang"].(string); ok && l != "" { + lang = l + } + + now := time.Now() + items := make([]*voteItem, 0, len(votes)) + + // 批量预取参与数与选项数(避免 N+1) + ids := make([]uint, 0, len(votes)) + for _, v := range votes { + ids = append(ids, v.ID) + } + subCounts := map[uint]int64{} + optCounts := map[uint]int64{} + if len(ids) > 0 { + if m, err := db.VoteSubmissions.CountByVoteIDs(ctx.Request().Context(), ids); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Warn("Failed to batch count submissions") + } else { + subCounts = m + } + if m, err := db.VoteOptions.CountByVoteIDs(ctx.Request().Context(), ids); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Warn("Failed to batch count options") + } else { + optCounts = m + } + } + + for _, v := range votes { + count := subCounts[v.ID] + optionCount := optCounts[v.ID] + eff := effectiveVoteStatus(v, now) + remaining := "" + if eff == db.VoteStatusPublished { + if v.EndAt != nil { + remaining = formatRemaining(lang, *v.EndAt, now) + } else { + remaining = i18n.T(lang, "vote.perpetual") + } + } + items = append(items, &voteItem{ + Vote: v, + SubmissionCount: count, + OptionCount: optionCount, + EffectiveStatus: eff, + RemainingText: remaining, + }) + } + return items +} + +// VoteList 投票管理列表(保留以兼容旧链接):投票管理已合并到「我的提问箱」的投票面板, +// 直接跳转 /user/questions#votes,避免两套功能重复的页面。 +func VoteList(ctx context.Context) { + ctx.Redirect("/user/questions#votes") +} + +// VoteNew 新建投票页面。 +func VoteNew(ctx context.Context) { + ctx.Data["Title"] = "新建投票" + ctx.Data["IsEdit"] = false + ctx.Data["MaxVoteOptionLen"] = conf.Limits.VoteOptionLen // 选项输入框 maxlength 同源(vote-form.html JS) + // 默认投票类型为表单收集(用户要求);同时给定模板零值兜底,避免切到多选时 max_choices 显示 0。 + ctx.Data["Vote"] = &db.Vote{ + Type: db.VoteTypeForm, + MaxChoices: 3, + MaxVotesPerFingerprint: 1, + } + ctx.Data["InitialOptions"] = []string{} + ctx.Data["InitialFields"] = []voteFormFieldInput{} + ctx.Success("user/vote-form") +} + +// renderVoteFormWithInput 在保存失败时重新渲染投票表单并回填用户已提交的内容, +// 避免校验/审核/数据库错误导致整页输入被清空(原先 Redirect("/user/votes/new") 会丢失全部数据)。 +// isEdit=true 时回填 vote.ID,保留编辑动作的提交地址。 +// +// flashMsg/internal 用于在同请求内直接写入 c.Data 的错误提示(而非 session flash): +// 本项目的 flash 在请求开始时读取进 c.Data,随后写入 session 的 flash 不会被本次渲染读到, +// 且会残留到下一次请求造成"陈旧错误"串页;故错误回填采用直接写 c.Data 的方式。 +func renderVoteFormWithInput(ctx context.Context, isEdit bool, voteID uint, flashMsg string, internal bool) { + ctx.Data["MaxVoteOptionLen"] = conf.Limits.VoteOptionLen // 选项输入框 maxlength 同源(vote-form.html JS) + get := func(n string) string { return strings.TrimSpace(ctx.Request().FormValue(n)) } + title := get("title") + description := get("description") + voteType := get("type") + visibility := get("visibility") + voterScope := get("voter_scope") + showResult := get("show_result") + maxChoices, _ := strconv.Atoi(get("max_choices")) + if maxChoices < 1 { + maxChoices = 1 + } + // 与数据库唯一索引保持一致;该策略不再由表单配置。 + maxVotes := 1 + allowCustom := get("allow_custom") == "on" + // 匿名投票始终要求验证码(决策 #3 / P2-2):忽略客户端开关,强制开启。 + requireCaptcha := true + startAt, _ := parseTimeInput(ctx, get("start_at")) + endAt, _ := parseTimeInput(ctx, get("end_at")) + quotaLimit, _ := parseQuotaLimit(get("quota_limit")) + + var initialOptions []string + if raw := strings.TrimSpace(ctx.Request().FormValue("options")); raw != "" { + _ = json.Unmarshal([]byte(raw), &initialOptions) + } + var initialFields []voteFormFieldInput + if raw := strings.TrimSpace(ctx.Request().FormValue("form_fields")); raw != "" { + _ = json.Unmarshal([]byte(raw), &initialFields) + } + + vote := &db.Vote{ + Title: title, + Description: description, + Type: voteType, + Visibility: visibility, + VoterScope: voterScope, + ShowResult: showResult, + MaxChoices: maxChoices, + MaxVotesPerFingerprint: maxVotes, + AllowCustom: allowCustom, + RequireCaptcha: requireCaptcha, + StartAt: startAt, + EndAt: endAt, + QuotaLimit: int(quotaLimit), + } + if isEdit { + vote.ID = voteID + } + + ctx.Data["Title"] = "新建投票" + if isEdit { + ctx.Data["Title"] = "编辑投票" + } + ctx.Data["IsEdit"] = isEdit + ctx.Data["Vote"] = vote + ctx.Data["LockedContent"] = false + ctx.Data["InitialOptions"] = initialOptions + ctx.Data["InitialFields"] = initialFields + if startAt != nil { + ctx.Data["StartAtStr"] = startAt.Format("2006-01-02T15:04") + } + if endAt != nil { + ctx.Data["EndAtStr"] = endAt.Format("2006-01-02T15:04") + } + + // 同请求错误提示:直接写入 c.Data(见函数注释,不能用 session flash) + if internal { + ctx.Data["HasError"] = true + ctx.Data["Error"] = "服务内部错误,请稍后重试。" + span := trace.SpanFromContext(ctx.Request().Context()) + ctx.Data["FlashTip"] = fmt.Sprintf("若问题一直出现,请带上该段字符 %s 提交反馈。", span.SpanContext().TraceID().String()) + } else if flashMsg != "" { + ctx.Data["HasError"] = true + ctx.Data["Error"] = flashMsg + } + + ctx.Success("user/vote-form") +} + +// VoteCreate 创建投票(默认草稿状态)。 +// 草稿保存放宽校验并跳过内容审核(见 parseVoteForm/parseVoteMeta);任何错误均回填表单而非清空输入。 +// action=publish 时:先按草稿保存,再执行发布校验(结构 + 审核),通过则直接发布;失败则保留草稿并停留在编辑页,避免重复创建。 +func VoteCreate(ctx context.Context) { + action := strings.TrimSpace(ctx.Request().FormValue("action")) + + form, err := parseVoteForm(ctx, true) + if err != nil { + renderVoteFormWithInput(ctx, false, 0, err.Error(), false) + return + } + form.opts.CensorMetadata = form.censorMetadata + + vote, err := db.Votes.Create(ctx.Request().Context(), form.opts) + if err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to create vote") + renderVoteFormWithInput(ctx, false, 0, "", true) + return + } + + if len(form.options) > 0 { + if _, err := db.VoteOptions.BulkCreate(ctx.Request().Context(), vote.ID, form.options); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to create vote options") + _ = db.Votes.DeleteByID(ctx.Request().Context(), vote.ID) // 回滚本次已建的空草稿,避免孤儿记录 + renderVoteFormWithInput(ctx, false, 0, "", true) + return + } + } + if len(form.formFields) > 0 { + for i := range form.formFields { + form.formFields[i].VoteID = vote.ID + } + if _, err := db.VoteFormFields.BulkCreate(ctx.Request().Context(), vote.ID, form.formFields); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to create vote form fields") + _ = db.Votes.DeleteByID(ctx.Request().Context(), vote.ID) // 回滚本次已建的空草稿,避免孤儿记录 + renderVoteFormWithInput(ctx, false, 0, "", true) + return + } + } + + editURL := "/user/votes/" + fmt.Sprint(vote.ID) + "/edit" + + // action=publish:已保存为草稿,再做发布校验;失败则保留草稿并停留在编辑页,避免重复创建 + if action == "publish" { + if err := validateForPublish(ctx, vote); err != nil { + ctx.SetErrorFlash(err.Error()) + ctx.Redirect(editURL) + return + } + if err := db.Votes.UpdateStatus(ctx.Request().Context(), vote.ID, db.VoteStatusPublished); err != nil { + logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to publish vote") + ctx.SetInternalErrorFlash() + ctx.Redirect(editURL) + return + } + shareURL := fmt.Sprintf("%s/vote/%s", strings.TrimRight(conf.App.ExternalURL, "/"), vote.LinkToken) + ctx.SetSuccessFlash(i18n.T(ctx.Lang(), "vote.flash.published", shareURL)) + ctx.Redirect("/user/questions#votes") + return + } + + // 草稿保存成功:停留在编辑页,使用页面 toast 提示,避免 success flash 与 toast 重复展示。 + ctx.Redirect(editURL + "?saved=1") +} + +// VoteEdit 编辑投票页面(预填选项与表单字段)。 +func VoteEdit(ctx context.Context) { + vote, err := getOwnedVote(ctx, ctx.Param("voteID")) + if err != nil { + ctx.SetErrorFlash(err.Error()) + ctx.Redirect("/user/questions#votes") + return + } + + ctx.Data["Vote"] = vote + ctx.Data["IsEdit"] = true + ctx.Data["MaxVoteOptionLen"] = conf.Limits.VoteOptionLen // 选项输入框 maxlength 同源(vote-form.html JS) + ctx.Data["Title"] = "编辑投票" + // 草稿保存成功仅通过本次 URL 参数驱动统一 alert,不使用 session flash。 + if ctx.Query("saved") == "1" { + ctx.Data["Success"] = i18n.T(ctx.Lang(), "vote.flash.draftSaved") + ctx.Data["DraftSaved"] = true + } + // 发布后的投票锁定类型与选项/字段(避免破坏历史投票数据归因),仅可编辑元信息 + ctx.Data["LockedContent"] = vote.Status == db.VoteStatusPublished + + // 选项 / 表单字段回填:传结构化数据,模板经 toJSON(template.JS)注入 +
    +
  • + + + + diff --git a/templates/base/header.html b/templates/base/header.html new file mode 100644 index 0000000..b50b75f --- /dev/null +++ b/templates/base/header.html @@ -0,0 +1,1031 @@ + + + + + + {{ .Title }} + + + + + + + + + + + + + + + + + + {{ if .VConsole }} + + + {{ end }} + + + {{ if eq .CaptchaType "math" }} + + + {{ else if .RecaptchaTurnstileStyle }} + + + {{ else }} + + + {{ end }} + {{ if ne SentryDSN "" }} + + + {{ end }} + + + + + + + + + + + + + + + + + + + + + + + + + + + {{ if .NoIndex }}{{ end }} + {{ if .IsUserPage }} + + + + + + + + + {{ else }} + + + + + + + {{ end }} + + + + + + + + + + + + + + +
    + {{ if not .IsUserPage }} + + {{ end }} + +
    + + + +{{ if .IsPixel }} +
    +{{ else }} +
    +{{ end }} + +{{ if eq .CaptchaType "math" }} +
    +
    +

    {{t .LangCode "captcha.title"}}

    +

    {{t .LangCode "captcha.hint"}}

    +
    + {{t .LangCode "captcha.loading"}} + +
    +
    + +
    + +
    + + +
    +
    +
    + + + + +{{ end }} \ No newline at end of file diff --git a/templates/change-logs.html b/templates/change-logs.html new file mode 100644 index 0000000..57c3bac --- /dev/null +++ b/templates/change-logs.html @@ -0,0 +1,15 @@ +{{template "base/header" .}} +
    +

    修改记录

    +
    +

    为使首页更为简洁,今后修改的相关记录存档在此处(主要信息仍然会在首页提示)。

    +
    +
    +
    +
    +
    +
    +{{template "base/footer" .}} diff --git a/templates/chat/conversation.html b/templates/chat/conversation.html new file mode 100644 index 0000000..1d220e7 --- /dev/null +++ b/templates/chat/conversation.html @@ -0,0 +1,195 @@ +{{template "base/header" .}} + + +
    +

    + {{ if .IsOwner }}{{t .LangCode "chat.withAsker"}}{{ else }}{{t .LangCode "chat.withUser" .PageUser.Name}}{{ end }} +

    +

    + {{ if .Conversation.IsClosed }} + {{t .LangCode "chat.closed"}} + {{ else }} + {{t .LangCode "chat.remaining" (sub .Conversation.MaxMessages .Conversation.MessageCount) .Conversation.MaxMessages}} + {{ end }} +

    + +
    +
      + {{ range .Messages }} + {{ $isMyMessage := eq .SenderID $.LoggedUser.ID }} +
    • +
      +
      +
      + + + {{ if $isMyMessage }}{{t $.LangCode "chat.me"}}{{ else }}{{t $.LangCode "chat.other"}}{{ end }} + + + {{ .CreatedAt.Format "01-02 15:04" }} + +
      + {{ if and $.IsOwner $.IsBlocked (eq .SenderID $.Conversation.AskerID) }} +

      {{t $.LangCode "chat.userBlocked"}}

      + {{ else }} + {{ if .Content }} +

      {{ .Content }}

      + {{ end }} + {{ range (index $.MessageImages .ID) }} +
      + {{ .FileName }} +
      + {{ end }} + {{ end }} +
      +
      +
    • + {{ end }} +
    +
    + + {{ if .CanSend }} +
    +
    + {{ .CSRFTokenHTML }} + + +
    +
    + + {{t .LangCode "chat.addImage"}} + +
    + +
    + +
    + +
    +
    +
    + {{ else }} +
    +

    {{t .LangCode "chat.closedNoSend"}}

    + {{t .LangCode "common.backHome"}} +
    + {{ end }} + + {{ if .IsOwner }} +
    + + {{ if .IsBlocked }}{{t .LangCode "chat.unblock"}}{{ else }}{{t .LangCode "chat.block"}}{{ end }} + +
    +
    +

    {{ if .IsBlocked }}{{t .LangCode "chat.unblock"}}{{ else }}{{t .LangCode "chat.block"}}{{ end }}?

    +

    {{ if .IsBlocked }}{{t .LangCode "chat.confirmUnblock"}}{{ else }}{{t .LangCode "chat.confirmBlock"}}{{ end }}

    +
    + {{ .CSRFTokenHTML }} + +
    +
    +
    + + {{t .LangCode "chat.delete"}} +
    +
    +

    {{t .LangCode "qitem.danger"}}

    +

    {{t .LangCode "chat.deleteConfirm"}}

    +
    + {{ .CSRFTokenHTML }} + +
    +
    +
    +
    + {{ end }} + +
    + + +
    + × + +
    +
    + + + +{{template "base/footer" .}} \ No newline at end of file diff --git a/templates/embed.go b/templates/embed.go new file mode 100644 index 0000000..284f679 --- /dev/null +++ b/templates/embed.go @@ -0,0 +1,12 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package templates + +import ( + "embed" +) + +//go:embed auth base mail question user chat vote home.html about-me.html sponsor.html change-logs.html pixel.html maintenance-mode.html +var FS embed.FS diff --git a/templates/home.html b/templates/home.html new file mode 100644 index 0000000..a43f14f --- /dev/null +++ b/templates/home.html @@ -0,0 +1,123 @@ +{{template "base/header" .}} +
    +

    {{t .LangCode "site.title"}}

    +

    重大消息!本站已切换到box.shiroko.one,原域名将在2026年12月24日到期,期间将通过301转发指向新域名,到期后旧域名将彻底不在使用。
    问:为什么?答:.guru域名连续涨价,现在一年三百出头了遭不住。
    问:我该做什么?答:记住新域名,如果之前有通过二维码分享出去的,记得替换成新的二维码。


    +


    ⭐一个无需注册即可提问的匿名提问箱。你不需要下载App,不需要绑定社交账号,甚至连邮箱都不需要是真的。
    ⭐本站在原版的基础上新增了问题页面的二维码、私聊、投票、追加提问等功能以及更多自定义内容。各位用户可自行修改二维码背景图、颜色等个性化配置。
    ⭐可以到站长唯一提问提问箱链接小狼的提问箱尝试相关功能或给我提意见。
    ⭐可以加群:小狼的群一起水群。

    +

    近期将国内段访问交由EdgeOne接管,境外访问照旧由CloudFlare提供,经测试国内访问速度有所提升。但因EdgeOne Free套餐不提供CIDR列表,IP放行采取自动抓取手动维护模式,如果出现521错误请刷新一下页面,过几天应该就好了。

    +

    近期更新:
    ⭐2026.9 增加了提问、投票、私聊的总开关,可以设置定时收集、定量收集或关闭功能,顺便调整了前后端显示,看起来更易用了一些。
    ⭐2026.8 新增了投票功能、追加提问、多语言、Markdown显示、置顶显示等多个功能,详情见这里。
    ⭐2026.8 放弃使用recaptcha等对国内用户非常不友好的验证方式,更新了密码加密方式,修复了图片上传等一系列问题。
    ⭐2026.5 增加了私聊功能,可进行连续性对话,详见介绍;另有增加提问箱的卡片分享,更直观和美观。
    ⭐2026.2 新增了用户展示和标签功能,如果你希望陌生人给你提问,可以在设置页面给自己贴上5个标签并选择是否展示在探索页面:点我访问,详情见狼的公告板

    +

    一点提醒:
    ⭐本站唯一指定认证站长:小狼,注意不要被骗。 +
    ⭐本站不允许垃圾信息、广告、辱骂、涉政、暴恐、色情、违禁、无意义、灌水提问的出现,如有涉证或不良言论将直接删除。

    +
    +

    {{t .LangCode "site.stats"}}:

    {{if .SiteStats}}{{.SiteStats.Text}}{{end}}

    + + +
    + + {{template "base/footer" .}} \ No newline at end of file diff --git a/templates/mail/new-answer.html b/templates/mail/new-answer.html new file mode 100644 index 0000000..be78e5c --- /dev/null +++ b/templates/mail/new-answer.html @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + +
    +
    +
    +
    + 您在 狼的提问箱 的提问有了回复 +
    + + + + + + +
    +

    + {{.question}}

    +
    + + + + + + +
    +

    + {{.answer}}

    +
    +
    + +
    +
    +
    +
    + 我们向您发送这封邮件来告诉您在 狼的提问箱 的活动状态,若您未曾使用过 狼的提问箱,请忽略本邮件。 +
    +
    + {{ .year }} 狼的提问箱 +
    +
    +
    +
    +
    + + diff --git a/templates/mail/new-conversation.html b/templates/mail/new-conversation.html new file mode 100644 index 0000000..6e5449e --- /dev/null +++ b/templates/mail/new-conversation.html @@ -0,0 +1,15 @@ + + + + +

    您好!

    +

    您收到一个新的私聊对话,内容如下:

    +
    + {{.content}} +
    +

    点击下方链接查看并回复:

    +

    {{.link}}

    +
    +

    此邮件由系统自动发送,请勿回复。
    © {{.year}} 狼的提问箱

    + + \ No newline at end of file diff --git a/templates/mail/new-follow-up.html b/templates/mail/new-follow-up.html new file mode 100644 index 0000000..978d070 --- /dev/null +++ b/templates/mail/new-follow-up.html @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + +
    +
    +
    +
    + 您的提问有了一条追问 +
    + + + + + + +
    +

    + 原提问:{{.question}}

    +

    + 追问:{{.followup}}

    +
    +
    + +
    +
    +
    +
    + 我们向您发送这封邮件来告诉您账号的状态,若您未曾在 狼的提问箱 注册过账号,请忽略本邮件。 +
    +
    + {{ .year }} 狼的提问箱 +
    +
    +
    +
    +
    + + diff --git a/templates/mail/new-message.html b/templates/mail/new-message.html new file mode 100644 index 0000000..eaa8e2c --- /dev/null +++ b/templates/mail/new-message.html @@ -0,0 +1,15 @@ + + + + +

    您好!

    +

    您收到一条私聊新消息:

    +
    + {{.content}} +
    +

    点击下方链接查看对话:

    +

    {{.link}}

    +
    +

    此邮件由系统自动发送,请勿回复。
    © {{.year}} 狼的提问箱

    + + \ No newline at end of file diff --git a/templates/mail/new-question-to-user.html b/templates/mail/new-question-to-user.html new file mode 100644 index 0000000..66a7c88 --- /dev/null +++ b/templates/mail/new-question-to-user.html @@ -0,0 +1,109 @@ + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + +
    +
    +
    +
    + 您在 狼的提问箱 发送了一个提问 +
    + + + + + + +
    +

    {{.question}}

    +
    +
    + +
    +
    +
    +
    + 我们向您发送这封邮件来告诉您账号的状态,若您未曾在 狼的提问箱 进行过提问,请忽略本邮件。 +
    +
    + {{ .year }} 狼的提问箱 +
    +
    +
    +
    +
    + + diff --git a/templates/mail/new-question.html b/templates/mail/new-question.html new file mode 100644 index 0000000..8bef529 --- /dev/null +++ b/templates/mail/new-question.html @@ -0,0 +1,109 @@ + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + +
    +
    +
    +
    + 您的 狼的提问箱 收到一个新的提问 +
    + + + + + + +
    +

    {{.question}}

    +
    +
    + +
    +
    +
    +
    + 我们向您发送这封邮件来告诉您账号的状态,若您未曾在 狼的提问箱 注册过账号,请忽略本邮件。 +
    +
    + {{ .year }} 狼的提问箱 +
    +
    +
    +
    +
    + + diff --git a/templates/mail/new-vote.html b/templates/mail/new-vote.html new file mode 100644 index 0000000..10c3d62 --- /dev/null +++ b/templates/mail/new-vote.html @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + +
    +
    +
    +
    + 您的投票收到了新回复 +
    + + + + + + +
    +

    投票《{{.title}}》收到了一条新的表单回复,点击下方按钮查看。

    +
    +
    +
    + +
    + 提示:直接回复此邮件不能提交回答,请点击上方“查看回复”按钮完成操作。 +
    +
    +
    +
    +
    +
    +
    + 此邮件由系统自动发送,请勿直接回复。直接回复邮件不能实现回答,请通过邮件中的按钮访问页面。
    + 若您未曾在 狼的提问箱 创建过投票,请忽略本邮件。 +
    +
    + {{ .year }} 狼的提问箱 +
    +
    +
    +
    +
    + + diff --git a/templates/mail/password-recovery.html b/templates/mail/password-recovery.html new file mode 100644 index 0000000..ebb5235 --- /dev/null +++ b/templates/mail/password-recovery.html @@ -0,0 +1,109 @@ + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + +
    +
    +
    +
    + 您正在找回 狼的提问箱 注册账号的密码 +
    + + + + + + +
    + {{.email}} +
    +
    + +
    +
    +
    +
    + 我们向您发送这封邮件来告诉您账号的状态,若您未曾在 狼的提问箱 注册过账号,请忽略本邮件。 +
    +
    + {{ .year }} 狼的提问箱 +
    +
    +
    +
    +
    + + diff --git a/templates/mail/security-alert.html b/templates/mail/security-alert.html new file mode 100644 index 0000000..c185711 --- /dev/null +++ b/templates/mail/security-alert.html @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + +
    +
    +
    +
    + 检测到疑似批量扫描 +
    +
    + {{.time}} +
    +
    +
    +
    +
    来源 IP:{{.ip}}
    +
    网络归属:{{.provider}}
    +
    处置:已自动临时封禁 {{.duration}} 分钟,到期自动解除
    + {{if .proxy_hint}} +
    ⚠️ 该 IP 属于 CDN / 代理网络,攻击者可随时更换出口 IP,本次封禁可能无法拦截真实来源。
    + {{end}} +
    +
    命中路径样本:
    +
    + {{.paths}} +
    +
    + 该 IP 在统计窗口内频繁访问后台/敏感路径或产生大量 404,已自动加入临时封禁名单。如属误报,请检查服务器访问日志确认。 +
    +
    +
    +
    +
    +
    + 此邮件由系统自动发送,请勿直接回复。
    + {{ .year }} 狼的提问箱 +
    +
    +
    +
    +
    + + diff --git a/templates/maintenance-mode.html b/templates/maintenance-mode.html new file mode 100644 index 0000000..0de4842 --- /dev/null +++ b/templates/maintenance-mode.html @@ -0,0 +1,8 @@ +{{template "base/header" .}} +
    +

    {{t .LangCode "maintenance.title"}}

    +
    +

    {{t .LangCode "maintenance.desc"}}

    +
    +
    +{{template "base/footer" .}} \ No newline at end of file diff --git a/templates/percent_check_test.go b/templates/percent_check_test.go new file mode 100644 index 0000000..ec42fff --- /dev/null +++ b/templates/percent_check_test.go @@ -0,0 +1,148 @@ +package templates + +import ( + "bytes" + gotemplate "html/template" + "testing" + "time" + + "github.com/flamego/template" + + "github.com/tamakyi/TamaBox/internal/db" + "github.com/tamakyi/TamaBox/internal/dbutil" + templatepkg "github.com/tamakyi/TamaBox/internal/template" +) + +// TestPercentRender 渲染投票结果页并检查百分比与进度条是否真实输出。 +func TestPercentRender(t *testing.T) { + fs, err := template.EmbedFS(FS, ".", []string{".html"}) + if err != nil { + t.Fatalf("EmbedFS: %v", err) + } + tpl := gotemplate.New("Flamego.Template") + for _, f := range fs.Files() { + tt := tpl.New(f.Name()) + for _, funcMap := range templatepkg.FuncMap() { + tt.Funcs(funcMap) + } + dataBytes, err := f.Data() + if err != nil { + t.Fatalf("get data of %q: %v", f.Name(), err) + } + if _, err := tt.Parse(string(dataBytes)); err != nil { + t.Fatalf("parse %q: %v", f.Name(), err) + } + } + + data := map[string]interface{}{ + "LangCode": "zh-CN", + "IsUserPage": true, + "Vote": &db.Vote{Model: dbutil.Model{ID: 1}, Title: "表单结果", Type: db.VoteTypeForm}, + "Total": int64(1), + "HasTextFields": true, + "FormFields": []*db.VoteFormField{ + {Label: "满意度", FieldType: db.VoteFormFieldTypeRadio, Options: `["满意","一般"]`}, + }, + "Results": map[string]interface{}{ + "Type": "form", "FormCount": int64(1), "FormFieldStats": []interface{}{ + map[string]interface{}{ + "Field": map[string]interface{}{"Label": "满意度", "FieldType": "radio"}, + "Total": int64(3), + "OptionStats": []interface{}{ + map[string]interface{}{"Option": map[string]interface{}{"Content": "满意"}, "Count": int64(2)}, + map[string]interface{}{"Option": map[string]interface{}{"Content": "一般"}, "Count": int64(1)}, + }, + }, + }, + }, + "Submissions": []interface{}{ + map[string]interface{}{"CreatedAt": time.Now(), "Fields": map[string]interface{}{"满意度": "满意"}}, + }, + "CSRFTokenHTML": gotemplate.HTML(""), + } + + var buf bytes.Buffer + if err := tpl.ExecuteTemplate(&buf, "user/vote-results", data); err != nil { + t.Fatalf("execute: %v", err) + } + html := buf.String() + + // 2/3 取整 = 66%,1/3 取整 = 33%;进度条宽度同步渲染 + for _, want := range []string{"(66%)", "(33%)", "width: 66%", "width: 33%", "uk-progressbar"} { + if !bytes.Contains([]byte(html), []byte(want)) { + t.Errorf("HTML missing %q", want) + } + } +} + +// TestInlineTextRepliesRender 验证表单结果页:文本类字段的逐条提交内容内联在题目 +// 下方、默认收起(含 hidden 属性),点击"查看文本提交(N)"展开。 +func TestInlineTextRepliesRender(t *testing.T) { + fs, err := template.EmbedFS(FS, ".", []string{".html"}) + if err != nil { + t.Fatalf("EmbedFS: %v", err) + } + tpl := gotemplate.New("Flamego.Template") + for _, f := range fs.Files() { + tt := tpl.New(f.Name()) + for _, funcMap := range templatepkg.FuncMap() { + tt.Funcs(funcMap) + } + dataBytes, err := f.Data() + if err != nil { + t.Fatalf("get data of %q: %v", f.Name(), err) + } + if _, err := tt.Parse(string(dataBytes)); err != nil { + t.Fatalf("parse %q: %v", f.Name(), err) + } + } + + data := map[string]interface{}{ + "LangCode": "zh-CN", + "IsUserPage": true, + "Vote": &db.Vote{Model: dbutil.Model{ID: 1}, Title: "表单结果", Type: db.VoteTypeForm}, + "Total": int64(1), + "FormFields": []*db.VoteFormField{ + {Model: dbutil.Model{ID: 10}, Label: "建议", FieldType: db.VoteFormFieldTypeTextarea}, + }, + "Results": map[string]interface{}{ + "Type": "form", "FormCount": int64(1), "FormFieldStats": []interface{}{ + map[string]interface{}{ + "Field": map[string]interface{}{"ID": int64(10), "Label": "建议", "FieldType": "textarea"}, + "Total": int64(2), + "TextCount": int64(2), + }, + }, + }, + "TextReplies": map[string]interface{}{ + "建议": []interface{}{ + map[string]interface{}{"CreatedAt": time.Now(), "Text": "希望增加夜间模式"}, + map[string]interface{}{"CreatedAt": time.Now(), "Text": "页面很清爽"}, + }, + }, + "CSRFTokenHTML": gotemplate.HTML(""), + } + + var buf bytes.Buffer + if err := tpl.ExecuteTemplate(&buf, "user/vote-results", data); err != nil { + t.Fatalf("execute: %v", err) + } + html := buf.String() + + // 内联折叠入口 + 两则文本均存在 + 默认收起(hidden) + for _, want := range []string{ + "查看文本提交(2)", + "希望增加夜间模式", + "页面很清爽", + `id="replies-10"`, + `id="caret-10"`, + } { + if !bytes.Contains([]byte(html), []byte(want)) { + t.Errorf("HTML missing %q", want) + } + } + // 折叠内容默认 hidden,不随页面始终铺在底部 + if !bytes.Contains([]byte(html), []byte(`id="replies-10" hidden`)) { + t.Errorf("inline text replies should be hidden by default") + } +} diff --git a/templates/pixel.html b/templates/pixel.html new file mode 100644 index 0000000..03575c9 --- /dev/null +++ b/templates/pixel.html @@ -0,0 +1,19 @@ +{{template "base/header" .}} + +
    +

    + 请各位用户知悉并确认在使用画板功能时,不会发起及/或参与以下内容: + 1. 涉及地域、种族、性别、宗教、政治等方面的歧视性内容; + 2. 侮辱、诽谤他人,侵害他人合法权益的内容; + 3. 含有淫秽色情、血腥暴力、赌博的内容; + 4. 其他在法律法规中禁止的或不适宜的内容。 + 如果您实施了违反上述规范的行为,我们将视情况采取相关措施,并保留移交司法机关或者行政机关的权利。 +

    +
    + +
    + + +{{template "base/footer" .}} \ No newline at end of file diff --git a/templates/question/history-template.html b/templates/question/history-template.html new file mode 100644 index 0000000..ee27070 --- /dev/null +++ b/templates/question/history-template.html @@ -0,0 +1,83 @@ +{{$pinTitle := t .LangCode "ask.pinned"}} +
    + {{range $index, $elem := .PageQuestions}} +
    +
    + 查看回答 +
    + {{if $elem.IsPinned}}⭐{{end}} + {{Date $elem.CreatedAt "Y-m-d H:i:s"}} +
    +

    {{MarkdownPlainText $elem.Content}}

    +
    + {{end}} +
    + + +
    + +
    +
    + 无更多留言 +

    +
    +
    diff --git a/templates/question/item.html b/templates/question/item.html new file mode 100644 index 0000000..54d5591 --- /dev/null +++ b/templates/question/item.html @@ -0,0 +1,425 @@ +{{template "base/header" .}} + + + + +
    +
    +
    +
    {{Date .Question.CreatedAt "Y-m-d H:i:s"}}
    +
    {{MarkdownFormat .Question.Content}}
    + {{ if .AskUploadImages }} +
      + {{ range $index, $elem := .AskUploadImages }} +
      + + + +
      + {{ end }} +
    + {{ end }} +
    + + {{if ne .Question.Answer ""}} +
    + +
    +
    {{MarkdownFormat .Question.Answer}}
    + {{ if .AnswerUploadImages }} +
      + {{ range $index, $elem := .AnswerUploadImages }} +
      + + + +
      + {{ end }} +
    + {{ end }} +
    +

    {{t .LangCode "qitem.answeredBy" .PageUser.Name (Date .Question.UpdatedAt "Y-m-d H:i:s")}}

    + +
    + {{ if and (not .Question.IsPrivate) (ne .Question.Answer "") }} + 📤 {{t .LangCode "qitem.shareCard"}} + {{ end }} + {{ if .CanDelete }} +
    + +
    + {{ end }} +
    + {{ if not .CanDelete }} +
    + + {{ end }} + {{ if .CanDelete }} + + {{ end }} +
    + {{ else if .CanDelete }} +
    +
    +
    {{t .LangCode "qitem.answerTitle"}}
    +
    + {{ .CSRFTokenHTML }} +
    + +
    +
    + + + +
    + +
    +
    + {{ if ne .Question.ReceiveReplyEmail "" }} +
    +

    {{t .LangCode "qitem.emailNotifyHint"}}

    +
    + {{ end }} +
    + +
    + +
    + {{ if .Question.IsRead }} + ✓ {{t .LangCode "qlist.read"}} +
    + {{ .CSRFTokenHTML }} + +
    + {{ else }} +
    + {{ .CSRFTokenHTML }} + +
    + {{ end }} +
    +
    +
    + {{ end }} + + + {{ if and .CanDelete (ne .Question.Answer "") }} +
    +
    + ✓ {{t .LangCode "qlist.read"}} + {{t .LangCode "qitem.readLocked"}} +
    +
    + {{ end }} + + {{ if .FollowUps }} +
    + {{ range $index, $elem := .FollowUps }} +
    +

    {{t $.LangCode "followup.content"}}{{ $elem.Content }}

    + {{ if ne $elem.Answer "" }} + {{ if $.CanDelete }} +
    @{{ $.PageUser.Name }}:{{ MarkdownFormat $elem.Answer }}
    +
    + +
    + + {{ else }} +
    @{{ $.PageUser.Name }}:{{ MarkdownFormat $elem.Answer }}
    + {{ end }} + {{ else if $.CanDelete }} +
    + {{ $.CSRFTokenHTML }} + +
    + +
    +
    + {{ else }} +

    {{t $.LangCode "followup.waiting"}}

    + {{ end }} +
    + {{ end }} +
    + {{ end }} + + {{ if and .CanFollowUp (not .CanDelete) }} +
    +
    +
    {{t .LangCode "followup.askMore"}}
    +

    {{t .LangCode "followup.remaining" .FollowUpRemaining .FollowUpLimit}}

    +
    + {{ .CSRFTokenHTML }} + + +
    + +
    +
    +
    +
    + {{ end }} + + {{ if and .WaitingFollowUpReply (not .CanDelete) }} +
    +
    {{t .LangCode "followup.waitingReply"}}
    +
    + {{ end }} + + +
    +
    + +{{template "base/footer" .}} diff --git a/templates/question/list.html b/templates/question/list.html new file mode 100644 index 0000000..2934952 --- /dev/null +++ b/templates/question/list.html @@ -0,0 +1,310 @@ +{{template "base/header" .}} + + + + + +
    +
    +
    + +

    {{ .PageUser.Name }}

    +

    {{ .PageUser.Intro }}

    +
    + {{ if and .PageUser.Acfunlink (ne .PageUser.Acfunlink "none") }} + + acfunlink + + {{ end }} + {{ if and .PageUser.Bililink (ne .PageUser.Bililink "none") }} + + bililink + + {{ end }} + {{ if and .PageUser.Weibolink (ne .PageUser.Weibolink "none") }} + + weibolink + + {{ end }} + {{ if and .PageUser.Xiaohongshulink (ne .PageUser.Xiaohongshulink "none") }} + + xiaohongshulink + + {{ end }} + {{ if and .PageUser.Bloglink (ne .PageUser.Bloglink "none") }} + + bloglink + + {{ end }} +
    +
    +
    +
    + +
    +
    + {{ if .CanAsk }} + + + +
    + + +

    {{t .LangCode "ask.scan" .PageUser.Name}}
    {{ if .RegisterOnlyAsk }}{{t .LangCode "ask.registerOnly"}}{{ else }}{{t .LangCode "ask.anonymous"}}{{ end }}

    + + + + + + + {{ end }} + {{template "base/alert" .}} + + +
    + + {{ if .VoteEnabled }} + + {{ else }} + + + {{ end }} +
    + +
    + {{template "question/new-question-template" .}} + + {{ if ne (len .PageQuestions) 0 }} +

    {{t .LangCode "ask.history" .PageUser.Name}} ({{ .AnsweredCount }})

    + {{ template "question/history-template" . }} + {{ end }} +
    + + +
    +
    + +{{template "base/footer" .}} \ No newline at end of file diff --git a/templates/question/new-question-template.html b/templates/question/new-question-template.html new file mode 100644 index 0000000..ab70a6f --- /dev/null +++ b/templates/question/new-question-template.html @@ -0,0 +1,232 @@ +{{ if .AskClosedMessage }} +
    +
    +

    {{ .AskClosedMessage }}

    + {{ if .AskNextOpenAtStr }} +

    {{t .LangCode "ask.nextOpenAt" .AskNextOpenAtStr}}

    + {{ end }} + {{ if .AskLastCloseAtStr }} +

    {{t .LangCode "ask.lastCloseAt" .AskLastCloseAtStr}}

    + {{ end }} +
    + + + {{ if .AllowChat }} +
    + {{ if .LoggedUser }} +
    + {{ .CSRFTokenHTML }} + {{ if .PageUser.AskPassword }} + + {{ end }} + + +
    + +
    +
    + {{ if eq .CaptchaType "math" }} + + {{ else }} + + {{ end }} +
    {{t .LangCode "ask.chatLimit" .PageUser.ChatMaxMessages}}
    +
    +
    + {{ else }} + +
    +

    {{t .LangCode "ask.loginRequiredChat"}}

    + {{t .LangCode "ask.goLogin"}} +
    + {{ end }} +
    + {{ end }} + + {{ if and .AllowChat .LoggedUser }} + {{ if ne .CaptchaType "math" }} + + + {{ end }} + {{ end }} +
    +{{ else if not .CanAsk }} +
    +
    +

    {{t .LangCode "ask.needLogin"}}

    +
    + +
    +{{ else }} +
    + {{ .CSRFTokenHTML }} + + {{if .PageUser.AskPassword}} + + {{end}} + + + + +
    + +
    +
    + + + +
    + +
    +
    + +
    + + + +
    + +
    +
    +
    + {{ if eq .CaptchaType "math" }} + + {{ else }} + + {{ end }} +
    + {{ if not .AllowChat }} +
    + +
    + {{ else if .LoggedUser }} +
    + +
    {{t .LangCode "ask.chatLimit" .PageUser.ChatMaxMessages}}
    +
    + {{ else }} +
    + +
    + {{ end }} +
    +
    +
    + + +{{ end }} diff --git a/templates/question/new-question-template.html.bak b/templates/question/new-question-template.html.bak new file mode 100644 index 0000000..f1ad848 --- /dev/null +++ b/templates/question/new-question-template.html.bak @@ -0,0 +1,145 @@ +{{ if not .CanAsk }} +
    +
    +

    提问箱的主人设置了仅注册用户才能提问,你需要先登录才能向他提问。

    +
    + +
    +{{ else }} +
    + {{ .CSRFTokenHTML }} + + {{if .PageUser.AskPassword}} + + {{end}} + + + +
    + +
    +
    + + + +
    + +
    +
    + +
    + + + +
    + +
    +
    +
    + +
    + {{ if and .LoggedUser .PageUser.AllowChat }} +
    + +
    消息上限:{{.PageUser.ChatMaxMessages}}条
    +
    + {{ else if not .LoggedUser }} +
    + +
    + {{ else }} +
    + +
    + {{ end }} +
    +
    +
    + + +{{ end }} \ No newline at end of file diff --git a/templates/question/password.html b/templates/question/password.html new file mode 100644 index 0000000..92f8f2b --- /dev/null +++ b/templates/question/password.html @@ -0,0 +1,62 @@ +{{template "base/header" .}} + + + + + + + +
    +
    +
    + +
    +

    {{ .PageUser.Name }}{{t .LangCode "site.logoSuffix"}}

    +

    {{t .LangCode "password.desc"}}

    + + {{template "base/alert" .}} + +
    + {{ .CSRFTokenHTML }} + +
    +
    + + +
    +
    +
    + +
    +
    + + +
    +
    + +{{template "base/footer" .}} \ No newline at end of file diff --git a/templates/question/question-not-found.html b/templates/question/question-not-found.html new file mode 100644 index 0000000..beec2fc --- /dev/null +++ b/templates/question/question-not-found.html @@ -0,0 +1,106 @@ +{{template "base/header" .}} + + + + + +
    +
    +
    + +

    {{ .PageUser.Name }}

    +

    {{ .PageUser.Intro }}

    +
    + {{ if and .PageUser.Acfunlink (ne .PageUser.Acfunlink "none") }} + + acfunlink + + {{ end }} + {{ if and .PageUser.Bililink (ne .PageUser.Bililink "none") }} + + bililink + + {{ end }} + {{ if and .PageUser.Weibolink (ne .PageUser.Weibolink "none") }} + + weibolink + + {{ end }} + {{ if and .PageUser.Xiaohongshulink (ne .PageUser.Xiaohongshulink "none") }} + + xiaohongshulink + + {{ end }} + {{ if and .PageUser.Bloglink (ne .PageUser.Bloglink "none") }} + + bloglink + + {{ end }} +
    +
    +
    +
    + +
    +
    + {{ if .CanAsk }} + + + +
    + + +

    扫码向@{{ .PageUser.Name }}提问
    {{ if .RegisterOnlyAsk }}{{t .LangCode "ask.registerOnly"}}{{ else }}{{t .LangCode "ask.anonymous"}}{{ end }}

    + {{ end }} + {{template "base/alert" .}} + {{template "question/new-question-template" .}} + +
    + {{ if ne (len .PageQuestions) 0 }} +

    @{{ .PageUser.Name }} 以前回答过的问题 ({{ .AnsweredCount }})

    + {{ template "question/history-template" . }} + {{ end }} +
    +
    +{{template "base/footer" .}} \ No newline at end of file diff --git a/templates/question/success.html b/templates/question/success.html new file mode 100644 index 0000000..ae3a840 --- /dev/null +++ b/templates/question/success.html @@ -0,0 +1,54 @@ +{{template "base/header" .}} +
    +
    + +

    {{t .LangCode "success.title"}}

    +
    + +

    {{t .LangCode "success.yourQuestion"}}

    +
    {{MarkdownFormat .Question.Content}}
    + + {{ if .HasReceiveEmail }} +
    +

    {{t .LangCode "success.emailSent"}}

    +
    + {{ else }} +
    +

    {{t .LangCode "success.saveLink" | safe}}

    +
    + {{ end }} + +
    + +
    + + +
    +

    {{t .LangCode "success.token" .Question.Token}}

    +
    + + +
    + + +{{template "base/footer" .}} diff --git a/templates/render_public_test.go b/templates/render_public_test.go new file mode 100644 index 0000000..12eb2b8 --- /dev/null +++ b/templates/render_public_test.go @@ -0,0 +1,271 @@ +package templates + +import ( + gotemplate "html/template" + "strings" + "testing" + "time" + + "github.com/tamakyi/TamaBox/internal/conf" +) + +type mockPageQuestion struct { + ID uint + Content string + CreatedAt time.Time + IsPinned bool + Answer string +} + +func publicBaseData() map[string]interface{} { + pageUser := map[string]interface{}{ + "Domain": "tester", "Name": "测试箱主", "Avatar": "", "Background": "", + "Intro": "欢迎提问", "Usernamecolor": "#000", "Introcolor": "#666", + "Acfunlink": "none", "Bililink": "none", "Weibolink": "none", + "Xiaohongshulink": "none", "Bloglink": "none", + "Qrcodebackcolor": "#fff", "Qrcodecolor": "#000", "Dotscale": "0.35", + "BackgroundImage": "", "Backgroundimagealpha": "0.8", "Qrcodepdpcolor": "#000", + "HarassmentSetting": "disabled", "AllowChat": true, "ChatMaxMessages": 10, + } + return map[string]interface{}{ + "LangCode": "zh-CN", + "SupportedLangs": []map[string]string{{"Code": "zh-CN", "Name": "简体中文"}}, + "IsLogged": false, + "IsUserPage": true, + "IsOwnPage": false, + "IsPixel": false, + "VConsole": false, + "CSRFTokenHTML": gotemplate.HTML(``), + "RecaptchaSiteKey": "", + "CaptchaType": "recaptcha", + "PageUser": pageUser, + "PageUserRaw": pageUser, + "PageQuestions": []mockPageQuestion{ + {ID: 1, Content: "置顶的问题", CreatedAt: time.Now(), IsPinned: true, Answer: "答1"}, + {ID: 2, Content: "普通问题", CreatedAt: time.Now().Add(-time.Hour), IsPinned: false, Answer: "答2"}, + }, + "PageQuestionCursor": "2", + "CanAsk": true, + "AnsweredCount": 2, + "ICP": "", + // [limits] 全站上限(生产由 Contexter 全局注入 conf.Limits),供提问/回答/追问 + // 输入框 maxlength 与私聊发起框同源 + "Limits": conf.Limits, + } +} + +// TestRenderPublicQuestionList 渲染提问箱主页(含置顶条目),复现公开页 500。 +func TestRenderPublicQuestionList(t *testing.T) { + if err := renderWithData(t, "question/list", publicBaseData()); err != nil { + t.Fatalf("render question/list failed: %v", err) + } +} + +// TestRenderQuestionListClosed 提问功能关闭时:展示关闭原因 + 下次开放/上次关闭时间(问题 3 的模板路径)。 +func TestRenderQuestionListClosed(t *testing.T) { + base := publicBaseData() + base["CanAsk"] = false + base["AskState"] = map[string]interface{}{"Open": false, "Reason": "not_started"} + base["AskClosedMessage"] = "提问功能尚未开放" + base["AskNextOpenAtStr"] = "2026-09-02 10:00" + base["AskLastCloseAtStr"] = "2026-09-01 18:00" + + out, err := renderToString(t, "question/list", base) + if err != nil { + t.Fatalf("render question/list (closed) failed: %v", err) + } + if !strings.Contains(out, "提问功能尚未开放") { + t.Fatal("closed reason not rendered") + } + if !strings.Contains(out, "下次开放时间:2026-09-02 10:00") { + t.Fatal("next open time not rendered") + } + if !strings.Contains(out, "上次关闭时间:2026-09-01 18:00") { + t.Fatal("last close time not rendered") + } +} + +// TestRenderQuestionListClosedPermanent 一次性窗口结束后(无循环定时):只展示上次关闭时间,不展示下次开放。 +func TestRenderQuestionListClosedPermanent(t *testing.T) { + base := publicBaseData() + base["CanAsk"] = false + base["AskState"] = map[string]interface{}{"Open": false, "Reason": "ended"} + base["AskClosedMessage"] = "提问功能已结束收集" + base["AskNextOpenAtStr"] = "" + base["AskLastCloseAtStr"] = "2026-08-31 18:00" + + out, err := renderToString(t, "question/list", base) + if err != nil { + t.Fatalf("render question/list (ended) failed: %v", err) + } + if strings.Contains(out, "下次开放时间") { + t.Fatal("next open time should NOT be rendered when permanently closed") + } + if !strings.Contains(out, "上次关闭时间:2026-08-31 18:00") { + t.Fatal("last close time not rendered") + } +} + +// TestRenderQuestionListRegisterOnlyCaption 未开启「仅允许注册用户」时,二维码文案保持原样。 +func TestRenderQuestionListRegisterOnlyCaption(t *testing.T) { + base := publicBaseData() + base["RegisterOnlyAsk"] = false + out, err := renderToString(t, "question/list", base) + if err != nil { + t.Fatalf("render question/list failed: %v", err) + } + if !strings.Contains(out, "谁都可以以匿名的形式提问") { + t.Fatal("anonymous caption should be rendered when not register-only") + } + if strings.Contains(out, "仅允许注册用户向TA提问") { + t.Fatal("register-only caption should NOT be rendered when not register-only") + } +} + +// TestRenderQuestionListRegisterOnlyOn 开启「仅允许注册用户」(箱主登录态可提问)时,二维码文案联动(问题 2)。 +func TestRenderQuestionListRegisterOnlyOn(t *testing.T) { + base := publicBaseData() + base["CanAsk"] = true + base["RegisterOnlyAsk"] = true + out, err := renderToString(t, "question/list", base) + if err != nil { + t.Fatalf("render question/list failed: %v", err) + } + if !strings.Contains(out, "仅允许注册用户向TA提问") { + t.Fatal("register-only caption should be rendered when register-only enabled") + } + if strings.Contains(out, "谁都可以以匿名的形式提问") { + t.Fatal("anonymous caption should NOT be rendered when register-only enabled") + } +} + +// TestRenderQuestionListVoteDisabled 投票功能关闭时:投票 Tab 保留显示但置灰禁用,并带原因 tooltip。 +func TestRenderQuestionListVoteDisabled(t *testing.T) { + base := publicBaseData() + base["VoteEnabled"] = false + base["VoteClosedMessage"] = "该提问箱已关闭投票功能" + out, err := renderToString(t, "question/list", base) + if err != nil { + t.Fatalf("render question/list (vote disabled) failed: %v", err) + } + if !strings.Contains(out, "profile-tab is-disabled") { + t.Fatal("vote tab should stay visible but disabled") + } + if !strings.Contains(out, "disabled") { + t.Fatal("vote tab should carry disabled attribute") + } + if !strings.Contains(out, "该提问箱已关闭投票功能") { + t.Fatal("vote tab should carry the close reason tooltip") + } + // 注意:JS 守卫代码里也有 [data-profile-tab="votes"] 选择器,须按按钮元素精确断言 + if strings.Contains(out, `data-profile-tab="votes" role="tab"`) { + t.Fatal("disabled vote tab must NOT be switchable") + } +} + +// TestRenderQuestionListVoteEnabled 投票功能正常时:投票 Tab 可点击切换。 +func TestRenderQuestionListVoteEnabled(t *testing.T) { + base := publicBaseData() + base["VoteEnabled"] = true + out, err := renderToString(t, "question/list", base) + if err != nil { + t.Fatalf("render question/list (vote enabled) failed: %v", err) + } + if !strings.Contains(out, `data-profile-tab="votes"`) { + t.Fatal("vote tab should be switchable when enabled") + } + if strings.Contains(out, "profile-tab is-disabled") { + t.Fatal("vote tab must not be disabled when enabled") + } +} + +// TestRenderQuestionListChatOnly 提问功能关闭但私聊开启时:保留独立私聊入口(含已登录/未登录两种形态)。 +func TestRenderQuestionListChatOnly(t *testing.T) { + base := publicBaseData() + base["CanAsk"] = false + base["AskState"] = map[string]interface{}{"Open": false, "Reason": "disabled"} + base["AskClosedMessage"] = "提问箱主人已关闭提问功能" + base["AskNextOpenAtStr"] = "" + base["AskLastCloseAtStr"] = "" + base["AllowChat"] = true + base["ChatMaxMessages"] = 20 + base["LoggedUser"] = map[string]interface{}{"Domain": "tester", "Name": "测试箱主"} + + // 已登录:渲染独立私聊表单 + out, err := renderToString(t, "question/list", base) + if err != nil { + t.Fatalf("render question/list (chat only, logged in) failed: %v", err) + } + if !strings.Contains(out, "提问箱主人已关闭提问功能") { + t.Fatal("ask closed reason should still be shown") + } + if !strings.Contains(out, `id="chat-only-form"`) { + t.Fatal("chat-only form should be rendered when chat enabled and logged in") + } + if !strings.Contains(out, `id="chat-only-form" enctype="multipart/form-data"`) { + t.Fatal("chat-only form must be multipart, otherwise form.Bind panics on the Images field") + } + if !strings.Contains(out, `name="start_chat_val" value="true"`) { + t.Fatal("chat-only form must submit as a chat request") + } + if !strings.Contains(out, "在此处撰写你的私聊消息...") { + t.Fatal("chat placeholder should be rendered") + } + if !strings.Contains(out, "onChatOnlySubmit") { + t.Fatal("chat-only captcha callback should be defined for non-math captcha") + } + + // 未登录:渲染登录引导而非表单 + base["LoggedUser"] = nil + out, err = renderToString(t, "question/list", base) + if err != nil { + t.Fatalf("render question/list (chat only, anonymous) failed: %v", err) + } + if strings.Contains(out, `id="chat-only-form"`) { + t.Fatal("chat-only form must not be rendered for anonymous visitors") + } + if !strings.Contains(out, "/login?to=") { + t.Fatal("anonymous visitors should get a login link to start chats") + } +} + +// TestRenderQuestionListChatOnlyNoChat 提问关闭且私聊也关闭:不渲染私聊入口。 +func TestRenderQuestionListChatOnlyNoChat(t *testing.T) { + base := publicBaseData() + base["CanAsk"] = false + base["AskClosedMessage"] = "提问箱主人已关闭提问功能" + base["AllowChat"] = false + base["LoggedUser"] = map[string]interface{}{"Domain": "tester", "Name": "测试箱主"} + out, err := renderToString(t, "question/list", base) + if err != nil { + t.Fatalf("render question/list (all closed) failed: %v", err) + } + if strings.Contains(out, `id="chat-only-form"`) { + t.Fatal("chat-only form must not be rendered when chat is disabled") + } +} + +// TestRenderPublicQuestionItem 渲染单题页(含历史列表),复现公开页 500。 +func TestRenderPublicQuestionItem(t *testing.T) { + data := publicBaseData() + data["Question"] = map[string]interface{}{ + "ID": 1, "Content": "置顶的问题", "Answer": "答1", "CreatedAt": time.Now(), + "UpdatedAt": time.Now(), "IsPrivate": false, "IsPinned": true, + "Token": "abc123", "ReceiveReplyEmail": "", + } + data["QuestionToken"] = "abc123" + data["AskUploadImages"] = []interface{}{} + data["AnswerUploadImages"] = []interface{}{} + data["FollowUps"] = []interface{}{} + data["CanFollowUp"] = false + data["FollowUpRemaining"] = 0 + data["FollowUpLimit"] = 3 + data["IsOwnPage"] = true + data["IsQuestioner"] = false + data["IsBlocked"] = false + data["AllowChat"] = true + + if err := renderWithData(t, "question/item", data); err != nil { + t.Fatalf("render question/item failed: %v", err) + } +} diff --git a/templates/render_test.go b/templates/render_test.go new file mode 100644 index 0000000..a7ddb8f --- /dev/null +++ b/templates/render_test.go @@ -0,0 +1,313 @@ +package templates + +import ( + "bytes" + "fmt" + gotemplate "html/template" + "strings" + "testing" + "time" + + "github.com/flamego/template" + + "github.com/tamakyi/TamaBox/internal/conf" + "github.com/tamakyi/TamaBox/internal/db" + templatepkg "github.com/tamakyi/TamaBox/internal/template" +) + +// renderWithData 用给定数据渲染模板(复刻生产环境 Templater + FuncMap)。 +func renderWithData(t *testing.T, name string, data map[string]interface{}) error { + t.Helper() + _, err := renderToString(t, name, data) + return err +} + +// renderToString 渲染模板并返回输出,供需要断言渲染结果的用例使用。 +func renderToString(t *testing.T, name string, data map[string]interface{}) (string, error) { + t.Helper() + fs, err := template.EmbedFS(FS, ".", []string{".html"}) + if err != nil { + t.Fatalf("EmbedFS: %v", err) + } + + tpl := gotemplate.New("Flamego.Template") + for _, f := range fs.Files() { + tt := tpl.New(f.Name()) + for _, funcMap := range templatepkg.FuncMap() { + tt.Funcs(funcMap) + } + dataBytes, err := f.Data() + if err != nil { + t.Fatalf("get data of %q: %v", f.Name(), err) + } + if _, err := tt.Parse(string(dataBytes)); err != nil { + t.Fatalf("parse %q: %v", f.Name(), err) + } + } + + var buf bytes.Buffer + if err := tpl.ExecuteTemplate(&buf, name, data); err != nil { + return "", err + } + return buf.String(), nil +} + +// mockLoggedUser 覆盖 templates/user/profile.html 引用到的 LoggedUser 字段。 +type mockLoggedUser struct { + Domain string + Name string + Email string + Avatar string + Background string + BackgroundImage string + Backgroundimagealpha string + Intro string + Introcolor string + Usernamecolor string + Qrcodebackcolor string + Qrcodecolor string + Qrcodepdpcolor string + Dotscale string + UseCustomQRColor bool + Notify string + Language string + HarassmentSetting string + BlockWords string + Tags string + ShowInHome bool + Acfunlink string + Bililink string + Weibolink string + Xiaohongshulink string + Bloglink string + ChatMaxMessages int + DailyMessageLimit int +} + +// profileBaseData 构造 /user/profile 渲染所需的基础数据。 +func profileBaseData() map[string]interface{} { + return map[string]interface{}{ + "Title": "设置", + "LangCode": "zh-CN", + "SupportedLangs": []map[string]string{{"Code": "zh-CN", "Name": "简体中文"}}, + "IsLogged": true, + "LoggedUser": &mockLoggedUser{ + Domain: "tester", Name: "测试箱主", Email: "t@example.com", + Usernamecolor: "#000", Introcolor: "#666", Qrcodecolor: "#000", + Qrcodepdpcolor: "#000", Qrcodebackcolor: "#fff", Dotscale: "0.35", + Backgroundimagealpha: "0.8", Notify: "email", Language: "zh-CN", + HarassmentSetting: "none", BlockWords: "广告,spam", Tags: "杂谈", + ChatMaxMessages: 20, DailyMessageLimit: 0, + }, + "CSRFTokenHTML": gotemplate.HTML(``), + "IsUserPage": false, + "IsPixel": false, + "VConsole": false, + "HasPagePassword": false, + "HasAskPassword": true, + "ActiveProfileTab": "account", + "ICP": "", + // 标签 / 屏蔽词上限,供标签块输入组件做实时提示(生产由 route/user.Profile 注入, + // 值来自 conf.Limits) + "TagLimits": map[string]int{ + "MaxTags": conf.Limits.MaxTags, + "MaxTagLen": conf.Limits.MaxTagLen, + "MaxBlockWords": conf.Limits.MaxBlockWords, + "MaxBlockWordLen": conf.Limits.MaxBlockWordLen, + }, + // 私聊面板数值上下界(同样来自 conf.Limits) + "ChatLimits": map[string]int{ + "MaxChatMessages": conf.Limits.ChatMaxMessages, + "DailyMessageLimitMax": conf.Limits.DailyMessageLimitMax, + }, + } +} + +// TestRenderUserProfileTabs 渲染整合后的账号设置页:用户设置 + 提问/私聊/投票 三个功能面板, +// 覆盖"开启 / 手动关闭 / 已达定量上限"三种功能状态。 +func TestRenderUserProfileTabs(t *testing.T) { + type mockControl struct { + Enabled bool + OpenAt *time.Time + CloseAt *time.Time + QuotaLimit int64 + QuotaCount int64 + QuotaResetAt *time.Time + } + type mockState struct { + Enabled bool + Open bool + Reason string + QuotaLimit int64 + QuotaCount int64 + } + type mockFeature struct { + Key string + LangCode string + NameText string + StatusText string + CSRFTokenHTML interface{} + Control *mockControl + State *mockState + OpenAtStr string + CloseAtStr string + QuotaResetAtStr string + ScheduleDays string + ScheduleStart string + ScheduleEnd string + Mode string + } + + resetAt := time.Now().Add(-24 * time.Hour) + csrf := gotemplate.HTML(``) + + base := profileBaseData() + base["QuotaLimitMax"] = db.QuotaLimitMax + base["CSRFTokenHTML"] = csrf + base["FeatureQuestion"] = &mockFeature{ + Key: "question", LangCode: "zh-CN", NameText: "提问", StatusText: "进行中", CSRFTokenHTML: csrf, + Control: &mockControl{Enabled: true}, + State: &mockState{Enabled: true, Open: true}, + Mode: "always", + } + // 手动关闭 + base["FeatureChat"] = &mockFeature{ + Key: "chat", LangCode: "zh-CN", NameText: "私聊", StatusText: "已关闭", CSRFTokenHTML: csrf, + Control: &mockControl{Enabled: false}, + State: &mockState{Enabled: false, Reason: "disabled"}, + Mode: "always", + } + // 定时 + 定量:已达上限(历史数据存在循环定时,模式推断为 recurring) + base["FeatureVote"] = &mockFeature{ + Key: "vote", LangCode: "zh-CN", NameText: "投票", StatusText: "已达上限", CSRFTokenHTML: csrf, + Control: &mockControl{Enabled: true, QuotaLimit: 100, QuotaCount: 100, QuotaResetAt: &resetAt}, + State: &mockState{Enabled: true, Reason: "quota_reached", QuotaLimit: 100, QuotaCount: 100}, + OpenAtStr: "2026-09-01T09:00", CloseAtStr: "2026-09-30T18:00", + QuotaResetAtStr: resetAt.Format("2006-01-02 15:04"), + ScheduleDays: "1,3,5", ScheduleStart: "09:00", ScheduleEnd: "18:00", + Mode: "recurring", + } + + // 逐个面板渲染:模板能正常执行,且只有目标面板可见、其余面板带 hidden + all := []string{"account", "question", "chat", "vote"} + for _, tab := range all { + base["ActiveProfileTab"] = tab + out, err := renderToString(t, "user/profile", base) + if err != nil { + t.Fatalf("render user/profile (tab=%s) failed: %v", tab, err) + } + if tab == "account" { + // 标签块组件的上限常量已注入(缺注入时 with 会静默跳过,页面失去计数/锁定能力) + wantMax := fmt.Sprintf(`data-tb-max="%d" data-tb-max-len="%d"`, conf.Limits.MaxTags, conf.Limits.MaxTagLen) + if !strings.Contains(out, wantMax) { + t.Fatalf("account: 标签输入缺 data-tb-max 注入,want %q", wantMax) + } + wantBlock := fmt.Sprintf(`data-tb-max="%d" data-tb-max-len="%d"`, conf.Limits.MaxBlockWords, conf.Limits.MaxBlockWordLen) + if !strings.Contains(out, wantBlock) { + t.Fatalf("account: 屏蔽词输入缺 data-tb-max 注入,want %q", wantBlock) + } + } + if tab == "chat" { + // 私聊面板的 number 输入框 min/max 与 conf.Limits 同源 + wantChat := fmt.Sprintf(`name="chat_max_messages" class="uk-input uk-width-small" type="number" min="1" max="%d"`, conf.Limits.ChatMaxMessages) + if !strings.Contains(out, wantChat) { + t.Fatalf("chat: 会话条数输入缺 conf 上限,want %q", wantChat) + } + wantDaily := fmt.Sprintf(`name="chat_daily_limit" class="uk-input uk-width-small" type="number" min="0" max="%d"`, conf.Limits.DailyMessageLimitMax) + if !strings.Contains(out, wantDaily) { + t.Fatalf("chat: 每日条数输入缺 conf 上限,want %q", wantDaily) + } + } + for _, other := range all { + want := fmt.Sprintf(`data-profile-panel="%s"`, other) + visible := strings.Contains(out, want+">") + hidden := strings.Contains(out, want+" hidden>") + if other == tab && !visible { + t.Fatalf("tab=%s: 面板 %s 未渲染为可见", tab, other) + } + if other != tab && !hidden { + t.Fatalf("tab=%s: 面板 %s 未隐藏", tab, other) + } + } + } +} + +// TestRenderUserQuestionList 模拟 /user/questions 的数据渲染,复现 500 错误。 +func TestRenderUserQuestionList(t *testing.T) { + type mockItem struct { + Type string + CreatedAt time.Time + Content string + Link string + IsAnswered bool + IsRead bool + IsPrivate bool + IsBlocked bool + QuestionID uint + IsPinned bool + PinLink string + } + type mockConv struct { + Token string + CreatedAt time.Time + } + type mockConvDetail struct { + Conversation *mockConv + OwnerDomain string + OwnerName string + FirstMessage string + IsBlocked bool + } + + base := map[string]interface{}{ + "Title": "我的提问", + "LangCode": "zh-CN", + "SupportedLangs": []map[string]string{{"Code": "zh-CN", "Name": "简体中文"}}, + "IsLogged": true, + "LoggedUser": map[string]interface{}{"Domain": "test", "Name": "tester"}, + "LoggedUserName": "tester", + "CurrentURI": "/user/questions", + "IsUserPage": true, + "IsPixel": false, + "VConsole": false, + "CSRFTokenHTML": gotemplate.HTML(``), + "RecaptchaSiteKey": "", + "CaptchaType": "recaptcha", + "PageUser": map[string]interface{}{"Domain": "test", "Name": "tester", "Avatar": ""}, + "ICP": "", + "Stats": map[string]int64{ + "total": 3, "answered": 2, "unanswered": 1, "read": 2, "unread": 1, "private": 1, "pinned": 1, + }, + "ChatStats": map[string]int64{ + "total": 2, "received": 1, "initiated": 1, "closed": 0, + }, + "Keyword": "", + "SelectedSort": "latest", + "SelectedStatus": "all", + "SelectedRead": "all", + "SelectedType": "all", + "ReceivedItems": []interface{}{ + mockItem{Type: "question_public", CreatedAt: time.Now(), Content: "你好吗?", Link: "/_/test/1", + IsAnswered: true, IsRead: true, QuestionID: 1, IsPinned: true, PinLink: "/_/test/1/pin"}, + mockItem{Type: "question_private", CreatedAt: time.Now(), Content: "悄悄话", Link: "/_/test/2", + IsAnswered: false, IsPrivate: true, QuestionID: 2, PinLink: "/_/test/2/pin"}, + }, + "ReceivedChats": []interface{}{ + mockItem{Type: "chat", CreatedAt: time.Now(), Content: "你好", Link: "/_/test/chat/abc", IsBlocked: false}, + }, + "ConversationDetails": []interface{}{ + mockConvDetail{Conversation: &mockConv{Token: "abc", CreatedAt: time.Now()}, + OwnerDomain: "other", OwnerName: "别人", FirstMessage: "hi", IsBlocked: false}, + }, + } + + if err := renderWithData(t, "user/question-list", base); err != nil { + t.Fatalf("render user/question-list failed: %v", err) + } + + // 带搜索关键词的场景 + base["Keyword"] = "hello" + if err := renderWithData(t, "user/question-list", base); err != nil { + t.Fatalf("render user/question-list (keyword) failed: %v", err) + } +} diff --git a/templates/sponsor.html b/templates/sponsor.html new file mode 100644 index 0000000..ae8c551 --- /dev/null +++ b/templates/sponsor.html @@ -0,0 +1,108 @@ +{{template "base/header" .}} + +
    +
    +
    +

    给 NekoBox 打钱

    +

    NekoBox 创立于 2020 年疫情初期,一开始是我疫情在家花了三天时间随手写得一个匿名留言箱。

    +

    目前 NekoBox 的服务器、CDN 开销还是我一个人承担,如果你也想为我分担一些,欢迎给 NekoBox 打钱!👏🏻

    +
    +
    + +
    +
    +
    感谢以下小伙伴对 NekoBox 的支持!
    + + + + + + + + + + +
    日期附言金额
    +
    +{{template "base/footer" .}} diff --git a/templates/templates_test.go b/templates/templates_test.go new file mode 100644 index 0000000..5e83e39 --- /dev/null +++ b/templates/templates_test.go @@ -0,0 +1,85 @@ +// Copyright 2022 E99p1ant. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package templates + +import ( + gotemplate "html/template" + "regexp" + "testing" + + "github.com/flamego/template" + + templatepkg "github.com/tamakyi/TamaBox/internal/template" +) + +// TestTemplatesParse 复刻生产环境(internal/route/route.go 中 +// template.Templater + templatepkg.FuncMap())的模板加载逻辑: +// 逐个模板注册 FuncMap 并解析,任一文件解析失败即报错。 +func TestTemplatesParse(t *testing.T) { + fs, err := template.EmbedFS(FS, ".", []string{".html"}) + if err != nil { + t.Fatalf("EmbedFS: %v", err) + } + + tpl := gotemplate.New("Flamego.Template") + for _, f := range fs.Files() { + tt := tpl.New(f.Name()) + for _, funcMap := range templatepkg.FuncMap() { + tt.Funcs(funcMap) + } + + data, err := f.Data() + if err != nil { + t.Fatalf("get data of %q: %v", f.Name(), err) + } + + if _, err := tt.Parse(string(data)); err != nil { + t.Errorf("parse %q: %v", f.Name(), err) + } + } +} + +var ( + // definePattern 匹配 {{define "x"}} / {{block "x" ...}}:定义模板。 + definePattern = regexp.MustCompile(`\{\{\s*(?:define|block)\s+"([^"]+)"`) + // refPattern 匹配 {{template "x" ...}}:引用模板。 + refPattern = regexp.MustCompile(`\{\{\s*template\s+"([^"]+)"`) +) + +// TestTemplateCrossReferences 检查所有 {{template "x"}} 引用的目标模板 +// 是否真实存在(文件名或 define/block 定义),避免运行时 "no such template"。 +func TestTemplateCrossReferences(t *testing.T) { + fs, err := template.EmbedFS(FS, ".", []string{".html"}) + if err != nil { + t.Fatalf("EmbedFS: %v", err) + } + + // 集合 = 所有模板文件名 + 文件内 define/block 定义的名称 + names := make(map[string]bool) + fileData := make(map[string][]byte) + for _, f := range fs.Files() { + names[f.Name()] = true + data, err := f.Data() + if err != nil { + t.Fatalf("get data of %q: %v", f.Name(), err) + } + fileData[f.Name()] = data + } + + for _, data := range fileData { + for _, m := range definePattern.FindAllStringSubmatch(string(data), -1) { + names[m[1]] = true + } + } + + // 检查所有引用是否落在集合内 + for name, data := range fileData { + for _, m := range refPattern.FindAllStringSubmatch(string(data), -1) { + if !names[m[1]] { + t.Errorf("%s: 引用了未定义的模板 %q", name, m[1]) + } + } + } +} diff --git a/templates/user/deactivate.html b/templates/user/deactivate.html new file mode 100644 index 0000000..3e71042 --- /dev/null +++ b/templates/user/deactivate.html @@ -0,0 +1,17 @@ +{{template "base/header" .}} +
    +
    + {{ .CSRFTokenHTML }} + {{t .LangCode "deactivate.title"}} + {{template "base/alert" .}} +
    + {{t .LangCode "deactivate.desc"}} +
    +
    + +
    +
    +
    +{{template "base/footer" .}} diff --git a/templates/user/explore.html b/templates/user/explore.html new file mode 100644 index 0000000..f50de58 --- /dev/null +++ b/templates/user/explore.html @@ -0,0 +1,621 @@ +{{template "base/header" .}} + + +
    +

    {{t .LangCode "explore.title"}}

    + +
    +

    {{t .LangCode "explore.notice" | safe}}

    +
    + +
    + + +
    + +
    +
    +
    +

    {{t .LangCode "explore.recommend"}}

    + +
    +
    + {{if .RecommendUsers}} + {{range $user := .RecommendUsers}} + + {{end}} + {{else}} +
    {{t .LangCode "explore.noRecommend"}}
    + {{end}} +
    +
    + + + {{if .HotTags}} +
    +

    {{t .LangCode "explore.hotTags"}}

    +
    + {{range $i, $tag := .HotTags}} + #{{$tag}} + {{end}} +
    +
    + {{end}} + +
    +
    +
    +
    + + +
    +
    +
    + +
    +
    +
    + + {{if .Users}} +
    + {{range .Users}} + {{$user := .}} +
    +
    +
    +
    + avatar +
    +
    + +
    + {{if $user.Intro}}{{$user.Intro}}{{else}}{{t $.LangCode "explore.lazy"}}{{end}} +
    +
    + {{if $user.TagList}} + {{range $index, $tag := $user.TagList}} + {{$tag}} + {{end}} + {{else}} + {{t $.LangCode "explore.noTags"}} + {{end}} +
    +
    +
    +
    +
    + {{end}} +
    + + + {{else}} +
    {{t .LangCode "explore.noResult"}}
    + {{end}} +
    + + +
    + + +{{template "base/footer" .}} diff --git a/templates/user/feature-control-form.html b/templates/user/feature-control-form.html new file mode 100644 index 0000000..0345d3a --- /dev/null +++ b/templates/user/feature-control-form.html @@ -0,0 +1,135 @@ + +
    +
    +

    {{ .NameText }}

    + {{ .StatusText }} +
    + {{t .LangCode (print "admin.featureHint." .Key)}} + +
    + {{ .CSRFTokenHTML }} + +
    + +
    +
    + {{t .LangCode "admin.featureMode"}} +
    + + + +
    + {{t .LangCode "admin.featureModeHint"}} +
    +
    + + + {{t .LangCode "admin.featureTimeHint"}} +
    +
    + +
    +
    + {{ range $i := loop 7 }} + + {{ end }} +
    +
    + + +
    + {{t .LangCode "admin.featureScheduleHint"}} +
    +
    + {{ if ne .Key "chat" }} +
    + + {{t .LangCode "admin.featureQuotaHint"}} +
    +
    + {{t .LangCode "admin.featureQuotaCount"}}:{{ .State.QuotaCount }} + {{ if .Control.QuotaLimit }}/ {{ .Control.QuotaLimit }}{{ else }}({{t .LangCode "admin.featureQuotaUnlimited"}}){{ end }} + {{ if .Control.QuotaResetAt }}
    {{t .LangCode "admin.featureQuotaResetAt"}} {{ .QuotaResetAtStr }}{{ end }} +
    + {{ end }} +
    + {{ if ne .Key "chat" }} + + {{ end }} + +
    +
    + + {{ if ne .Key "chat" }} +
    + {{ .CSRFTokenHTML }} + +
    + {{ end }} + + +
    diff --git a/templates/user/global-blockwords.html b/templates/user/global-blockwords.html new file mode 100644 index 0000000..a59668e --- /dev/null +++ b/templates/user/global-blockwords.html @@ -0,0 +1,29 @@ + +{{ $root := .Root }} +
    +
    + {{ $root.CSRFTokenHTML }} + {{t $root.LangCode "admin.globalBlockWords"}} +
    +

    {{t $root.LangCode "admin.globalBlockWordsHint"}}

    + + +
    +
    + +
    +
    +
    diff --git a/templates/user/profile.html b/templates/user/profile.html new file mode 100644 index 0000000..739e561 --- /dev/null +++ b/templates/user/profile.html @@ -0,0 +1,1528 @@ +{{template "base/header" .}} + + + + + + + + + + + + + + + + +{{template "base/alert" .}} + + +
    +
    + +
    +

    {{t .LangCode "profile.cropTitle"}}

    +
    +
    +
    + +
    +

    +
    + +
    +
    + + +
    + + + + +
    + + +
    +
    + {{ .CSRFTokenHTML }} + + +
    +

    {{t .LangCode "profile.card.basic"}}

    +
    + + +
    +
    + + +
    +
    + +
    + +
    +
    + + +
    +
    + +
    + +
    +
    + + + {{t .LangCode "admin.langHint"}} +
    +
    + + +
    +
    + +
    +
    + + +
    +

    {{t .LangCode "profile.card.avatarBg"}}

    +
    +
    + + + + 1:1 +
    + + +
    + {{t .LangCode "profile.avatarCropHint"}} +
    +
    + + + + 16:9 +
    + + +
    + {{t .LangCode "profile.backgroundCropHint"}} +
    +
    + +
    + +
    +
    + + +
    +
      +
    • + {{t .LangCode "profile.card.qr"}} +
      +
      +
      +
      + +
      + +
      +
      + +
      + +
      +
      + +
      + +
      +
      + + {{t .LangCode "admin.customFgHint"}} +
      +
      + +
      + + {{.LoggedUser.Dotscale}} + +
      +
      +
      + +
      + + {{.LoggedUser.Backgroundimagealpha}} + +
      +
      +
      + +
      + + +
      + {{t .LangCode "admin.qrPreviewHint"}} +
      +
      +
      +
      +

      {{t .LangCode "admin.preview"}}

      +
      +
      +
      + {{t .LangCode "admin.themePreset"}} +
      + + + + +
      +
      +
      + +
      +

      {{t .LangCode "admin.previewHint"}}

      +
      +
      +
      +
      +
    • +
    +
    + +
    +
    + + +
    +
      +
    • + {{t .LangCode "admin.social"}} +
      + {{t .LangCode "admin.socialHint"}} + + + + + +
      +
    • +
    +
    + +
    +
    + + +
    +

    {{t .LangCode "profile.card.password"}}

    +
    + + +
    +
    + + +
    +

    {{t .LangCode "profile.pwdNote"}}

    +
    +
    + +
    +
    +
    + + +
    +

    {{t .LangCode "admin.tags"}}

    +
    + {{ .CSRFTokenHTML }} +
    + + +
    +
    + +
    +
    + +
    +
    +
    + + +
    +

    {{t .LangCode "admin.pagePassword"}}

    +
    + {{ .CSRFTokenHTML }} +
    + + +
    +
    + +
    +
    +
    + + +
    +

    {{t .LangCode "admin.account"}}

    + +
    +
    + + + +
    + {{ with .FeatureQuestion }}{{template "user/feature-control-form" .}}{{ end }} + +
    +
    +
    + {{ $.CSRFTokenHTML }} + {{t $.LangCode "admin.harassment"}} +
    +
    + +
    +
    + +
    +
    +
    + + + {{ template "user/global-blockwords" (dict "Root" $ "Action" "/user/blockwords/update?tab=question") }} + +
    +
    +
    + {{ $.CSRFTokenHTML }} + {{t $.LangCode "admin.askPassword"}} +
    + + +
    +
    + +
    +
    +
    +
    + + +
    + +
    + {{ with .FeatureChat }}{{template "user/feature-control-form" .}}{{ end }} + +
    +
    + {{ $.CSRFTokenHTML }} + {{t $.LangCode "admin.chat"}} +
    + + {{ with $.ChatLimits }} + + {{ end }} +
    +
    + + {{ with $.ChatLimits }} + + {{ end }} + {{t $.LangCode "admin.dailyLimitHint"}} +
    +
    + +
    +
    +
    + +
    + + {{ template "user/global-blockwords" (dict "Root" $ "Action" "/user/blockwords/update?tab=chat") }} +
    + + +
    + {{ with .FeatureVote }}{{template "user/feature-control-form" .}}{{ end }} + +
    + + {{ template "user/global-blockwords" (dict "Root" $ "Action" "/user/blockwords/update?tab=vote") }} +
    + + + + + + + + + +{{template "base/footer" .}} diff --git a/templates/user/question-list.html b/templates/user/question-list.html new file mode 100644 index 0000000..3c8c53a --- /dev/null +++ b/templates/user/question-list.html @@ -0,0 +1,486 @@ +{{template "base/header" .}} + + + +
    +
    +

    {{t .LangCode "qlist.title"}}

    + {{t .LangCode "admin.featuresEntry"}} +
    + + +
    + + + +
    + + +
    + + {{template "base/alert" .}} + + +
    +
    {{ .Stats.total }}{{t .LangCode "qlist.statsTotal"}}
    +
    {{ .Stats.answered }}{{t .LangCode "qlist.statsAnswered"}}
    +
    {{ .Stats.unanswered }}{{t .LangCode "qlist.statsUnanswered"}}
    +
    {{ .Stats.read }}{{t .LangCode "qlist.statsRead"}}
    +
    {{ .Stats.unread }}{{t .LangCode "qlist.statsUnread"}}
    +
    {{ .Stats.private }}{{t .LangCode "qlist.statsPrivate"}}
    +
    {{ .Stats.pinned }}{{t .LangCode "qlist.statsPinned"}}
    +
    + +
    + +
    +
    +
    + +
    +
    + +
    + {{ if ne .Keyword "" }} + + {{ end }} +
    +
    +
    +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    +
    +
    + + +

    {{t .LangCode "qlist.received"}}

    + {{ if .ReceivedItems }} + {{ range .ReceivedItems }} +
    +
    + +
    + +
    + {{Date .CreatedAt "Y-m-d H:i:s"}} + {{ if .IsPinned }} + {{t $.LangCode "qlist.pinnedShort"}}{{t $.LangCode "qlist.pinned"}} + {{ end }} + {{ if eq .Type "question_private" }} + {{t $.LangCode "qlist.privateShort"}}{{t $.LangCode "qlist.private"}} + {{ end }} + {{ if not .IsAnswered }} + {{t $.LangCode "qlist.unansweredShort"}}{{t $.LangCode "qlist.unanswered"}} + {{ end }} + {{ if .IsRead }} + {{t $.LangCode "qlist.readShort"}}{{t $.LangCode "qlist.read"}} + {{ else }} + {{t $.LangCode "qlist.unreadShort"}}{{t $.LangCode "qlist.unread"}} + {{ end }} +
    + +
    + {{ if not .IsRead }} + +
    + {{ $.CSRFTokenHTML }} + +
    + {{ end }} + +
    + {{ $.CSRFTokenHTML }} + +
    +
    +
    + +
    {{MarkdownPlainText .Content}}
    +
    +
    + {{ end }} + {{ if .HasMoreQuestions }} + + {{ end }} + {{ else }} +

    {{t .LangCode "qlist.empty"}}

    + {{ end }} +
    + + + + + + +
    + + + +{{template "base/footer" .}} diff --git a/templates/user/vote-form.html b/templates/user/vote-form.html new file mode 100644 index 0000000..19aefff --- /dev/null +++ b/templates/user/vote-form.html @@ -0,0 +1,392 @@ +{{template "base/header" .}} + +
    +

    + {{ if .IsEdit }}{{t .LangCode "vote.editTitle"}}{{ else }}{{t .LangCode "vote.newTitle"}}{{ end }} +

    + {{t .LangCode "common.back"}} +
    + +
    + {{ .CSRFTokenHTML }} + + {{template "base/alert" .}} + + +
    +

    {{t .LangCode "vote.formBasic"}}

    + + {{ if .LockedContent }} +
    {{t .LangCode "vote.formLockedHint"}}
    + {{ end }} + +
    + + +
    + +
    + + +
    + +
    +
    + + {{ if .LockedContent }} + + {{ else }} + + {{ end }} +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + + {{t .LangCode "vote.formQuotaHint"}} +
    + {{ if not .LockedContent }} +
    + + +
    + {{ end }} +
    + + + +
    +
    + {{t .LangCode "vote.formMaxVotesPerFingerprint"}}{{t .LangCode "vote.formMaxVotesPerAccount"}} +
    +
    + +
    + + + +
    +
    + + {{ if not .LockedContent }} + +
    +

    {{t .LangCode "vote.formOptions"}}

    + +
    + + +
    + + + + {{ end }} + +
    + + {{ if and .IsEdit (not .LockedContent) }}{{ end }} + + {{ if not .LockedContent }}{{ end }} + {{t .LangCode "common.cancel"}} +
    + +
    + + + +{{if .DraftSaved}} + +{{end}} + +{{template "base/footer" .}} diff --git a/templates/user/vote-results.html b/templates/user/vote-results.html new file mode 100644 index 0000000..7300b1b --- /dev/null +++ b/templates/user/vote-results.html @@ -0,0 +1,182 @@ +{{template "base/header" .}} + +
    +

    {{t .LangCode "vote.resultsTitle"}}:{{ .Vote.Title }}

    + +
    + +
    +
    {{ .Total }}
    +
    {{t .LangCode "vote.resultsTotal"}}
    +
    + +{{ if eq .Vote.Type "form" }} + + {{ if .Results.FormFieldStats }} +

    {{t .LangCode "vote.resultsOptions"}}

    +
    + {{ range $si, $stat := .Results.FormFieldStats }} +
    +
    + {{ add $si 1 }} + {{ fieldTypeLabel $.LangCode $stat.Field.FieldType }} + {{ $stat.Field.Label }} + {{t $.LangCode "vote.resultsAnswered"}}: {{ $stat.Total }} +
    + + {{ if or (eq $stat.Field.FieldType "radio") (eq $stat.Field.FieldType "select") (eq $stat.Field.FieldType "checkbox") }} + {{ $denom := $stat.Total }} + {{ if eq $stat.Field.FieldType "checkbox" }}{{ $denom = $stat.TotalSelections }}{{ end }} + {{ range $o := $stat.OptionStats }} +
    +
    + {{ $o.Option.Content }} + {{ $o.Count }} {{t $.LangCode "vote.resultsVotes"}}({{ if eq $denom 0 }}0{{ else }}{{ percentOf $o.Count $denom }}{{ end }}%) +
    +
    +
    +
    +
    + {{ end }} + {{ if $stat.CustomStats }} +
    +
    {{t $.LangCode "vote.page.customStats"}}:
    + {{ range $c := $stat.CustomStats }} +
    + {{ $c.Text }} + {{ $c.Count }} {{t $.LangCode "vote.resultsVotes"}} +
    + {{ end }} +
    + {{ end }} + + {{ else if eq $stat.Field.FieldType "rating" }} +
    {{t $.LangCode "vote.page.avgRating"}}: {{ printf "%.1f" $stat.AvgRating }}({{ $stat.Total }} {{t $.LangCode "vote.resultsVotes"}})
    + {{ range $r := $stat.RatingCounts }} +
    + {{ $r.Score }} {{t $.LangCode "vote.page.ratingUnit"}} + {{ $r.Count }} {{t $.LangCode "vote.resultsVotes"}}({{ if eq $stat.Total 0 }}0{{ else }}{{ percentOf $r.Count $stat.Total }}{{ end }}%) +
    +
    +
    +
    + {{ end }} + + {{ else if eq $stat.Field.FieldType "rank" }} +
    {{t $.LangCode "vote.page.avgRank"}}: {{ printf "%.2f" $stat.AvgRank }}({{ $stat.Total }} {{t $.LangCode "vote.resultsVotes"}})
    + {{ range $o := $stat.OptionStats }} +
    + {{ $o.Option.Content }} + {{t $.LangCode "vote.page.avgRank"}}: {{ if gt $o.Count 0 }}{{ printf "%.2f" $o.AvgRank }}{{ else }}-{{ end }} · {{t $.LangCode "vote.page.rankedTimes"}}: {{ $o.Count }} +
    + {{ end }} + + {{ else if eq $stat.Field.FieldType "number" }} +
    {{t $.LangCode "vote.page.avgNumber"}}: {{ printf "%.1f" $stat.AvgNumber }}({{ $stat.Total }} {{t $.LangCode "vote.resultsVotes"}})
    + + {{ else }} +
    {{t $.LangCode "vote.page.fieldFilled"}}: {{ $stat.TextCount }}
    + {{ $replies := index $.TextReplies $stat.Field.Label }} + {{ if $replies }} +
    +
    + ▾ + {{t $.LangCode "vote.resultsViewTexts"}}({{ len $replies }}) +
    + +
    + {{ end }} + {{ end }} +
    + {{ end }} +
    + {{ end }} + + +{{ else if .Results }} + +

    {{t .LangCode "vote.resultsOptions"}}

    +
    + {{ if or (eq .Results.Type "single") (eq .Results.Type "multiple") }} + {{ range .Results.Options }} +
    +
    + {{ .Option.Content }} + {{ .Count }} {{t $.LangCode "vote.resultsVotes"}}({{ .Percent }}%) +
    +
    +
    +
    +
    + {{ end }} + + {{ else if eq .Results.Type "rating" }} +
    {{t .LangCode "vote.page.avgRating"}}: {{ printf "%.1f" .Results.AvgRating }}
    + {{ range .Results.Ratings }} +
    +
    + {{ .Score }} {{t $.LangCode "vote.page.ratingUnit"}} + {{ .Count }} {{t $.LangCode "vote.resultsVotes"}} +
    +
    +
    +
    +
    + {{ end }} + + {{ else if eq .Results.Type "rank" }} + + + + {{ range .Results.Rankings }} + + {{ end }} + +
    {{t .LangCode "vote.page.optionColumn"}}{{t .LangCode "vote.page.avgRank"}}
    {{ .Option.Content }}{{ if gt .AvgRank 0.0 }}{{ printf "%.2f" .AvgRank }}{{ else }}-{{ end }}
    + {{ end }} + + {{ if .Results.CustomStats }} +
    +
    {{t .LangCode "vote.page.customStats"}}
    + {{ range .Results.CustomStats }} +
    + {{ .Text }} + {{ .Count }} {{t $.LangCode "vote.resultsVotes"}} +
    + {{ end }} +
    + {{ end }} +
    +{{ else }} +
    {{t .LangCode "vote.resultsEmpty"}}
    +{{ end }} + + + +{{template "base/footer" .}} diff --git a/templates/vote/page.html b/templates/vote/page.html new file mode 100644 index 0000000..33e895f --- /dev/null +++ b/templates/vote/page.html @@ -0,0 +1,526 @@ +{{template "base/header" .}} + + + +{{template "base/alert" .}} + +
    +
    + {{ if .Owner }} + +
    + {{ .Owner.Name }} +
    {{t .LangCode "vote.page.by"}}
    +
    + {{ end }} +
    + {{ if .NotStarted }}{{t .LangCode "vote.page.notStarted"}}{{ end }} + {{ if .Ended }}{{t .LangCode "vote.page.ended"}}{{ end }} + {{ if and .CanVote (not .Ended) }}{{t .LangCode "vote.page.active"}}{{ end }} + {{ if and .HasVoted (not .Ended) }}{{t .LangCode "vote.page.participated"}}{{ end }} +
    +
    + +

    {{ .Vote.Title }}

    + {{ if .Vote.Description }} +

    {{ .Vote.Description }}

    + {{ end }} +
    + +{{ if .PreviewMode }} +
    {{t .LangCode "vote.page.previewHint"}}
    +{{ end }} + +{{ if .FeatureClosedMessage }} +
    {{ .FeatureClosedMessage }}
    +{{ end }} + +{{ if and .NotStarted (not .Error) }} +
    {{t .LangCode "vote.page.notStartedHint"}}
    +{{ else if and .Ended (not .ShowResults) (not .Error) }} +
    {{t .LangCode "vote.page.endedHint"}}
    +{{ end }} + +{{ if .CanVote }} + {{ if .VoteScopeRegisteredOnly }} + {{ if not .IsLogged }} +
    + {{t .LangCode "vote.page.loginRequired"}} {{t .LangCode "common.login"}} +
    + {{ end }} + {{ else }} +
    {{t .LangCode "vote.page.anonymousHint"}}
    + {{ end }} + +
    + {{ .CSRFTokenHTML }} + + +
    + {{ if eq .Vote.Type "single" }} + {{ range .Options }} + + {{ end }} + + {{ else if eq .Vote.Type "multiple" }} +
    {{t .LangCode "vote.page.multipleHint"}}(最多 {{ .Vote.MaxChoices }} 项)
    +
    + {{ range .Options }} + + {{ end }} +
    + + {{ else if eq .Vote.Type "rating" }} + + + + {{ else if eq .Vote.Type "rank" }} +
    {{t .LangCode "vote.page.rankHint"}}
    + {{ range .Options }} +
    + {{ .Content }} + +
    + {{ end }} + + {{ else if eq .Vote.Type "form" }} + {{ range $fi, $f := .FormFields }} +
    +
    + {{ add $fi 1 }} + {{ fieldTypeLabel $.LangCode $f.FieldType }} +
    {{ $f.Label }}{{ if $f.Required }} *{{ end }}
    +
    + {{ if eq $f.FieldType "text" }} + + {{ else if eq $f.FieldType "textarea" }} + + {{ else if eq $f.FieldType "select" }} + + {{ if $f.AllowCustom }} + + {{ end }} + {{ else if eq $f.FieldType "radio" }} + {{ range parseOptions $f.Options }} + + {{ end }} + {{ if $f.AllowCustom }} + + + {{ end }} + {{ else if eq $f.FieldType "checkbox" }} + {{ range parseOptions $f.Options }} + + {{ end }} + {{ if $f.AllowCustom }} + + + {{ end }} + {{ else if eq $f.FieldType "number" }} + + {{ else if eq $f.FieldType "rating" }} + + {{ else if eq $f.FieldType "rank" }} +
    + {{ if $f.Required }}{{t $.LangCode "vote.page.rankHintRequired"}}{{ else }}{{t $.LangCode "vote.page.rankHintOptional"}}{{ end }} +
    + {{ $opts := parseOptions $f.Options }} + {{ range $oi, $opt := $opts }} +
    + {{ $opt }} + +
    + {{ end }} + {{ end }} +
    + {{ end }} + {{ end }} + + {{ if and .Vote.AllowCustom (or (eq .Vote.Type "single") (eq .Vote.Type "multiple") (eq .Vote.Type "rank")) }} +
    + + +
    + {{ end }} +
    + +
    + {{ if .PreviewMode }} + + {{t .LangCode "vote.page.previewSubmitHint"}} + {{ else if eq .CaptchaType "math" }} + + {{ else }} + + {{ end }} +
    +
    + +{{ else if .HasVoted }} + {{ if and (not .Success) (not .Error) }} +
    {{t .LangCode "vote.page.alreadyVoted"}}
    + {{ end }} +{{ end }} + +{{ if .ShowResults }} +
    +

    {{t .LangCode "vote.page.resultsTitle"}}

    + + {{ if .Results }} + {{ if or (eq .Results.Type "single") (eq .Results.Type "multiple") }} +
    {{t .LangCode "vote.page.totalVotes"}}: {{ .Results.Total }}
    + {{ range .Results.Options }} +
    +
    + {{ .Option.Content }} + {{ .Count }} {{t $.LangCode "vote.resultsVotes"}}({{ .Percent }}%) +
    +
    +
    +
    +
    + {{ end }} + + {{ else if eq .Results.Type "rating" }} +
    {{t .LangCode "vote.page.totalVotes"}}: {{ .Results.Total }} · {{t .LangCode "vote.page.avgRating"}}: {{ printf "%.1f" .Results.AvgRating }}
    + {{ range .Results.Ratings }} +
    +
    + {{ .Score }} {{t $.LangCode "vote.page.ratingUnit"}} + {{ .Count }} {{t $.LangCode "vote.resultsVotes"}} +
    +
    +
    +
    +
    + {{ end }} + + {{ else if eq .Results.Type "rank" }} +
    {{t .LangCode "vote.page.totalVotes"}}: {{ .Results.Total }}
    + + + + {{ range .Results.Rankings }} + + {{ end }} + +
    {{t .LangCode "vote.page.optionColumn"}}{{t .LangCode "vote.page.avgRank"}}
    {{ .Option.Content }}{{ if gt .AvgRank 0.0 }}{{ printf "%.2f" .AvgRank }}{{ else }}-{{ end }}
    + + {{ else if eq .Results.Type "form" }} +
    {{t .LangCode "vote.page.formCount"}}: {{ .Results.FormCount }}
    + {{ range $si, $stat := .Results.FormFieldStats }} +
    +
    + {{ add $si 1 }} + {{ fieldTypeLabel $.LangCode $stat.Field.FieldType }} + {{ $stat.Field.Label }} + {{t $.LangCode "vote.resultsAnswered"}}: {{ $stat.Total }} +
    + + {{ if or (eq $stat.Field.FieldType "radio") (eq $stat.Field.FieldType "select") (eq $stat.Field.FieldType "checkbox") }} + {{ $denom := $stat.Total }} + {{ if eq $stat.Field.FieldType "checkbox" }}{{ $denom = $stat.TotalSelections }}{{ end }} + {{ range $o := $stat.OptionStats }} +
    +
    + {{ $o.Option.Content }} + {{ $o.Count }} {{t $.LangCode "vote.resultsVotes"}}({{ if eq $denom 0 }}0{{ else }}{{ percentOf $o.Count $denom }}{{ end }}%) +
    +
    +
    +
    +
    + {{ end }} + {{ if $stat.CustomStats }} +
    +
    {{t $.LangCode "vote.page.customStats"}}:
    + {{ range $c := $stat.CustomStats }} +
    + {{ $c.Text }} + {{ $c.Count }} {{t $.LangCode "vote.resultsVotes"}} +
    + {{ end }} +
    + {{ end }} + + {{ else if eq $stat.Field.FieldType "rating" }} +
    {{t $.LangCode "vote.page.avgRating"}}: {{ printf "%.1f" $stat.AvgRating }}({{ $stat.Total }} {{t $.LangCode "vote.resultsVotes"}})
    + {{ range $r := $stat.RatingCounts }} +
    + {{ $r.Score }} {{t $.LangCode "vote.page.ratingUnit"}} + {{ $r.Count }} {{t $.LangCode "vote.resultsVotes"}}({{ if eq $stat.Total 0 }}0{{ else }}{{ percentOf $r.Count $stat.Total }}{{ end }}%) +
    +
    +
    +
    + {{ end }} + + {{ else if eq $stat.Field.FieldType "rank" }} +
    {{t $.LangCode "vote.page.avgRank"}}: {{ printf "%.2f" $stat.AvgRank }}({{ $stat.Total }} {{t $.LangCode "vote.resultsVotes"}})
    + {{ range $o := $stat.OptionStats }} +
    + {{ $o.Option.Content }} + {{t $.LangCode "vote.page.avgRank"}}: {{ if gt $o.Count 0 }}{{ printf "%.2f" $o.AvgRank }}{{ else }}-{{ end }} · {{t $.LangCode "vote.page.rankedTimes"}}: {{ $o.Count }} +
    + {{ end }} + + {{ else if eq $stat.Field.FieldType "number" }} +
    {{t $.LangCode "vote.page.avgNumber"}}: {{ printf "%.1f" $stat.AvgNumber }}({{ $stat.Total }} {{t $.LangCode "vote.resultsVotes"}})
    + + {{ else }} +
    {{t $.LangCode "vote.page.fieldFilled"}}: {{ $stat.TextCount }}
    + {{ end }} +
    + {{ end }} + {{ end }} + + {{ if .Results.CustomStats }} +
    +
    {{t .LangCode "vote.page.customStats"}}
    + {{ range .Results.CustomStats }} +
    + {{ .Text }} + {{ .Count }} {{t $.LangCode "vote.resultsVotes"}} +
    + {{ end }} +
    + {{ end }} + {{ else }} +
    {{t .LangCode "vote.resultsEmpty"}}
    + {{ end }} +
    +{{ end }} + +{{ if and .IsOwner (not .ShowResults) }} + +{{ end }} + + + +{{template "base/footer" .}} diff --git a/templates/vote_templates_test.go b/templates/vote_templates_test.go new file mode 100644 index 0000000..9469b6a --- /dev/null +++ b/templates/vote_templates_test.go @@ -0,0 +1,465 @@ +package templates + +import ( + gotemplate "html/template" + "regexp" + "strconv" + "strings" + "testing" + "time" + + "github.com/flamego/template" + + "github.com/tamakyi/TamaBox/internal/conf" + "github.com/tamakyi/TamaBox/internal/db" + "github.com/tamakyi/TamaBox/internal/dbutil" +) + +// voteBaseData 构造投票模板渲染的基础数据(仿 render_test.go 的 base)。 +func voteBaseData() map[string]interface{} { + return map[string]interface{}{ + "Title": "投票", + "LangCode": "zh-CN", + "SupportedLangs": []map[string]string{{"Code": "zh-CN", "Name": "简体中文"}}, + "IsLogged": true, + "LoggedUser": map[string]interface{}{"Domain": "test", "Name": "tester"}, + "LoggedUserName": "tester", + "CurrentURI": "/vote/abc123", + "IsUserPage": false, + "IsPixel": false, + "VConsole": false, + "CSRFTokenHTML": gotemplate.HTML(``), + "RecaptchaSiteKey": "", + "CaptchaType": "recaptcha", + "PageUser": map[string]interface{}{"Domain": "test", "Name": "tester", "Avatar": ""}, + "ICP": "", + // 参与端自定义补充选项的字数上限(生产由 route/vote 注入 conf.Limits.CustomAnswerLen) + "MaxCustomTextLen": conf.Limits.CustomAnswerLen, + "CustomFieldMarker": db.CustomFieldMarker, + // 站长侧单个选项文本上限(生产由 route/user 注入 conf.Limits.VoteOptionLen) + "MaxVoteOptionLen": conf.Limits.VoteOptionLen, + // [limits] 全站上限(生产由 Contexter 全局注入 conf.Limits), + // 供 question/list 嵌套的提问框 maxlength 同源 + "Limits": conf.Limits, + } +} + +func TestVoteFormUsesFixedDeviceLimitNotice(t *testing.T) { + fs, err := template.EmbedFS(FS, ".", []string{".html"}) + if err != nil { + t.Fatalf("EmbedFS: %v", err) + } + for _, f := range fs.Files() { + if f.Name() != "user/vote-form" && f.Name() != "user/vote-form.html" { + continue + } + data, err := f.Data() + if err != nil { + t.Fatalf("get template data: %v", err) + } + source := string(data) + if strings.Contains(source, `name="max_votes_per_fingerprint"`) { + t.Fatal("fixed fingerprint limit must not be rendered as a form input") + } + if !strings.Contains(source, `vote.formMaxVotesPerFingerprint`) { + t.Fatal("fixed fingerprint limit notice is missing") + } + return + } + t.Fatal("user/vote-form.html not found") +} + +func TestRenderVotePage(t *testing.T) { + opt1 := &db.VoteOption{Content: "选项 A"} + opt2 := &db.VoteOption{Content: "选项 B"} + + t.Run("single can vote", func(t *testing.T) { + base := voteBaseData() + base["Vote"] = &db.Vote{Title: "测试单选", Description: "描述", Type: db.VoteTypeSingle, LinkToken: "abc123", MaxChoices: 1} + base["Owner"] = map[string]interface{}{"Name": "tester", "Domain": "test", "Avatar": ""} + base["Options"] = []*db.VoteOption{opt1, opt2} + base["HasVoted"] = false + base["CanVote"] = true + base["NotStarted"] = false + base["Ended"] = false + base["VoteScopeRegisteredOnly"] = false + base["ShowResults"] = false + base["IsOwner"] = false + if err := renderWithData(t, "vote/page", base); err != nil { + t.Fatalf("render vote/page (single) failed: %v", err) + } + }) + + t.Run("multiple can vote", func(t *testing.T) { + base := voteBaseData() + base["Vote"] = &db.Vote{Title: "多选", Type: db.VoteTypeMultiple, LinkToken: "abc123", MaxChoices: 2} + base["Owner"] = map[string]interface{}{"Name": "tester", "Domain": "test", "Avatar": ""} + base["Options"] = []*db.VoteOption{opt1, opt2, {Content: "选项 C"}} + base["HasVoted"] = false + base["CanVote"] = true + base["NotStarted"] = false + base["Ended"] = false + base["VoteScopeRegisteredOnly"] = false + base["ShowResults"] = false + base["IsOwner"] = false + if err := renderWithData(t, "vote/page", base); err != nil { + t.Fatalf("render vote/page (multiple) failed: %v", err) + } + }) + + t.Run("rating can vote", func(t *testing.T) { + base := voteBaseData() + base["Vote"] = &db.Vote{Title: "评分", Type: db.VoteTypeRating, LinkToken: "abc123"} + base["Owner"] = map[string]interface{}{"Name": "tester", "Domain": "test", "Avatar": ""} + base["HasVoted"] = false + base["CanVote"] = true + base["NotStarted"] = false + base["Ended"] = false + base["VoteScopeRegisteredOnly"] = false + base["ShowResults"] = false + base["IsOwner"] = false + if err := renderWithData(t, "vote/page", base); err != nil { + t.Fatalf("render vote/page (rating) failed: %v", err) + } + }) + + t.Run("rank can vote", func(t *testing.T) { + base := voteBaseData() + base["Vote"] = &db.Vote{Title: "排序", Type: db.VoteTypeRank, LinkToken: "abc123"} + base["Owner"] = map[string]interface{}{"Name": "tester", "Domain": "test", "Avatar": ""} + base["Options"] = []*db.VoteOption{opt1, opt2} + base["HasVoted"] = false + base["CanVote"] = true + base["NotStarted"] = false + base["Ended"] = false + base["VoteScopeRegisteredOnly"] = false + base["ShowResults"] = false + base["IsOwner"] = false + if err := renderWithData(t, "vote/page", base); err != nil { + t.Fatalf("render vote/page (rank) failed: %v", err) + } + }) + + t.Run("preview draft form", func(t *testing.T) { + base := voteBaseData() + base["Vote"] = &db.Vote{Title: "草稿表单", Type: db.VoteTypeForm, LinkToken: "abc123"} + base["Owner"] = map[string]interface{}{"Name": "tester", "Domain": "test", "Avatar": ""} + base["FormFields"] = []*db.VoteFormField{ + {Model: dbutil.Model{ID: 1}, FieldType: db.VoteFormFieldTypeText, Label: "昵称", Required: true, MaxLength: 20}, + {Model: dbutil.Model{ID: 2}, FieldType: db.VoteFormFieldTypeRadio, Label: "满意度", Options: `["满意","一般"]`}, + } + base["HasVoted"] = false + base["CanVote"] = true + base["NotStarted"] = false + base["Ended"] = false + base["VoteScopeRegisteredOnly"] = false + base["ShowResults"] = false + base["IsOwner"] = true + base["IsLogged"] = true + base["PreviewMode"] = true + if err := renderWithData(t, "vote/page", base); err != nil { + t.Fatalf("render vote/page (preview) failed: %v", err) + } + }) + + t.Run("custom text limit injected", func(t *testing.T) { + base := voteBaseData() + base["Vote"] = &db.Vote{Title: "自定义选项", Type: db.VoteTypeSingle, LinkToken: "abc123", AllowCustom: true} + base["Owner"] = map[string]interface{}{"Name": "tester", "Domain": "test", "Avatar": ""} + base["FormFields"] = []*db.VoteFormField{ + {Model: dbutil.Model{ID: 1}, FieldType: db.VoteFormFieldTypeRadio, Label: "满意度", Options: `["满意","一般"]`, AllowCustom: true}, + } + base["HasVoted"] = false + base["CanVote"] = true + base["NotStarted"] = false + base["Ended"] = false + base["VoteScopeRegisteredOnly"] = false + base["ShowResults"] = false + base["IsOwner"] = false + out, err := renderToString(t, "vote/page", base) + if err != nil { + t.Fatalf("render vote/page (custom) failed: %v", err) + } + // 缺注入时模板不报错,只会渲染出 让整段脚本失效,必须显式断言 + if strings.Contains(out, "") { + t.Fatal("rendered page contains : MaxCustomTextLen was not injected") + } + // 注意:html/template 在