0904
This commit is contained in:
@@ -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:<port>,
|
||||||
|
; 使源站端口仅对本地 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
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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, "[email protected]", &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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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"`
|
||||||
|
}
|
||||||
|
)
|
||||||
@@ -0,0 +1,977 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="{{.LangCode}}">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width">
|
||||||
|
<title>{{ .Title }}</title>
|
||||||
|
<meta name="description" content="{{ if .MetaDescription }}{{ .MetaDescription }}{{ else }}{{ t .LangCode "site.description" }}{{ end }}">
|
||||||
|
<meta name="keywords" content="{{ t .LangCode "site.keywords" }}">
|
||||||
|
<!-- 预连接:UIkit 走公共 CDN(cdnjs.snrat.com),其余自托管库仍在本站 R2,均需预连接 -->
|
||||||
|
<link rel="preconnect" href="https://r2.337845818.best" crossorigin>
|
||||||
|
<link rel="preconnect" href="https://cdnjs.snrat.com" crossorigin>
|
||||||
|
<link rel="dns-prefetch" href="https://cn.vercount.one">
|
||||||
|
<!-- UIkit 3.3.3 切到公共 CDN(cdnjs.snrat.com,国内实测全量下载 ~0.25s,原 R2 自建 ~1.4-2.0s) -->
|
||||||
|
<link rel="stylesheet" href="https://cdnjs.snrat.com/ajax/libs/uikit/3.3.3/css/uikit.min.css"/>
|
||||||
|
<!-- Waline 评论区样式:非阻塞加载,不阻塞首屏渲染 -->
|
||||||
|
<link rel="stylesheet" href="https://r2.337845818.best/tamabox/cdn/waline/client/v2/waline-no-commits.css" media="print" onload="this.media='all'"/>
|
||||||
|
<script defer src="https://cdnjs.snrat.com/ajax/libs/uikit/3.3.3/js/uikit.min.js"></script>
|
||||||
|
<script defer src="https://cdnjs.snrat.com/ajax/libs/uikit/3.3.3/js/uikit-icons.min.js"></script>
|
||||||
|
<!-- UIkit 补丁:复刻原自建版 "modify-black-font"(官方版与自建版仅 3 处颜色差异——把有色容器内默认白字/白标题改为黑字)。
|
||||||
|
模板当前只用到 .uk-light 容器(用户背景封面,question/list.html、question-not-found.html;
|
||||||
|
其中 h3/p 已由 #usernamecolor/#introcolor 内联 style 覆盖),故只需补该容器的 3 处投影即可保持渲染一致。
|
||||||
|
若日后新增 .uk-card-primary/.uk-card-secondary/.uk-section-primary/.uk-tile-*/.uk-overlay-primary 等容器且需黑字,须同步扩展。 -->
|
||||||
|
<style>
|
||||||
|
.uk-light { color: rgba(0,0,0,.7); }
|
||||||
|
.uk-light .uk-h1, .uk-light .uk-h2, .uk-light .uk-h3, .uk-light .uk-h4, .uk-light .uk-h5, .uk-light .uk-h6,
|
||||||
|
.uk-light .uk-heading-2xlarge, .uk-light .uk-heading-large, .uk-light .uk-heading-medium, .uk-light .uk-heading-small, .uk-light .uk-heading-xlarge,
|
||||||
|
.uk-light h1, .uk-light h2, .uk-light h3, .uk-light h4, .uk-light h5, .uk-light h6 { color: #000; }
|
||||||
|
.uk-light .uk-table th { color: rgba(0,0,0,.7); }
|
||||||
|
</style>
|
||||||
|
<script defer src="https://r2.337845818.best/tamabox/cdn/lib/dayjs/1.10.8/dayjs.min.js"></script>
|
||||||
|
<script defer src="https://r2.337845818.best/tamabox/cdn/lib/alpinejs/3.9.0/cdn.min.js"></script>
|
||||||
|
{{ if .VConsole }}
|
||||||
|
<script src="https://r2.337845818.best/tamabox/cdn/lib/vconsole/3.12.1/vconsole.min.js" type="application/javascript"></script>
|
||||||
|
<script>new window.VConsole()</script>
|
||||||
|
{{ end }}
|
||||||
|
<!-- jQuery 已改为按需加载:仅 easy.qrcode 二维码页(list/question-not-found/profile)自行引入 -->
|
||||||
|
<script defer src="https://r2.337845818.best/tamabox/cdn/time.box.js"></script>
|
||||||
|
<!--<script src="https://r2.337845818.best/tamabox/cdn/busuanzi.pure.mini.js"/></script>-->
|
||||||
|
<script defer src="https://cn.vercount.one/js"></script>
|
||||||
|
<script defer src="https://r2.337845818.best/tamabox/cdn/lib/waline/2.15.8/waline.js"></script>
|
||||||
|
{{ if eq .CaptchaType "math" }}
|
||||||
|
<!-- 算数验证码:弹窗模式,不影响原布局 -->
|
||||||
|
<style>
|
||||||
|
.captcha-equation-box {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
background: #f0f2f5;
|
||||||
|
border: 1px solid #dcdcdc;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 8px 8px 8px 16px;
|
||||||
|
gap: 6px;
|
||||||
|
transition: border-color 0.2s;
|
||||||
|
}
|
||||||
|
.captcha-equation-box:focus-within {
|
||||||
|
border-color: #1e87f0;
|
||||||
|
box-shadow: 0 0 0 3px rgba(30,135,240,0.12);
|
||||||
|
}
|
||||||
|
.math-captcha-modal-question {
|
||||||
|
font-size: 1.4rem;
|
||||||
|
font-family: "Courier New", monospace;
|
||||||
|
font-weight: 700;
|
||||||
|
color: #333;
|
||||||
|
letter-spacing: 1px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
#captcha-modal-answer {
|
||||||
|
width: 80px;
|
||||||
|
padding: 6px 10px;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 1.2rem;
|
||||||
|
font-family: "Courier New", monospace;
|
||||||
|
font-weight: 600;
|
||||||
|
border: 1px solid #ccc;
|
||||||
|
border-radius: 5px;
|
||||||
|
outline: none;
|
||||||
|
transition: border-color 0.15s, box-shadow 0.15s;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
#captcha-modal-answer:focus {
|
||||||
|
border-color: #1e87f0;
|
||||||
|
box-shadow: 0 0 0 2px rgba(30,135,240,0.2);
|
||||||
|
}
|
||||||
|
/* 隐藏数字输入框的上下箭头 */
|
||||||
|
#captcha-modal-answer::-webkit-inner-spin-button,
|
||||||
|
#captcha-modal-answer::-webkit-outer-spin-button {
|
||||||
|
-webkit-appearance: none;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
#captcha-modal-answer {
|
||||||
|
-moz-appearance: textfield;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
{{ else if .RecaptchaTurnstileStyle }}
|
||||||
|
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?compat=recaptcha" async defer></script>
|
||||||
|
<script>
|
||||||
|
document.addEventListener('DOMContentLoaded', function () {
|
||||||
|
document.querySelectorAll('.g-recaptcha').forEach(item => {
|
||||||
|
item.disabled = true;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function onSubmit() {
|
||||||
|
document.querySelectorAll('.g-recaptcha').forEach(item => {
|
||||||
|
item.disabled = false;
|
||||||
|
})
|
||||||
|
}</script>
|
||||||
|
{{ else }}
|
||||||
|
<script src="{{.RecaptchaDomain}}/recaptcha/api.js" async defer></script>
|
||||||
|
<script>function onSubmit() {document.getElementById('form').submit();}</script>
|
||||||
|
{{ end }}
|
||||||
|
{{ if ne SentryDSN "" }}
|
||||||
|
<script
|
||||||
|
src="https://browser.sentry-cdn.com/7.37.2/bundle.tracing.replay.min.js"
|
||||||
|
integrity="sha384-o0mU2P+zsvXua0Y6f/J55PKWZt3sZCv3qDqJe6J5lZklyIQkpgjBVqNnPWYWqGhf"
|
||||||
|
crossorigin="anonymous"
|
||||||
|
></script>
|
||||||
|
<script>
|
||||||
|
Sentry.init({
|
||||||
|
dsn: "{{ SentryDSN }}",
|
||||||
|
integrations: [new Sentry.BrowserTracing(), new Sentry.Replay()],
|
||||||
|
tracesSampleRate: 1.0,
|
||||||
|
replaysSessionSampleRate: 0.1,
|
||||||
|
replaysOnErrorSampleRate: 1.0,
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
{{ end }}
|
||||||
|
<style>
|
||||||
|
.grecaptcha-badge {visibility: hidden;}
|
||||||
|
.icon-container {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
.icon {
|
||||||
|
margin-left: 10px;
|
||||||
|
width: 20px; /* 设置图标的宽度 */
|
||||||
|
height: auto; /* 保持图标的高度自动调整 */
|
||||||
|
}
|
||||||
|
.emoji-placeholder {
|
||||||
|
display: inline-block;
|
||||||
|
animation: jump 0.5s ease-in-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes jump {
|
||||||
|
0%, 100% { transform: translateY(0); }
|
||||||
|
50% { transform: translateY(-5px); }
|
||||||
|
}
|
||||||
|
/* 防止 UIkit Dropbar 初始闪烁 */
|
||||||
|
.uk-dropbar {
|
||||||
|
opacity: 0;
|
||||||
|
visibility: hidden;
|
||||||
|
transition: opacity 0.2s ease, visibility 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.uk-dropbar.uk-open {
|
||||||
|
opacity: 1;
|
||||||
|
visibility: visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
a.uk-button.uk-button-link {
|
||||||
|
text-transform: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 移动端优化:缩小字体和间距,避免右侧空白 */
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.uk-logo {
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
.uk-navbar-nav a {
|
||||||
|
font-size: 0.78rem;
|
||||||
|
padding: 0 4px;
|
||||||
|
}
|
||||||
|
.emoji-placeholder {
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
/* 移动端用户名限宽省略,避免长英文用户名撑爆顶栏 */
|
||||||
|
.tb-nav-username {
|
||||||
|
max-width: 64px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
display: inline-block;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<!-- 深色模式:html[data-theme="dark"] 时覆盖 UIkit 3.3.3 编译主题的关键颜色 -->
|
||||||
|
<style>
|
||||||
|
html[data-theme="dark"] {
|
||||||
|
--tb-bg: #1a1d23;
|
||||||
|
--tb-surface: #242830;
|
||||||
|
--tb-surface-2: #2d323c;
|
||||||
|
--tb-border: #3a404c;
|
||||||
|
--tb-text: #d8dce4;
|
||||||
|
--tb-text-muted: #8b93a1;
|
||||||
|
--tb-primary: #5c8dff;
|
||||||
|
}
|
||||||
|
/* 根元素与 body 一起覆盖,确保整个视口(含内容不足一屏时的空白区)都是深色背景 */
|
||||||
|
html[data-theme="dark"],
|
||||||
|
html[data-theme="dark"] body {
|
||||||
|
background-color: var(--tb-bg) !important;
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
}
|
||||||
|
/* 通用表面容器 */
|
||||||
|
html[data-theme="dark"] .uk-card,
|
||||||
|
html[data-theme="dark"] .uk-card-default,
|
||||||
|
html[data-theme="dark"] .uk-card-secondary,
|
||||||
|
html[data-theme="dark"] .uk-dropbar,
|
||||||
|
html[data-theme="dark"] .uk-navbar-dropdown,
|
||||||
|
html[data-theme="dark"] .uk-modal-dialog,
|
||||||
|
html[data-theme="dark"] .uk-dropdown,
|
||||||
|
html[data-theme="dark"] .uk-offcanvas-bar,
|
||||||
|
html[data-theme="dark"] .uk-section,
|
||||||
|
html[data-theme="dark"] .uk-tile,
|
||||||
|
html[data-theme="dark"] .uk-panel,
|
||||||
|
html[data-theme="dark"] .uk-background-default,
|
||||||
|
html[data-theme="dark"] .uk-search-default .uk-search-input {
|
||||||
|
background-color: var(--tb-surface) !important;
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-navbar-container {
|
||||||
|
background-color: var(--tb-surface) !important;
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-navbar-nav > li > a,
|
||||||
|
html[data-theme="dark"] .uk-card a,
|
||||||
|
html[data-theme="dark"] .uk-link,
|
||||||
|
html[data-theme="dark"] a.uk-button-link,
|
||||||
|
html[data-theme="dark"] .uk-navbar-dropdown-nav > li > a,
|
||||||
|
html[data-theme="dark"] .uk-dropdown-nav > li > a,
|
||||||
|
html[data-theme="dark"] .uk-list a {
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-navbar-nav > li > a:hover,
|
||||||
|
html[data-theme="dark"] .uk-card a:hover,
|
||||||
|
html[data-theme="dark"] .uk-navbar-dropdown-nav > li > a:hover,
|
||||||
|
html[data-theme="dark"] .uk-dropdown-nav > li > a:hover {
|
||||||
|
color: var(--tb-primary) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-input,
|
||||||
|
html[data-theme="dark"] .uk-textarea,
|
||||||
|
html[data-theme="dark"] .uk-select {
|
||||||
|
background-color: var(--tb-surface-2) !important;
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
border-color: var(--tb-border) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-input:focus,
|
||||||
|
html[data-theme="dark"] .uk-textarea:focus,
|
||||||
|
html[data-theme="dark"] .uk-select:focus {
|
||||||
|
border-color: var(--tb-primary) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-text-muted,
|
||||||
|
html[data-theme="dark"] .uk-text-meta,
|
||||||
|
html[data-theme="dark"] .uk-text-secondary,
|
||||||
|
html[data-theme="dark"] .uk-text-muted a,
|
||||||
|
html[data-theme="dark"] .uk-text-small.uk-text-muted {
|
||||||
|
color: var(--tb-text-muted) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-divider-icon::after,
|
||||||
|
html[data-theme="dark"] hr,
|
||||||
|
html[data-theme="dark"] .uk-table th,
|
||||||
|
html[data-theme="dark"] .uk-table td,
|
||||||
|
html[data-theme="dark"] .uk-list-divider > li:nth-child(n+2) {
|
||||||
|
border-color: var(--tb-border) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-button-default {
|
||||||
|
background-color: var(--tb-surface-2) !important;
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
border-color: var(--tb-border) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-modal-title,
|
||||||
|
html[data-theme="dark"] h1, html[data-theme="dark"] h2, html[data-theme="dark"] h3,
|
||||||
|
html[data-theme="dark"] h4, html[data-theme="dark"] h5, html[data-theme="dark"] h6,
|
||||||
|
html[data-theme="dark"] .uk-card-title {
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-alert-warning,
|
||||||
|
html[data-theme="dark"] .uk-alert-danger,
|
||||||
|
html[data-theme="dark"] .uk-alert-success,
|
||||||
|
html[data-theme="dark"] .uk-alert-primary {
|
||||||
|
background-color: var(--tb-surface-2) !important;
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] #math-captcha-modal .uk-modal-dialog {
|
||||||
|
background-color: var(--tb-surface) !important;
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] #math-captcha-modal .captcha-equation-box {
|
||||||
|
background-color: var(--tb-surface-2) !important;
|
||||||
|
border-color: var(--tb-border) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] #math-captcha-modal .math-captcha-modal-question {
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] #math-captcha-modal #captcha-modal-answer {
|
||||||
|
background-color: var(--tb-surface) !important;
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
border-color: var(--tb-border) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] #math-captcha-modal #captcha-modal-answer::placeholder {
|
||||||
|
color: var(--tb-text-muted) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] #math-captcha-modal .uk-text-meta,
|
||||||
|
html[data-theme="dark"] #math-captcha-modal #captcha-modal-refresh {
|
||||||
|
color: var(--tb-text-muted) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] #math-captcha-modal #captcha-modal-refresh:hover {
|
||||||
|
color: var(--tb-primary) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-label {
|
||||||
|
color: #fff !important;
|
||||||
|
}
|
||||||
|
/* 自定义组件(探索页推荐卡片等)深色覆盖 */
|
||||||
|
html[data-theme="dark"] .recommend-card,
|
||||||
|
html[data-theme="dark"] .recommend-card:hover {
|
||||||
|
background-color: var(--tb-surface-2) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .explore-name a {
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .explore-name a:hover {
|
||||||
|
color: var(--tb-primary) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .explore-intro {
|
||||||
|
color: var(--tb-text-muted) !important;
|
||||||
|
}
|
||||||
|
/* 切换按钮图标切换 */
|
||||||
|
#theme-toggle .tb-icon-dark, #theme-toggle-mobile .tb-icon-dark { display: none; }
|
||||||
|
html[data-theme="dark"] #theme-toggle .tb-icon-light,
|
||||||
|
html[data-theme="dark"] #theme-toggle-mobile .tb-icon-light { display: none; }
|
||||||
|
html[data-theme="dark"] #theme-toggle .tb-icon-dark,
|
||||||
|
html[data-theme="dark"] #theme-toggle-mobile .tb-icon-dark { display: inline; }
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<!-- 顶栏自适应:导航全部直接显示,窄屏时分级缩小字号/间距,保证英文/日文等长文字不溢出 -->
|
||||||
|
<style>
|
||||||
|
.uk-navbar-nav a {
|
||||||
|
font-size: 0.95rem;
|
||||||
|
padding: 0 10px;
|
||||||
|
}
|
||||||
|
/* 未登录移动端占位:桌面端隐藏,仅 ≤640px 显示(见下方 media 查询)。
|
||||||
|
桌面端布局与改动前完全一致,不受影响。 */
|
||||||
|
.tb-mobile-balancer { display: none; }
|
||||||
|
/* 桌面端保持 UIkit 原生居中三列布局(无需额外 CSS) */
|
||||||
|
.tb-navbar .uk-logo {
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
@media (max-width: 1200px) {
|
||||||
|
.uk-navbar-nav a {
|
||||||
|
font-size: 0.88rem;
|
||||||
|
padding: 0 8px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (max-width: 1000px) {
|
||||||
|
.uk-navbar-nav a {
|
||||||
|
font-size: 0.82rem;
|
||||||
|
padding: 0 6px;
|
||||||
|
}
|
||||||
|
.uk-logo {
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
/* 登录用户名限宽,过长省略号截断 */
|
||||||
|
.tb-nav-username {
|
||||||
|
max-width: 110px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
display: inline-block;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (max-width: 800px) {
|
||||||
|
.uk-navbar-nav a {
|
||||||
|
font-size: 0.78rem;
|
||||||
|
padding: 0 4px;
|
||||||
|
}
|
||||||
|
.uk-logo {
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
.tb-nav-username {
|
||||||
|
max-width: 80px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/* 手机端(≤640px):沿用 UIkit 桌面端 navbar 的原生三列定位。
|
||||||
|
不再重写 .uk-navbar-center / center-left / center-right 的定位,
|
||||||
|
避免 logo 被挤到下一行;底部语言与深色模式按钮仍由下方独立栏承载。 */
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.tb-navbar {
|
||||||
|
position: relative;
|
||||||
|
min-height: 56px;
|
||||||
|
overflow: visible;
|
||||||
|
}
|
||||||
|
.tb-navbar > .uk-navbar-center {
|
||||||
|
position: relative !important;
|
||||||
|
top: auto !important;
|
||||||
|
left: auto !important;
|
||||||
|
right: auto !important;
|
||||||
|
bottom: auto !important;
|
||||||
|
transform: none !important;
|
||||||
|
display: flex !important;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 100%;
|
||||||
|
min-height: 56px;
|
||||||
|
white-space: nowrap;
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
}
|
||||||
|
.tb-navbar .uk-navbar-center-left,
|
||||||
|
.tb-navbar .uk-navbar-center-right {
|
||||||
|
position: static !important;
|
||||||
|
top: auto !important;
|
||||||
|
left: auto !important;
|
||||||
|
right: auto !important;
|
||||||
|
bottom: auto !important;
|
||||||
|
transform: none !important;
|
||||||
|
display: flex !important;
|
||||||
|
align-items: center;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.tb-navbar .uk-navbar-center-left > div,
|
||||||
|
.tb-navbar .uk-navbar-center-right > div {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.tb-navbar .uk-navbar-nav {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
}
|
||||||
|
.tb-navbar .uk-navbar-nav > li > a,
|
||||||
|
.tb-navbar .uk-logo {
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
/* 未登录:移动端显示与「我的」等宽的隐藏占位,使左栏「探索+占位」与
|
||||||
|
右栏「注册/登录」两项等宽,logo 真正居中,左右视觉平衡 */
|
||||||
|
.tb-mobile-balancer { display: block; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<!-- 标签样式的按钮(管理页置顶等):
|
||||||
|
尺寸完全继承 .uk-label(font-size/padding/line-height/text-transform 等),
|
||||||
|
仅覆盖 button 元素特有的默认样式(边框/字体族/光标等),保证与相邻 span 标签完全一致。 -->
|
||||||
|
<style>
|
||||||
|
.tb-label-btn {
|
||||||
|
border: none !important;
|
||||||
|
cursor: pointer;
|
||||||
|
font-family: inherit;
|
||||||
|
margin: 0;
|
||||||
|
vertical-align: middle;
|
||||||
|
outline: none;
|
||||||
|
background-image: none;
|
||||||
|
box-sizing: border-box;
|
||||||
|
-webkit-appearance: none;
|
||||||
|
appearance: none;
|
||||||
|
}
|
||||||
|
.tb-label-btn:hover {
|
||||||
|
opacity: 0.85;
|
||||||
|
}
|
||||||
|
/* 公开页置顶小图标:仅一个图钉,不占行高、不影响原布局 */
|
||||||
|
.tb-pin-flag {
|
||||||
|
font-size: 0.9em;
|
||||||
|
margin-right: 4px;
|
||||||
|
vertical-align: -1px;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<!-- 页脚统计加载动画:替代 fontawesome 的 fa-spinner(纯 CSS,不引字体库) -->
|
||||||
|
<style>
|
||||||
|
.tb-spinner {
|
||||||
|
display: inline-block;
|
||||||
|
width: 0.9em;
|
||||||
|
height: 0.9em;
|
||||||
|
border: 2px solid rgba(128, 128, 128, 0.25);
|
||||||
|
border-top-color: #666;
|
||||||
|
border-radius: 50%;
|
||||||
|
vertical-align: -2px;
|
||||||
|
animation: tb-spin 0.8s linear infinite;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .tb-spinner {
|
||||||
|
border-color: rgba(255, 255, 255, 0.2);
|
||||||
|
border-top-color: #bbb;
|
||||||
|
}
|
||||||
|
@keyframes tb-spin {
|
||||||
|
to { transform: rotate(360deg); }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<!-- Markdown 渲染排版(问题/回答/追问正文,左对齐以保留排版格式) -->
|
||||||
|
<style>
|
||||||
|
/* 纯文本列表:保留换行与连续空格(pre-wrap),不渲染 Markdown 大字号/彩色 */
|
||||||
|
.tb-preline {
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
/* 纯文本列表:超过 5 行截断并显示省略号(不足 5 行则完整显示) */
|
||||||
|
.tb-clamp-5 {
|
||||||
|
display: -webkit-box;
|
||||||
|
-webkit-box-orient: vertical;
|
||||||
|
-webkit-line-clamp: 5;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.md-body {
|
||||||
|
line-height: 1.7;
|
||||||
|
text-align: left;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
.md-body p { margin: 0.5em 0; }
|
||||||
|
.md-body h1, .md-body h2, .md-body h3,
|
||||||
|
.md-body h4, .md-body h5, .md-body h6 {
|
||||||
|
margin: 0.8em 0 0.4em;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
.md-body ul, .md-body ol { padding-left: 1.6em; margin: 0.5em 0; }
|
||||||
|
.md-body li { margin: 0.2em 0; }
|
||||||
|
.md-body blockquote {
|
||||||
|
border-left: 3px solid #d3d1c7;
|
||||||
|
margin: 0.6em 0;
|
||||||
|
padding: 0.2em 1em;
|
||||||
|
color: #5f5e5a;
|
||||||
|
}
|
||||||
|
.md-body pre {
|
||||||
|
background: #f5f5f5;
|
||||||
|
padding: 0.8em 1em;
|
||||||
|
border-radius: 6px;
|
||||||
|
overflow-x: auto;
|
||||||
|
margin: 0.6em 0;
|
||||||
|
}
|
||||||
|
.md-body code {
|
||||||
|
background: #f0f0f0;
|
||||||
|
padding: 0.1em 0.35em;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 0.9em;
|
||||||
|
}
|
||||||
|
.md-body pre code { background: none; padding: 0; }
|
||||||
|
.md-body img { max-width: 100%; height: auto; }
|
||||||
|
.md-body table { border-collapse: collapse; margin: 0.6em 0; }
|
||||||
|
.md-body th, .md-body td {
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
padding: 0.4em 0.8em;
|
||||||
|
}
|
||||||
|
.md-body hr { margin: 1em 0; }
|
||||||
|
html[data-theme="dark"] .md-body blockquote {
|
||||||
|
border-color: #3a404c;
|
||||||
|
color: #8b93a1;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .md-body pre,
|
||||||
|
html[data-theme="dark"] .md-body code { background: #2d323c; }
|
||||||
|
html[data-theme="dark"] .md-body th,
|
||||||
|
html[data-theme="dark"] .md-body td { border-color: #3a404c; }
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<!-- 投票结果占比条:UIkit 3 已无 .uk-progressbar 类(那是 UIkit 2 的),
|
||||||
|
模板用 <div class="uk-progress"><div class="uk-progressbar"> 结构,需补一套填充样式,
|
||||||
|
否则内层填充无高度/背景,所有占比条都只剩外层灰色轨道,看起来一模一样。 -->
|
||||||
|
<style>
|
||||||
|
.uk-progress {
|
||||||
|
-webkit-appearance: none;
|
||||||
|
-moz-appearance: none;
|
||||||
|
appearance: none;
|
||||||
|
height: 10px;
|
||||||
|
margin: 0;
|
||||||
|
border: none;
|
||||||
|
border-radius: 6px;
|
||||||
|
background-color: #e5e5e5;
|
||||||
|
overflow: hidden;
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
.uk-progressbar {
|
||||||
|
display: block;
|
||||||
|
height: 100%;
|
||||||
|
background-color: #1e87f0;
|
||||||
|
border-radius: 6px 0 0 6px;
|
||||||
|
transition: width 0.3s ease;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-progress {
|
||||||
|
background-color: var(--tb-border);
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-progressbar {
|
||||||
|
background-color: var(--tb-primary);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<!-- 移动端底部操作栏:固定底栏承载语言切换与深色模式,桌面端隐藏 -->
|
||||||
|
<style>
|
||||||
|
#tb-mobile-utils {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
/* 顶栏不再容纳语言/深色按钮,恢复原有导航空间 */
|
||||||
|
.tb-nav-utils {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
/* 手机端隐藏登录用户名(左边仅保留"探索"),保证 logo 居中、
|
||||||
|
两侧各不超过 2 个短按钮,避免用户名宽度挤压布局 */
|
||||||
|
.tb-nav-username {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
/* 固定底部操作栏 */
|
||||||
|
#tb-mobile-utils {
|
||||||
|
display: flex;
|
||||||
|
position: fixed;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
z-index: 1000;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 8px 12px calc(8px + env(safe-area-inset-bottom));
|
||||||
|
background: rgba(255, 255, 255, 0.92);
|
||||||
|
-webkit-backdrop-filter: blur(8px);
|
||||||
|
backdrop-filter: blur(8px);
|
||||||
|
box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.08);
|
||||||
|
}
|
||||||
|
#tb-mobile-utils .uk-select {
|
||||||
|
width: 110px;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] #tb-mobile-utils {
|
||||||
|
background: rgba(36, 40, 48, 0.92);
|
||||||
|
box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.4);
|
||||||
|
}
|
||||||
|
/* 给页面底部预留空间,避免页脚内容被固定底栏遮挡 */
|
||||||
|
body {
|
||||||
|
padding-bottom: 56px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<!-- Commit 6d0a3ad -->
|
||||||
|
<meta property="og:site_name" content="{{ t .LangCode "site.title" }}" />
|
||||||
|
<meta property="og:type" content="website" />
|
||||||
|
<meta property="og:title" content="{{ if .IsUserPage }}{{ .PageUser.Name }} - {{ t .LangCode "site.title" }}{{ else }}{{ t .LangCode "site.title" }}{{ end }}" />
|
||||||
|
<meta property="og:url" content="{{ .ExternalURL }}{{ .CurrentURI }}" />
|
||||||
|
<meta property="og:description" content="{{ if .IsUserPage }}{{ .PageUser.Name }} - {{ t .LangCode "site.description" }}{{ else }}{{ t .LangCode "site.description" }}{{ end }}" />
|
||||||
|
{{ if .NoIndex }}<meta name="robots" content="noindex">{{ end }}
|
||||||
|
{{ if .IsUserPage }}
|
||||||
|
<meta property="og:image" content="{{ .PageUser.Avatar }}?og-image=1" />
|
||||||
|
<meta property="og:image:alt" content="{{ .PageUser.Name }}" />
|
||||||
|
<meta itemprop="image" content="{{ .PageUser.Avatar }}?og-image=1"/>
|
||||||
|
<meta name="msapplication-TileImage" content="{{ .PageUser.Avatar }}"/>
|
||||||
|
<link rel="shortcut icon" href="{{ .PageUser.Avatar }}?og-image=1"/>
|
||||||
|
<link rel="apple-touch-icon" href="{{ .PageUser.Avatar }}?og-image=1"/>
|
||||||
|
<link rel="icon" sizes="192x192" href="{{ .PageUser.Avatar }}?og-image=1">
|
||||||
|
<meta name="twitter:image:src" content="{{ .PageUser.Avatar }}?og-image=1" />
|
||||||
|
{{ else }}
|
||||||
|
<meta itemprop="image" content="https://r2.337845818.best/tamabox/tamabox_low.png"/>
|
||||||
|
<meta name="msapplication-TileImage" content="https://r2.337845818.best/tamabox/tamabox_low.png"/>
|
||||||
|
<link rel="shortcut icon" href="https://r2.337845818.best/tamabox/tamabox_low.png" />
|
||||||
|
<link rel="apple-touch-icon" href="https://r2.337845818.best/tamabox/tamabox_low.png"/>
|
||||||
|
<link rel="icon" sizes="192x192" href="https://r2.337845818.best/tamabox/tamabox_low.png">
|
||||||
|
<meta name="twitter:image:src" content="https://r2.337845818.best/tamabox/tamabox_low.png" />
|
||||||
|
{{ end }}
|
||||||
|
|
||||||
|
<!-- Google and Bing -->
|
||||||
|
<meta name="google-site-verification" content="fEPwRRJfiGsgwc5SINBQwZhPK8F0cwRaOvRx0YRurI4" />
|
||||||
|
<meta name="msvalidate.01" content="2F185E8E63C93635F50B3574F3B31E42" />
|
||||||
|
<script defer src="https://mami.tama.guru/tamami.js" data-website-id="c42ebe8b-9281-4da0-83a4-8f18b3e710fe"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<nav class="uk-navbar-container uk-margin tb-navbar" uk-navbar>
|
||||||
|
<div class="uk-navbar-center">
|
||||||
|
<div class="uk-navbar-center-left">
|
||||||
|
<div>
|
||||||
|
<ul class="uk-navbar-nav">
|
||||||
|
<!-- 探索链接,始终显示 -->
|
||||||
|
<li><a href="/explore">{{t .LangCode "nav.explore"}}</a></li>
|
||||||
|
{{ if .IsLogged }}
|
||||||
|
<!-- 我的:进入自己的提问箱主页(与右侧「提问/设置」形成左右均衡) -->
|
||||||
|
<li><a href="/_/{{ .LoggedUser.Domain }}">{{t .LangCode "nav.mine"}}</a></li>
|
||||||
|
{{ else }}
|
||||||
|
<!-- 移动端占位:未登录时左栏仅「探索」一项,与右栏「注册/登录」两项不等宽,
|
||||||
|
导致 logo 整体被拉向左(偏左)。移动端(≤640px)显示一个与「我的」等宽的隐藏占位,
|
||||||
|
使左右视觉平衡;桌面端由 .tb-mobile-balancer 隐藏,保持原布局完全不变。 -->
|
||||||
|
<li class="tb-mobile-balancer" aria-hidden="true"><a tabindex="-1" style="visibility:hidden">{{t .LangCode "nav.mine"}}</a></li>
|
||||||
|
{{ end }}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<a class="uk-navbar-item uk-logo" href="/"><span class="emoji-placeholder" aria-label="random animal">🐺</span>{{t .LangCode "site.logoSuffix"}}</a>
|
||||||
|
|
||||||
|
<div class="uk-navbar-center-right">
|
||||||
|
<div>
|
||||||
|
{{ if .IsLogged }}
|
||||||
|
<ul class="uk-navbar-nav">
|
||||||
|
<li><a href="/user/questions">{{t .LangCode "nav.ask"}}</a></li>
|
||||||
|
</ul>
|
||||||
|
<ul class="uk-navbar-nav">
|
||||||
|
<li><a href="/user/profile">{{t .LangCode "nav.settings"}}</a></li>
|
||||||
|
</ul>
|
||||||
|
{{ else}}
|
||||||
|
<ul class="uk-navbar-nav">
|
||||||
|
<li><a href="/register">{{t .LangCode "nav.register"}}</a></li>
|
||||||
|
</ul>
|
||||||
|
<ul class="uk-navbar-nav">
|
||||||
|
<li><a href="/login">{{t .LangCode "nav.login"}}</a></li>
|
||||||
|
</ul>
|
||||||
|
{{ end }}
|
||||||
|
{{ if not .IsUserPage }}
|
||||||
|
<!-- 语言切换(紧凑图标,点击展开;移动端隐藏,见底部操作栏) -->
|
||||||
|
<ul class="uk-navbar-nav tb-nav-utils">
|
||||||
|
<li>
|
||||||
|
<a href="#" aria-label="{{t .LangCode "common.lang"}}" title="{{t .LangCode "common.lang"}}">🌐</a>
|
||||||
|
<div class="uk-navbar-dropdown" uk-drop="mode: click; pos: bottom-right">
|
||||||
|
<ul class="uk-nav uk-navbar-dropdown-nav">
|
||||||
|
{{ range .SupportedLangs }}
|
||||||
|
<li class="{{ if eq .Code $.LangCode }}uk-active{{ end }}">
|
||||||
|
<a href="/i18n/{{ .Code }}?to={{ urlquery $.CurrentURI }}">{{ .Name }}</a>
|
||||||
|
</li>
|
||||||
|
{{ end }}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
{{ end }}
|
||||||
|
<!-- 深色模式切换(紧凑图标;移动端隐藏,见底部操作栏) -->
|
||||||
|
<ul class="uk-navbar-nav tb-nav-utils">
|
||||||
|
<li>
|
||||||
|
<a href="#" id="theme-toggle" title="{{t .LangCode "common.theme"}}" aria-label="{{t .LangCode "common.theme"}}">
|
||||||
|
<span class="tb-icon-light">🌙</span><span class="tb-icon-dark">☀️</span>
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
document.addEventListener("DOMContentLoaded", function() {
|
||||||
|
const emojis = ["🐺","🐗","🐻","🐨","🐼","🐹","🐭","🐰","🦊","🐮","🐷","🐽","🐸","🐒","🦍","🐔","🐧","🐦","🐤","🐦⬛","🦅","🦉","🦇","🐴","🦄","🐝","🦎","🦖","🦕","🐙","🦑","🦐","🦞","🦀","🐡","🐠","🐟","🐬","🐳","🐋","🦈","🐊","🐅","🐆","🦓","🦍","🦧","🐘","🦛","🦏","🐪","🐫","🦒","🦘","🐃","🐂","🐄","🐎","🐖","🐏","🐑","🦙","🐐","🦌","🐕","🐩","🦮","🐕🦺","🐈","🐋","🐳","🐬","🐉","🐲"];
|
||||||
|
const placeholder = document.querySelector('.emoji-placeholder');
|
||||||
|
if (placeholder) {
|
||||||
|
placeholder.textContent = emojis[Math.floor(Math.random() * emojis.length)];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<!-- 移动端固定底部操作栏:语言切换 + 深色模式(桌面端隐藏) -->
|
||||||
|
<div id="tb-mobile-utils">
|
||||||
|
{{ if not .IsUserPage }}
|
||||||
|
<select id="mobile-lang-select" class="uk-select uk-form-small" aria-label="{{t .LangCode "common.lang"}}">
|
||||||
|
{{ range .SupportedLangs }}
|
||||||
|
<option value="{{ .Code }}" {{ if eq .Code $.LangCode }}selected{{ end }}>{{ .Name }}</option>
|
||||||
|
{{ end }}
|
||||||
|
</select>
|
||||||
|
{{ end }}
|
||||||
|
<button type="button" id="theme-toggle-mobile" class="uk-button uk-button-default uk-button-small"
|
||||||
|
title="{{t .LangCode "common.theme"}}" aria-label="{{t .LangCode "common.theme"}}">
|
||||||
|
<span class="tb-icon-light">🌙</span><span class="tb-icon-dark">☀️</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
// 深色模式:读取 cookie 应用主题,按钮切换并持久化
|
||||||
|
var THEME_COOKIE = 'theme';
|
||||||
|
function getTheme() {
|
||||||
|
var m = document.cookie.match(/(?:^|;\s*)theme=([^;]*)/);
|
||||||
|
return m ? m[1] : '';
|
||||||
|
}
|
||||||
|
function applyTheme(theme) {
|
||||||
|
if (theme === 'dark') {
|
||||||
|
document.documentElement.setAttribute('data-theme', 'dark');
|
||||||
|
} else {
|
||||||
|
document.documentElement.removeAttribute('data-theme');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function toggleTheme() {
|
||||||
|
var next = getTheme() === 'dark' ? 'light' : 'dark';
|
||||||
|
applyTheme(next);
|
||||||
|
var expires = new Date(Date.now() + 365 * 24 * 3600 * 1000).toUTCString();
|
||||||
|
document.cookie = THEME_COOKIE + '=' + next + '; path=/; max-age=' + (365 * 24 * 3600) + '; SameSite=Lax';
|
||||||
|
}
|
||||||
|
// 首屏前应用,避免闪烁
|
||||||
|
applyTheme(getTheme());
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
// 桌面顶栏按钮与移动端底部按钮都绑定
|
||||||
|
var buttons = document.querySelectorAll('#theme-toggle, #theme-toggle-mobile');
|
||||||
|
buttons.forEach(function(btn) {
|
||||||
|
btn.addEventListener('click', function(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
toggleTheme();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 移动端底部语言切换:onchange 跳转到 /i18n/{code},保留当前页面位置
|
||||||
|
var langSel = document.getElementById('mobile-lang-select');
|
||||||
|
if (langSel) {
|
||||||
|
langSel.addEventListener('change', function() {
|
||||||
|
if (!this.value) return;
|
||||||
|
var to = window.location.pathname + window.location.search;
|
||||||
|
window.location.href = '/i18n/' + encodeURIComponent(this.value) + '?to=' + encodeURIComponent(to);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{{ if .IsPixel }}
|
||||||
|
<div>
|
||||||
|
{{ else }}
|
||||||
|
<div class="uk-container uk-container-xsmall">
|
||||||
|
{{ end }}
|
||||||
|
|
||||||
|
{{ if eq .CaptchaType "math" }}
|
||||||
|
<!-- 算数验证码弹窗 --><div id="math-captcha-modal" uk-modal>
|
||||||
|
<div class="uk-modal-dialog uk-modal-body uk-text-center">
|
||||||
|
<h3 class="uk-modal-title">{{t .LangCode "captcha.title"}}</h3>
|
||||||
|
<p class="uk-text-meta">{{t .LangCode "captcha.hint"}}</p>
|
||||||
|
<div class="captcha-equation-box">
|
||||||
|
<span id="captcha-modal-question" class="math-captcha-modal-question">{{t .LangCode "captcha.loading"}}</span>
|
||||||
|
<input type="number" id="captcha-modal-answer" placeholder="?" autocomplete="off" inputmode="numeric">
|
||||||
|
</div>
|
||||||
|
<div style="margin-top:6px;">
|
||||||
|
<button type="button" class="uk-button uk-button-text uk-text-small" id="captcha-modal-refresh">{{t .LangCode "captcha.refresh"}}</button>
|
||||||
|
</div>
|
||||||
|
<div id="captcha-modal-error" class="uk-text-danger uk-text-small" style="display:none;min-height:20px;"></div>
|
||||||
|
<div class="uk-margin-small-top">
|
||||||
|
<button type="button" class="uk-button uk-button-primary" id="captcha-modal-submit">{{t .LangCode "captcha.submit"}}</button>
|
||||||
|
<button type="button" class="uk-button uk-button-default uk-modal-close">{{t .LangCode "common.cancel"}}</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
var CAPTCHA_I18N = {
|
||||||
|
loading: "{{t .LangCode "captcha.loading"}}",
|
||||||
|
loadFailed: "{{t .LangCode "captcha.loadFailed"}}",
|
||||||
|
loadRetry: "{{t .LangCode "captcha.loadRetry"}}",
|
||||||
|
inputAnswer: "{{t .LangCode "captcha.inputAnswer"}}",
|
||||||
|
wrongAnswer: "{{t .LangCode "captcha.wrongAnswer"}}",
|
||||||
|
verifyFailed: "{{t .LangCode "captcha.verifyFailed"}}",
|
||||||
|
needPassword: "{{t .LangCode "ask.needPassword"}}",
|
||||||
|
needEmail: "{{t .LangCode "ask.pleaseEmail"}}"
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var captchaId = '';
|
||||||
|
var pendingForm = null;
|
||||||
|
var pendingNeedPassword = false;
|
||||||
|
var verifying = false;
|
||||||
|
|
||||||
|
function fetchCaptcha() {
|
||||||
|
var qEl = document.getElementById('captcha-modal-question');
|
||||||
|
var errEl = document.getElementById('captcha-modal-error');
|
||||||
|
var ansEl = document.getElementById('captcha-modal-answer');
|
||||||
|
qEl.textContent = CAPTCHA_I18N.loading;
|
||||||
|
fetch('/api/captcha/generate')
|
||||||
|
.then(function(r) { return r.json(); })
|
||||||
|
.then(function(data) {
|
||||||
|
if (data.code === 0 && data.data) {
|
||||||
|
captchaId = data.data.id;
|
||||||
|
qEl.textContent = data.data.question;
|
||||||
|
if (errEl) errEl.style.display = 'none';
|
||||||
|
if (ansEl) { ansEl.value = ''; ansEl.focus(); }
|
||||||
|
} else {
|
||||||
|
qEl.textContent = CAPTCHA_I18N.loadFailed;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(function() {
|
||||||
|
qEl.textContent = CAPTCHA_I18N.loadRetry;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCSRFToken() {
|
||||||
|
var input = document.querySelector('input[name="_csrf"]');
|
||||||
|
return input ? input.value : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function doSubmit(form) {
|
||||||
|
// 将 captcha 答案填入隐藏字段
|
||||||
|
var ans = document.getElementById('captcha-modal-answer').value.trim();
|
||||||
|
var hidden = form.querySelector('[name="g-recaptcha-response"]');
|
||||||
|
if (hidden) hidden.value = captchaId + ':' + (ans || '0');
|
||||||
|
|
||||||
|
UIkit.modal('#math-captcha-modal').hide();
|
||||||
|
|
||||||
|
// 处理 AskPassword(提问箱密码)
|
||||||
|
if (pendingNeedPassword) {
|
||||||
|
UIkit.modal.prompt(CAPTCHA_I18N.needPassword, '', 'password')
|
||||||
|
.then(function(password) {
|
||||||
|
if (password) {
|
||||||
|
var pwInput = document.getElementById('ask_password_input');
|
||||||
|
if (pwInput) pwInput.value = password;
|
||||||
|
form.submit();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
form.submit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证按钮
|
||||||
|
document.getElementById('captcha-modal-submit').addEventListener('click', function() {
|
||||||
|
if (verifying) return;
|
||||||
|
var ans = document.getElementById('captcha-modal-answer').value.trim();
|
||||||
|
if (!ans) {
|
||||||
|
var errEl = document.getElementById('captcha-modal-error');
|
||||||
|
errEl.textContent = CAPTCHA_I18N.inputAnswer;
|
||||||
|
errEl.style.display = 'block';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
verifying = true;
|
||||||
|
fetch('/api/captcha/verify', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-CSRF-Token': getCSRFToken()
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ id: captchaId, answer: parseInt(ans, 10) })
|
||||||
|
})
|
||||||
|
.then(function(r) { return r.json(); })
|
||||||
|
.then(function(data) {
|
||||||
|
verifying = false;
|
||||||
|
if (data.correct) {
|
||||||
|
if (pendingForm) doSubmit(pendingForm);
|
||||||
|
} else {
|
||||||
|
var errEl = document.getElementById('captcha-modal-error');
|
||||||
|
errEl.textContent = CAPTCHA_I18N.wrongAnswer;
|
||||||
|
errEl.style.display = 'block';
|
||||||
|
fetchCaptcha(); // 自动刷新题目
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(function() {
|
||||||
|
verifying = false;
|
||||||
|
var errEl = document.getElementById('captcha-modal-error');
|
||||||
|
errEl.textContent = CAPTCHA_I18N.verifyFailed;
|
||||||
|
errEl.style.display = 'block';
|
||||||
|
fetchCaptcha();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 回车提交
|
||||||
|
document.getElementById('captcha-modal-answer').addEventListener('keydown', function(e) {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
document.getElementById('captcha-modal-submit').click();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 刷新按钮
|
||||||
|
document.getElementById('captcha-modal-refresh').addEventListener('click', fetchCaptcha);
|
||||||
|
|
||||||
|
// 拦截所有带 class="math-captcha-trigger" 的按钮
|
||||||
|
document.addEventListener('click', function(e) {
|
||||||
|
var btn = e.target.closest('.math-captcha-trigger');
|
||||||
|
if (!btn) return;
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
var form = btn.closest('form');
|
||||||
|
if (!form) return;
|
||||||
|
pendingForm = form;
|
||||||
|
|
||||||
|
// 检查是否需要提问密码
|
||||||
|
pendingNeedPassword = !!(form.querySelector('#ask_password_input'));
|
||||||
|
|
||||||
|
// 邮箱校验(提问页面)
|
||||||
|
var notifyCb = document.getElementById('notify-checkbox');
|
||||||
|
var emailInput = document.getElementById('email-input');
|
||||||
|
if (notifyCb && notifyCb.checked && emailInput && emailInput.value.trim() === '') {
|
||||||
|
UIkit.modal.alert(CAPTCHA_I18N.needEmail);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchCaptcha();
|
||||||
|
UIkit.modal('#math-captcha-modal').show();
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
{{ end }}
|
||||||
@@ -0,0 +1,309 @@
|
|||||||
|
{{template "base/header" .}}
|
||||||
|
<!-- 头像直连 R2:crossorigin 让 favicon 也以 CORS 模式请求,确保浏览器缓存的响应都带 ACAO;
|
||||||
|
?v=2 击穿历史上被「无 ACAO 响应」污染的缓存条目(R2 对无 Origin 请求的响应无 Vary,可缓存 31 天) -->
|
||||||
|
<link rel="shortcut icon" href="{{.PageUser.Avatar}}?v=2" crossorigin="anonymous"/>
|
||||||
|
<link rel="apple-touch-icon" href="{{.PageUser.Avatar}}?v=2" crossorigin="anonymous"/>
|
||||||
|
<link rel="icon" sizes="192x192" href="{{.PageUser.Avatar}}?v=2" crossorigin="anonymous">
|
||||||
|
<style>
|
||||||
|
/* 投票列表:与探索页"全部投票"一致的列表行样式 */
|
||||||
|
.profile-votes-list { display: grid; gap: 0; }
|
||||||
|
.profile-vote-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 16px;
|
||||||
|
min-width: 0;
|
||||||
|
padding: 14px 16px;
|
||||||
|
border-bottom: 1px solid var(--tb-border, #e9e9e9);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
.profile-vote-item:first-child { border-top: 1px solid var(--tb-border, #e9e9e9); }
|
||||||
|
.profile-vote-item:hover { background: var(--tb-surface-hover, #f8fbff); text-decoration: none; }
|
||||||
|
.profile-vote-content { min-width: 0; }
|
||||||
|
.profile-vote-title {
|
||||||
|
display: block;
|
||||||
|
overflow: hidden;
|
||||||
|
color: var(--tb-text, #333);
|
||||||
|
font-size: 0.98rem;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1.45;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.profile-vote-meta {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 7px;
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
.profile-vote-meta .uk-label { font-size: 0.72rem; line-height: 1.6; }
|
||||||
|
.profile-vote-action {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
color: var(--tb-primary, #1e87f0);
|
||||||
|
font-size: 0.82rem;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .profile-vote-item { border-color: var(--tb-border); }
|
||||||
|
html[data-theme="dark"] .profile-vote-title { color: var(--tb-text); }
|
||||||
|
html[data-theme="dark"] .profile-vote-item:hover { background: rgba(78, 168, 245, 0.10); }
|
||||||
|
/* 个人主页 Tab:与探索页一致的胶囊切换样式 */
|
||||||
|
/* 个人主页 Tab:全宽等分,置于主体顶部,作为一级导航(移动端整行可点) */
|
||||||
|
.profile-tabs {
|
||||||
|
display: flex;
|
||||||
|
gap: 4px;
|
||||||
|
padding: 4px;
|
||||||
|
margin-top: 20px;
|
||||||
|
margin-bottom: 18px;
|
||||||
|
border: 1px solid var(--tb-border, #e5e5e5);
|
||||||
|
border-radius: 9px;
|
||||||
|
background: var(--tb-surface-2, #fafafa);
|
||||||
|
}
|
||||||
|
.profile-tab {
|
||||||
|
flex: 1;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 9px 15px;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--tb-text-muted, #666);
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
transition: background 0.2s ease, color 0.2s ease;
|
||||||
|
}
|
||||||
|
.profile-tab:hover { color: var(--tb-primary, #1e87f0); }
|
||||||
|
.profile-tab.is-active {
|
||||||
|
background: var(--tb-surface, #fff);
|
||||||
|
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.10);
|
||||||
|
color: var(--tb-primary, #1e87f0);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
/* 功能关闭时置灰禁用的 Tab(如投票功能关闭) */
|
||||||
|
.profile-tab.is-disabled,
|
||||||
|
.profile-tab:disabled {
|
||||||
|
cursor: not-allowed;
|
||||||
|
color: var(--tb-text-muted, #999);
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
.profile-tab.is-disabled:hover { color: var(--tb-text-muted, #999); }
|
||||||
|
.profile-panel[hidden] { display: none !important; }
|
||||||
|
html[data-theme="dark"] .profile-tabs {
|
||||||
|
border-color: var(--tb-border);
|
||||||
|
background: var(--tb-surface-2);
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .profile-tab { color: var(--tb-text-muted); }
|
||||||
|
html[data-theme="dark"] .profile-tab.is-active { background: var(--tb-surface); color: var(--tb-primary); }
|
||||||
|
html[data-theme="dark"] .profile-tab.is-disabled { color: var(--tb-text-muted); opacity: 0.55; }
|
||||||
|
</style>
|
||||||
|
<div class="uk-card uk-card-default uk-text-center">
|
||||||
|
<div class="uk-flex uk-flex-center uk-flex-middle uk-background-cover uk-light" style="min-height: 260px;" data-src="{{ .PageUser.Background }}" uk-img>
|
||||||
|
<div class="uk-card-body">
|
||||||
|
<img class="uk-border-circle uk-box-shadow-large" src="{{ if .PageUser.Avatar }}{{ .PageUser.Avatar }}?v=2{{ else }}{{ .DefaultAvatar }}{{ end }}" crossorigin="anonymous" style="width: 100px; height: 100px; max-width: 100%; max-height: 100%;">
|
||||||
|
<h3 id="usernamecolor">{{ .PageUser.Name }}</h3>
|
||||||
|
<p id="introcolor">{{ .PageUser.Intro }}</p>
|
||||||
|
<div class="icon-container">
|
||||||
|
{{ if and .PageUser.Acfunlink (ne .PageUser.Acfunlink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Acfunlink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/ailicili.png" alt="acfunlink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
{{ if and .PageUser.Bililink (ne .PageUser.Bililink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Bililink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/bili.png" alt="bililink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
{{ if and .PageUser.Weibolink (ne .PageUser.Weibolink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Weibolink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/weibo.png" alt="weibolink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
{{ if and .PageUser.Xiaohongshulink (ne .PageUser.Xiaohongshulink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Xiaohongshulink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/xiaohongshu.png" alt="xiaohongshulink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
{{ if and .PageUser.Bloglink (ne .PageUser.Bloglink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Bloglink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/blog.png" alt="bloglink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
document.getElementById("usernamecolor").style.color = "{{.PageUser.Usernamecolor}}";
|
||||||
|
document.getElementById("introcolor").style.color = "{{.PageUser.Introcolor}}";
|
||||||
|
</script>
|
||||||
|
<div>
|
||||||
|
<div class="uk-card uk-card-default uk-card-small uk-card-body">
|
||||||
|
{{ if .CanAsk }}
|
||||||
|
<!-- jQuery 已改为按需加载:defer 按文档顺序先于 easy.qrcode 执行,保证就绪 -->
|
||||||
|
<script defer src="https://r2.337845818.best/tamabox/cdn/lib/jquery/3.7.1/jquery.min.js"></script>
|
||||||
|
<script defer src='https://r2.337845818.best/tamabox/cdn/js/remake/easy.qrcode.min.js' type="text/javascript" charset="utf-8"></script>
|
||||||
|
<center><div id="boxqrimg"></div></center>
|
||||||
|
<script type="text/javascript">
|
||||||
|
document.addEventListener('DOMContentLoaded', function () {
|
||||||
|
var options = {
|
||||||
|
text: window.location.href,
|
||||||
|
width: 200,
|
||||||
|
height: 200,
|
||||||
|
// 与 Profile 编辑器保持一致:仅当启用自定义前景色时,才把 Qrcodebackcolor 作为前景色;
|
||||||
|
// 否则强制黑色 #000000,避免未勾选却显示自定义前景色、与 Profile 预览不一致。
|
||||||
|
colorDark: ({{.PageUser.UseCustomQRColor}} ? "{{.PageUser.Qrcodebackcolor}}" : "#000000") || "#000000",
|
||||||
|
colorLight: "{{.PageUser.Qrcodecolor}}" || "#FFFFFF",
|
||||||
|
dotScale: parseFloat("{{.PageUser.Dotscale}}") || 0.4,
|
||||||
|
dotScaleTiming: parseFloat("{{.PageUser.Dotscale}}") || 0.4,
|
||||||
|
dotScaleA: parseFloat("{{.PageUser.Dotscale}}") || 0.4,
|
||||||
|
correctLevel: QRCode.CorrectLevel.H,
|
||||||
|
logo: (function () {
|
||||||
|
// ?v=2:击穿曾被无 ACAO 响应污染的浏览器缓存条目;仅对 http(s) 绝对地址追加
|
||||||
|
var a = "{{.PageUser.Avatar}}" || "{{.DefaultAvatar}}";
|
||||||
|
return a ? (a.indexOf("http") === 0 ? a + "?v=2" : a) : undefined;
|
||||||
|
})(),
|
||||||
|
logoWidth: 60,
|
||||||
|
logoHeight: 60,
|
||||||
|
logoBackgroundTransparent: true,
|
||||||
|
// 直连 R2 等跨域图片须以 CORS 模式加载,canvas 才不被污染、可正常导出
|
||||||
|
crossOrigin: 'anonymous',
|
||||||
|
backgroundImage: ("{{.PageUser.BackgroundImage}}" ? "{{.PageUser.BackgroundImage}}" : undefined),
|
||||||
|
backgroundImageAlpha: parseFloat("{{.PageUser.Backgroundimagealpha}}") || 0.8,
|
||||||
|
autoColor: false,
|
||||||
|
PO: "{{.PageUser.Qrcodepdpcolor}}" || "#000000",
|
||||||
|
PI: "{{.PageUser.Qrcodepdpcolor}}" || "#000000",
|
||||||
|
AO: '',
|
||||||
|
AI: '',
|
||||||
|
timing: "{{.PageUser.Qrcodepdpcolor}}" || "#000000"
|
||||||
|
};
|
||||||
|
new QRCode(document.getElementById("boxqrimg"), options);
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<p class="uk-text-center uk-text-small">{{t .LangCode "ask.scan" .PageUser.Name}}<br>{{ if .RegisterOnlyAsk }}{{t .LangCode "ask.registerOnly"}}{{ else }}{{t .LangCode "ask.anonymous"}}{{ end }}</p>
|
||||||
|
|
||||||
|
<div class="uk-text-center uk-margin-small-top">
|
||||||
|
<a id="share-btn" href="/_/{{ .PageUser.Domain }}/share-card" download class="uk-button uk-button-default uk-button-small">
|
||||||
|
📤 {{t .LangCode "ask.share"}}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="share-loading-overlay" style="display:none; position: fixed; top:0; left:0; width:100%; height:100%; background: rgba(255,255,255,0.85); z-index:9999;">
|
||||||
|
<div style="display:flex; flex-direction:column; align-items:center; justify-content:center; height:100%;">
|
||||||
|
<div uk-spinner="ratio: 2" class="uk-margin-bottom"></div>
|
||||||
|
<p class="uk-text-large uk-text-muted">{{t .LangCode "ask.generating"}}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var btn = document.getElementById('share-btn');
|
||||||
|
var overlay = document.getElementById('share-loading-overlay');
|
||||||
|
if (!btn || !overlay) return;
|
||||||
|
btn.addEventListener('click', function(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
overlay.style.display = 'block';
|
||||||
|
btn.style.pointerEvents = 'none';
|
||||||
|
fetch(btn.href)
|
||||||
|
.then(function(response) {
|
||||||
|
if (!response.ok) throw new Error('{{t .LangCode "ask.networkError"}}');
|
||||||
|
return response.blob();
|
||||||
|
})
|
||||||
|
.then(function(blob) {
|
||||||
|
var url = URL.createObjectURL(blob);
|
||||||
|
var a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = '{{t .LangCode "ask.shareFilename"}}';
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
setTimeout(function() {
|
||||||
|
document.body.removeChild(a);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}, 100);
|
||||||
|
})
|
||||||
|
.catch(function(err) {
|
||||||
|
alert('{{t .LangCode "ask.genFailed"}}');
|
||||||
|
console.error(err);
|
||||||
|
})
|
||||||
|
.finally(function() {
|
||||||
|
overlay.style.display = 'none';
|
||||||
|
btn.style.pointerEvents = 'auto';
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
{{ end }}
|
||||||
|
{{template "base/alert" .}}
|
||||||
|
|
||||||
|
<!-- 提问 / 投票 切换:默认显示提问,支持 ?tab=votes 直达(服务端初始态)与 #votes hash 覆盖 -->
|
||||||
|
<div class="profile-tabs" role="tablist">
|
||||||
|
<button type="button" class="profile-tab{{ if eq .ActiveProfileTab "questions" }} is-active{{ end }}" data-profile-tab="questions" role="tab" aria-selected="{{ if eq .ActiveProfileTab "questions" }}true{{ else }}false{{ end }}">{{t .LangCode "explore.questionsTab"}}</button>
|
||||||
|
{{ if .VoteEnabled }}
|
||||||
|
<button type="button" class="profile-tab{{ if eq .ActiveProfileTab "votes" }} is-active{{ end }}" data-profile-tab="votes" role="tab" aria-selected="{{ if eq .ActiveProfileTab "votes" }}true{{ else }}false{{ end }}">{{t .LangCode "explore.votesTab"}}</button>
|
||||||
|
{{ else }}
|
||||||
|
<!-- 投票功能关闭:保留 Tab 展示但置灰禁用,hover 提示原因 -->
|
||||||
|
<button type="button" class="profile-tab is-disabled" disabled aria-disabled="true" uk-tooltip="{{ .VoteClosedMessage }}">{{t .LangCode "explore.votesTab"}} <span uk-icon="icon: lock; ratio: 0.8"></span></button>
|
||||||
|
{{ end }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="profile-panel" data-profile-panel="questions"{{ if eq .ActiveProfileTab "votes" }} hidden{{ end }}>
|
||||||
|
{{template "question/new-question-template" .}}
|
||||||
|
|
||||||
|
{{ if ne (len .PageQuestions) 0 }}
|
||||||
|
<p class="uk-text-left uk-text-muted uk-text-small">{{t .LangCode "ask.history" .PageUser.Name}} ({{ .AnsweredCount }})</p>
|
||||||
|
{{ template "question/history-template" . }}
|
||||||
|
{{ end }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="profile-panel" data-profile-panel="votes"{{ if ne .ActiveProfileTab "votes" }} hidden{{ end }}>
|
||||||
|
{{ if .PageVotes }}
|
||||||
|
<!-- 匿名投票板块:箱主"进行中"的公开投票(列表行样式,与探索页"全部投票"一致) -->
|
||||||
|
<div class="profile-votes-list">
|
||||||
|
{{ range .PageVotes }}
|
||||||
|
<a href="/vote/{{ .LinkToken }}" class="profile-vote-item">
|
||||||
|
<div class="profile-vote-content">
|
||||||
|
<span class="profile-vote-title" title="{{ .Title }}">{{ .Title }}</span>
|
||||||
|
<span class="profile-vote-meta">
|
||||||
|
{{ if eq .Type "single" }}<span class="uk-label uk-label-primary">{{t $.LangCode "vote.typeSingle"}}</span>{{ end }}
|
||||||
|
{{ if eq .Type "multiple" }}<span class="uk-label uk-label-primary">{{t $.LangCode "vote.typeMultiple"}}</span>{{ end }}
|
||||||
|
{{ if eq .Type "rating" }}<span class="uk-label uk-label-primary">{{t $.LangCode "vote.typeRating"}}</span>{{ end }}
|
||||||
|
{{ if eq .Type "rank" }}<span class="uk-label uk-label-primary">{{t $.LangCode "vote.typeRank"}}</span>{{ end }}
|
||||||
|
{{ if eq .Type "form" }}<span class="uk-label uk-label-primary">{{t $.LangCode "vote.typeForm"}}</span>{{ end }}
|
||||||
|
<span class="uk-text-meta">{{ .CreatedAt.Format "2006-01-02" }}</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span class="profile-vote-action">{{t $.LangCode "vote.page.goVote"}} <span uk-icon="icon: arrow-right; ratio: .8"></span></span>
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
</div>
|
||||||
|
{{ else }}
|
||||||
|
<div class="uk-alert uk-alert-primary uk-margin-remove-top">{{t .LangCode "explore.noVotes"}}</div>
|
||||||
|
{{ end }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
var tabs = document.querySelectorAll('[data-profile-tab]');
|
||||||
|
var panels = document.querySelectorAll('[data-profile-panel]');
|
||||||
|
function showPanel(name) {
|
||||||
|
tabs.forEach(function(tab) {
|
||||||
|
var active = tab.dataset.profileTab === name;
|
||||||
|
tab.classList.toggle('is-active', active);
|
||||||
|
tab.setAttribute('aria-selected', active ? 'true' : 'false');
|
||||||
|
});
|
||||||
|
panels.forEach(function(panel) {
|
||||||
|
panel.hidden = panel.dataset.profilePanel !== name;
|
||||||
|
});
|
||||||
|
if (window.history && window.history.replaceState) {
|
||||||
|
window.history.replaceState({}, document.title, window.location.pathname + window.location.search + (name === 'votes' ? '#votes' : ''));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tabs.forEach(function(tab) {
|
||||||
|
tab.addEventListener('click', function() { showPanel(tab.dataset.profileTab); });
|
||||||
|
});
|
||||||
|
// 仅当投票 Tab 可点击(功能开启)时才响应 #votes hash,避免投票关闭时切到空面板
|
||||||
|
if (window.location.hash === '#votes' && document.querySelector('[data-profile-tab="votes"]')) {
|
||||||
|
showPanel('votes');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
{{template "base/footer" .}}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,105 @@
|
|||||||
|
{{template "base/header" .}}
|
||||||
|
<!--<link rel="stylesheet" href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-y/uikit/3.3.3/css/uikit.min.css">-->
|
||||||
|
<!-- 头像直连 R2:crossorigin 让 favicon 也以 CORS 模式请求,确保浏览器缓存的响应都带 ACAO;
|
||||||
|
?v=2 击穿历史上被「无 ACAO 响应」污染的缓存条目 -->
|
||||||
|
<link rel="shortcut icon"
|
||||||
|
href="{{.PageUser.Avatar}}?v=2" crossorigin="anonymous"/>
|
||||||
|
<link rel="apple-touch-icon"
|
||||||
|
href="{{.PageUser.Avatar}}?v=2" crossorigin="anonymous"/>
|
||||||
|
<link rel="icon" sizes="192x192"
|
||||||
|
href="{{.PageUser.Avatar}}?v=2" crossorigin="anonymous">
|
||||||
|
<div class="uk-card uk-card-default uk-text-center">
|
||||||
|
<div class="uk-flex uk-flex-center uk-flex-middle uk-background-cover uk-light" style="min-height: 260px;" data-src="{{ .PageUser.Background }}" uk-img>
|
||||||
|
<div class="uk-card-body">
|
||||||
|
<img class="uk-border-circle uk-box-shadow-large" src="{{ if .PageUser.Avatar }}{{ .PageUser.Avatar }}?v=2{{ else }}{{ .DefaultAvatar }}{{ end }}" crossorigin="anonymous" style="width: 100px; height: 100px; max-width: 100%; max-height: 100%;">
|
||||||
|
<h3 id="usernamecolor">{{ .PageUser.Name }}</h3>
|
||||||
|
<p id="introcolor">{{ .PageUser.Intro }}</p>
|
||||||
|
<div class="icon-container">
|
||||||
|
{{ if and .PageUser.Acfunlink (ne .PageUser.Acfunlink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Acfunlink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/ailicili.png" alt="acfunlink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
{{ if and .PageUser.Bililink (ne .PageUser.Bililink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Bililink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/bili.png" alt="bililink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
{{ if and .PageUser.Weibolink (ne .PageUser.Weibolink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Weibolink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/weibo.png" alt="weibolink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
{{ if and .PageUser.Xiaohongshulink (ne .PageUser.Xiaohongshulink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Xiaohongshulink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/xiaohongshu.png" alt="xiaohongshulink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
{{ if and .PageUser.Bloglink (ne .PageUser.Bloglink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Bloglink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/blog.png" alt="bloglink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
document.getElementById("usernamecolor").style.color = {{.PageUser.Usernamecolor}};
|
||||||
|
document.getElementById("introcolor").style.color = {{.PageUser.Introcolor}};
|
||||||
|
</script>
|
||||||
|
<div>
|
||||||
|
<div class="uk-card uk-card-default uk-card-small uk-card-body">
|
||||||
|
{{ if .CanAsk }}
|
||||||
|
<!-- jQuery 按需加载(同步,保证下方内联二维码初始化就绪) -->
|
||||||
|
<script src="https://r2.337845818.best/tamabox/cdn/lib/jquery/3.7.1/jquery.min.js"></script>
|
||||||
|
<script src='https://r2.337845818.best/tamabox/cdn/js/remake/easy.qrcode.min.js' type="text/javascript" charset="utf-8"></script>
|
||||||
|
<center><div id="boxqrimg"></div></center>
|
||||||
|
<script type="text/javascript">
|
||||||
|
var options = {
|
||||||
|
text: window.location.href,
|
||||||
|
width: 200,
|
||||||
|
height: 200,
|
||||||
|
// 与 Profile 编辑器保持一致:仅当启用自定义前景色时,才把 Qrcodebackcolor 作为前景色;
|
||||||
|
// 否则强制黑色 #000000,避免未勾选却显示自定义前景色、与 Profile 预览不一致。
|
||||||
|
colorDark: ({{.PageUser.UseCustomQRColor}} ? "{{.PageUser.Qrcodebackcolor}}" : "#000000") || "#000000",
|
||||||
|
colorLight: "{{.PageUser.Qrcodecolor}}" || "#FFFFFF",
|
||||||
|
dotScale: parseFloat("{{.PageUser.Dotscale}}") || 0.4,
|
||||||
|
dotScaleTiming: parseFloat("{{.PageUser.Dotscale}}") || 0.4,
|
||||||
|
dotScaleA: parseFloat("{{.PageUser.Dotscale}}") || 0.4,
|
||||||
|
correctLevel: QRCode.CorrectLevel.H,
|
||||||
|
logo: (function () {
|
||||||
|
// ?v=2:击穿曾被无 ACAO 响应污染的浏览器缓存条目;仅对 http(s) 绝对地址追加
|
||||||
|
var a = "{{.PageUser.Avatar}}" || "{{.DefaultAvatar}}";
|
||||||
|
return a ? (a.indexOf("http") === 0 ? a + "?v=2" : a) : undefined;
|
||||||
|
})(),
|
||||||
|
logoWidth: 60,
|
||||||
|
logoHeight: 60,
|
||||||
|
logoBackgroundTransparent: true,
|
||||||
|
// 直连 R2 等跨域图片须以 CORS 模式加载,canvas 才不被污染、可正常导出
|
||||||
|
crossOrigin: 'anonymous',
|
||||||
|
backgroundImage: ("{{.PageUser.BackgroundImage}}" ? "{{.PageUser.BackgroundImage}}" : undefined),
|
||||||
|
backgroundImageAlpha: parseFloat("{{.PageUser.Backgroundimagealpha}}") || 0.8,
|
||||||
|
autoColor: false,
|
||||||
|
PO: "{{.PageUser.Qrcodepdpcolor}}" || "#000000",
|
||||||
|
PI: "{{.PageUser.Qrcodepdpcolor}}" || "#000000",
|
||||||
|
AO: '',
|
||||||
|
AI: '',
|
||||||
|
timing: "{{.PageUser.Qrcodepdpcolor}}" || "#000000"
|
||||||
|
};
|
||||||
|
new QRCode(document.getElementById("boxqrimg"), options);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<p class="uk-text-center uk-text-small">扫码向@{{ .PageUser.Name }}提问<br>{{ if .RegisterOnlyAsk }}{{t .LangCode "ask.registerOnly"}}{{ else }}{{t .LangCode "ask.anonymous"}}{{ end }}</p>
|
||||||
|
{{ end }}
|
||||||
|
{{template "base/alert" .}}
|
||||||
|
{{template "question/new-question-template" .}}
|
||||||
|
|
||||||
|
<hr class="uk-divider-icon">
|
||||||
|
{{ if ne (len .PageQuestions) 0 }}
|
||||||
|
<p class="uk-text-left uk-text-muted uk-text-small">@{{ .PageUser.Name }} 以前回答过的问题 ({{ .AnsweredCount }})</p>
|
||||||
|
{{ template "question/history-template" . }}
|
||||||
|
{{ end }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{{template "base/footer" .}}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
<p class="{{ if .IsPixel }}uk-container{{end}} uk-text-right uk-text-muted uk-text-small">
|
||||||
|
<br>Powered by NekoBox | {{ ICP }}<br>{{t .LangCode "site.footer.runtime"}}:<span id="box_runtime"></span>
|
||||||
|
<br>
|
||||||
|
<!--<a href="/pixel">画板</a> | -->
|
||||||
|
<a href="https://box.tama.guru/_/tamakyi" target="_blank">{{t .LangCode "site.footer.admin"}}</a>
|
||||||
|
| <a href="https://blog.tama.guru" target="_blank">{{t .LangCode "site.footer.notice"}}</a>
|
||||||
|
| <a href="https://chat.tama.guru" target="_blank">{{t .LangCode "site.footer.chat"}}</a>
|
||||||
|
| <a href="https://share.tama.guru" target="_blank">{{t .LangCode "site.footer.drive"}}</a>
|
||||||
|
| <a href="https://status.tama.guru" target="_blank">{{t .LangCode "site.footer.status"}}</a>
|
||||||
|
| <a href="https://tama.guru" target="_blank">{{t .LangCode "site.footer.nav"}}</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// 页脚「提问箱已成功存活」倒计时:原 R2 cdn/time.box.js(1.6KB)内联于此,
|
||||||
|
// 消除全站每页一个 R2 慢 defer(实测 0.7-1.7s 波动)。相对原脚本两处修复:
|
||||||
|
// 1) 先判空再写入(原版先赋值后判空,box_runtime 缺失时会抛 ReferenceError 中断脚本);
|
||||||
|
// 2) 首帧立即填充(原版 DOMContentLoaded + 首个 1s 间隔后才显示,首秒为空)。
|
||||||
|
(function () {
|
||||||
|
var create = Math.round(Date.UTC(2023, 6, 1, 18, 15, 43) / 1000); // 提问箱创建时刻(UTC)
|
||||||
|
function tick() {
|
||||||
|
var el = document.getElementById("box_runtime");
|
||||||
|
if (!el) return;
|
||||||
|
var s = Math.round((Date.now() + 8 * 3600 * 1000) / 1000) - create; // UTC+8 秒级存活
|
||||||
|
var t = [0, 0, 0, 0, 0];
|
||||||
|
if (s >= 31536000) { t[0] = s / 31536000 | 0; s %= 31536000; }
|
||||||
|
if (s >= 86400) { t[1] = s / 86400 | 0; s %= 86400; }
|
||||||
|
if (s >= 3600) { t[2] = s / 3600 | 0; s %= 3600; }
|
||||||
|
if (s >= 60) { t[3] = s / 60 | 0; s %= 60; }
|
||||||
|
if (s > 0) { t[4] = s; }
|
||||||
|
el.innerHTML = t[0] + '年 ' + t[1] + '天 ' + t[2] + '时 ' + t[3] + '分 ' + t[4] + '秒 ';
|
||||||
|
}
|
||||||
|
tick();
|
||||||
|
setInterval(tick, 1000);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<br>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// 提交反馈(P0):点击任意表单的提交按钮后,立即把触发按钮变成「转圈 + 本地化文字」,
|
||||||
|
// 并禁用表单内全部按钮,物理阻止在上传/网络慢时的重复点击与重复提交。
|
||||||
|
// 浏览器前进/后退(bfcache)回到本页时自动复位,避免停留在禁用或转圈状态。
|
||||||
|
// 纯内联反馈,不使用全屏遮罩。
|
||||||
|
var SUBMIT_I18N = {
|
||||||
|
submitting: '{{t .LangCode "common.submitting"}}',
|
||||||
|
uploading: '{{t .LangCode "common.uploading"}}'
|
||||||
|
};
|
||||||
|
|
||||||
|
function tbResetSubmitButtons() {
|
||||||
|
document.querySelectorAll('button[data-tb-submitting]').forEach(function(b) {
|
||||||
|
b.disabled = false;
|
||||||
|
b.removeAttribute('data-tb-submitting');
|
||||||
|
var orig = b.getAttribute('data-tb-restore');
|
||||||
|
if (orig !== null) {
|
||||||
|
b.innerHTML = orig;
|
||||||
|
b.removeAttribute('data-tb-restore');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('submit', function(e) {
|
||||||
|
var form = e.target;
|
||||||
|
if (!form || form.tagName !== 'FORM') return;
|
||||||
|
|
||||||
|
// 页面级提交反馈必须尊重前置校验:投票编辑页等 onsubmit 返回 false 时,
|
||||||
|
// submit 事件仍可能继续到达此监听器;此时绝不能切换到“提交中”状态。
|
||||||
|
if (e.defaultPrevented || form.getAttribute('data-tb-skip-submit-feedback') === '1') {
|
||||||
|
form.removeAttribute('data-tb-skip-submit-feedback');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 下载 / 新窗口类表单(target="_blank",如导出):当前页不发生导航,也没有 bfcache
|
||||||
|
// 复位机会,进入“提交中”状态后按钮会永远卡在转圈 + 禁用。这类表单直接跳过提交反馈。
|
||||||
|
if (form.getAttribute('target') === '_blank') return;
|
||||||
|
|
||||||
|
// 触发提交的按钮(programmatic submit 时 e.submitter 为 null,回退到首个 submit 按钮)
|
||||||
|
var trigger = e.submitter || form.querySelector('button[type="submit"]');
|
||||||
|
|
||||||
|
// 表单含已选中的文件 → 提示“上传中”,否则“提交中”
|
||||||
|
var hasFile = false;
|
||||||
|
form.querySelectorAll('input[type="file"]').forEach(function(f) {
|
||||||
|
if (f.files && f.files.length > 0) hasFile = true;
|
||||||
|
});
|
||||||
|
var label = hasFile ? SUBMIT_I18N.uploading : SUBMIT_I18N.submitting;
|
||||||
|
|
||||||
|
if (trigger && trigger.tagName === 'BUTTON') {
|
||||||
|
trigger.setAttribute('data-tb-restore', trigger.innerHTML);
|
||||||
|
trigger.innerHTML = '<span uk-spinner="ratio: 0.6"></span> ' + label;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 禁用表单内所有按钮,防止重复提交
|
||||||
|
form.querySelectorAll('button').forEach(function(b) {
|
||||||
|
b.disabled = true;
|
||||||
|
b.setAttribute('data-tb-submitting', '1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// bfcache 还原时复位按钮
|
||||||
|
window.addEventListener('pageshow', tbResetSubmitButtons);
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,122 @@
|
|||||||
|
{{template "base/header" .}}
|
||||||
|
<div class="uk-card uk-card-default uk-card-body">
|
||||||
|
<h1 class="uk-heading-small">{{t .LangCode "site.title"}}</h1>
|
||||||
|
<p><br>⭐一个无需注册即可提问的匿名提问箱。你不需要下载App,不需要绑定社交账号,甚至连邮箱都不需要是真的。<br>⭐本站在原版的基础上新增了问题页面的二维码、私聊、投票、追加提问等功能以及更多自定义内容。各位用户可自行修改二维码背景图、颜色等个性化配置。<br>⭐可以到站长唯一提问提问箱链接<a href="//box.tama.guru/_/tamakyi">小狼的提问箱</a>尝试相关功能或给我提意见。<br>⭐可以加群:<a href="http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=rRy9g5XY34LIzOITGGmQHjX6BIICFpam&authKey=EjyNjp60KyG8BtKZGN8BXJaf1jl8okkCcUhVF2zAnGPRjhvuSdopnVqOSfSymnGg&noverify=0&group_code=777163254">小狼的群</a>一起水群。<br></p>
|
||||||
|
<hr><p style="color: red;">近期将国内段访问交由EdgeOne接管,境外访问照旧由CloudFlare提供,经测试国内访问速度有所提升。但因EdgeOne Free套餐不提供CIDR列表,IP放行采取自动抓取手动维护模式,如果出现521错误请刷新一下页面,过几天应该就好了。</p>
|
||||||
|
<hr><p style="color: red; font-weight: bold;">近期更新:<br>⭐2026.9 增加了提问、投票、私聊的总开关,可以设置定时收集、定量收集或关闭功能,顺便调整了前后端显示,看起来更易用了一些。<br>⭐2026.8 新增了<a href="https://box.tama.guru/vote/sANyLkiBNUGN">投票功能</a>、追加提问、多语言、<a href="https://box.tama.guru/_/tamakyi/2894">Markdown显示</a>、置顶显示等多个功能,详情见<a href="https://blog.tama.guru/record/tamabox_changelog_20260813">这里</a>。<br>⭐2026.8 放弃使用recaptcha等对国内用户非常不友好的验证方式,更新了密码加密方式,修复了图片上传等一系列问题。<br>⭐2026.5 增加了私聊功能,可进行连续性对话,详见<a href="https://blog.tama.guru/record/tamabox-update-20260513">介绍</a>;另有增加提问箱的卡片分享,更直观和美观。<br>⭐2026.2 新增了用户展示和标签功能,如果你希望陌生人给你提问,可以在设置页面给自己贴上5个标签并选择是否展示在探索页面:<a href="https://box.tama.guru/explore">点我访问</a>,详情见<a href="https://blog.tama.guru/record/tamabox-tags">狼的公告板</a><br></p>
|
||||||
|
<hr><p>一点提醒:<br>⭐本站唯一指定认证站长:<a href="//box.tama.guru/_/tamakyi">小狼</a>,注意不要被骗。
|
||||||
|
<br>⭐本站不允许垃圾信息、广告、辱骂、涉政、暴恐、色情、违禁、无意义、灌水提问的出现,如有涉证或不良言论将直接删除。</p>
|
||||||
|
</div>
|
||||||
|
<p>{{t .LangCode "site.stats"}}:<pre style="overflow: hidden;" id="site-stats-text">{{if .SiteStats}}{{.SiteStats.Text}}{{end}}</pre></p>
|
||||||
|
<script type="text/javascript">
|
||||||
|
// 首页统计已改为程序内直接计算(服务端 30 分钟缓存),这里每 30 分钟定时拉取最新值刷新,
|
||||||
|
// 与原来 crontab 生成 question.count.txt 的节奏一致,且不再依赖外部静态文件。
|
||||||
|
document.addEventListener('DOMContentLoaded', function () {
|
||||||
|
setInterval(function () {
|
||||||
|
fetch("/api/v1/site-stats")
|
||||||
|
.then(function (r) { return r.json(); })
|
||||||
|
.then(function (resp) {
|
||||||
|
var d = resp.data;
|
||||||
|
if (!d || !d.text) return;
|
||||||
|
var el = document.getElementById("site-stats-text");
|
||||||
|
if (el) el.textContent = d.text;
|
||||||
|
})
|
||||||
|
.catch(function () {});
|
||||||
|
}, 30 * 60 * 1000);
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
<!--<script src="https://r2.337845818.best/oss-to-r2/nekobox/cdn/waline/client/v2/waline.js"></script>
|
||||||
|
<link href='https://r2.337845818.best/oss-to-r2/nekobox/cdn/waline/client/v2/waline-no-commits.css' rel='stylesheet' />-->
|
||||||
|
<div id="waline"></div>
|
||||||
|
<script>
|
||||||
|
document.addEventListener('DOMContentLoaded', function () {
|
||||||
|
const waline = Waline.init({
|
||||||
|
el: '#waline',
|
||||||
|
//后端服务器地址
|
||||||
|
serverURL: 'https://waline.337845818.best/',
|
||||||
|
path: window.location.href,
|
||||||
|
// 中文默认
|
||||||
|
locale: {
|
||||||
|
nick: '昵称',
|
||||||
|
nickError: '昵称不能少于3个字符',
|
||||||
|
mail: '邮箱',
|
||||||
|
mailError: '请填写正确的邮件地址',
|
||||||
|
link: '网址',
|
||||||
|
optional: '可选',
|
||||||
|
placeholder: '欢迎评论(可以无需登录,但需要手工审核,不会立即展现)',
|
||||||
|
sofa: '来发评论吧~',
|
||||||
|
submit: '提交',
|
||||||
|
like: '喜欢',
|
||||||
|
cancelLike: '取消喜欢',
|
||||||
|
reply: '回复',
|
||||||
|
cancelReply: '取消回复',
|
||||||
|
comment: '评论',
|
||||||
|
refresh: '刷新',
|
||||||
|
more: '加载更多...',
|
||||||
|
preview: '预览',
|
||||||
|
emoji: '表情',
|
||||||
|
uploadImage: '上传图片',
|
||||||
|
seconds: '秒前',
|
||||||
|
minutes: '分钟前',
|
||||||
|
hours: '小时前',
|
||||||
|
days: '天前',
|
||||||
|
now: '刚刚',
|
||||||
|
uploading: '正在上传',
|
||||||
|
login: '登录',
|
||||||
|
logout: '退出',
|
||||||
|
admin: '博主',
|
||||||
|
sticky: '置顶',
|
||||||
|
word: '字',
|
||||||
|
wordHint: '评论字数应在 $0 到 $1 字之间!\n当前字数:$2',
|
||||||
|
anonymous: '无名小狼',
|
||||||
|
level0: '潜水',
|
||||||
|
level1: '冒泡',
|
||||||
|
level2: '吐槽',
|
||||||
|
level3: '活跃',
|
||||||
|
level4: '话痨',
|
||||||
|
level5: '传说',
|
||||||
|
gif: '表情包',
|
||||||
|
gifSearchPlaceholder: '搜索表情包',
|
||||||
|
profile: '个人资料',
|
||||||
|
approved: '通过',
|
||||||
|
waiting: '待审核',
|
||||||
|
spam: '垃圾',
|
||||||
|
unsticky: '取消置顶',
|
||||||
|
oldest: '按倒序',
|
||||||
|
latest: '按正序',
|
||||||
|
hottest: '按热度',
|
||||||
|
reactionTitle: '',
|
||||||
|
reaction0: '哇哦',
|
||||||
|
reaction1: 'prpr',
|
||||||
|
reaction2: '流汗',
|
||||||
|
reaction3: '生气',
|
||||||
|
reaction4: '流鼻血',
|
||||||
|
reaction5: 'あべ',
|
||||||
|
},
|
||||||
|
reaction: [
|
||||||
|
'https://ali-imgs.acfun.cn/kimg/bs2/zt-image-host/ChYwOGQ3OTRhYzRjMTBkZmZhZDVmZTA1EIjM1y8.gif',
|
||||||
|
'https://ali-imgs.acfun.cn/kimg/bs2/zt-image-host/ChQwOGEyOTlhYzRjMTBmOWFkZjAwYRCIzNcv.gif',
|
||||||
|
'https://ali-imgs.acfun.cn/kimg/bs2/zt-image-host/ChYwOGRhOTVhYzRjMTBkNmViYTVlNTA2EIjM1y8.gif',
|
||||||
|
'https://ali-imgs.acfun.cn/kimg/bs2/zt-image-host/ChYwOGU1OTJhYzRjMTBmMzk3ZmVmNTAyEIjM1y8.gif',
|
||||||
|
'https://ali-imgs.acfun.cn/kimg/bs2/zt-image-host/ChYwOGNkODdhYzRjMTBjYmEwOTFjNjAxEIjM1y8.gif',
|
||||||
|
'https://ali-imgs.acfun.cn/kimg/bs2/zt-image-host/ChQwODliOGVhYzRjMTBmOGM0ZWY1ZRCIzNcv.gif',
|
||||||
|
],
|
||||||
|
meta: ['nick','mail'],
|
||||||
|
requiredMeta: ['mail'],
|
||||||
|
pageview: true,
|
||||||
|
search: false,
|
||||||
|
login: 'enable',
|
||||||
|
wordLimit: 50,
|
||||||
|
pageSize: 5,
|
||||||
|
avatar: 'identicon',
|
||||||
|
emoji: [
|
||||||
|
'https://gcore.jsdelivr.net/gh/tamakyi/emoji-collection@main/acfun-color/60x60',
|
||||||
|
],
|
||||||
|
//禁止图片上传按钮
|
||||||
|
imageUploader: false,
|
||||||
|
//不显示版权标志
|
||||||
|
copyright: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
{{template "base/footer" .}}
|
||||||
@@ -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
|
||||||
@@ -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 之外。
|
||||||
|
- 内容规范:禁止垃圾信息、广告、辱骂、涉政、暴恐、色情、违禁、无意义或灌水内容,违规内容将被删除。
|
||||||
@@ -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")
|
||||||
|
}
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<urlset
|
||||||
|
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
|
||||||
|
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"
|
||||||
|
>
|
||||||
|
|
||||||
|
<url>
|
||||||
|
<loc>https://box.tama.guru/explore</loc>
|
||||||
|
<priority>0.3</priority>
|
||||||
|
<lastmod>2026-02-27</lastmod>
|
||||||
|
<changefreq>weekly</changefreq>
|
||||||
|
</url>
|
||||||
|
|
||||||
|
<url>
|
||||||
|
<loc>https://box.tama.guru/</loc>
|
||||||
|
<priority>0.3</priority>
|
||||||
|
<lastmod>2026-02-27</lastmod>
|
||||||
|
<changefreq>weekly</changefreq>
|
||||||
|
</url>
|
||||||
|
|
||||||
|
<url>
|
||||||
|
<loc>https://box.tama.guru/register</loc>
|
||||||
|
<priority>0.3</priority>
|
||||||
|
<lastmod>2026-02-27</lastmod>
|
||||||
|
<changefreq>weekly</changefreq>
|
||||||
|
</url>
|
||||||
|
|
||||||
|
<url>
|
||||||
|
<loc>https://box.tama.guru/login</loc>
|
||||||
|
<priority>0.3</priority>
|
||||||
|
<lastmod>2026-02-27</lastmod>
|
||||||
|
<changefreq>weekly</changefreq>
|
||||||
|
</url>
|
||||||
|
|
||||||
|
<url>
|
||||||
|
<loc>https://box.tama.guru/_/tamakyi</loc>
|
||||||
|
<priority>0.3</priority>
|
||||||
|
<lastmod>2026-02-27</lastmod>
|
||||||
|
<changefreq>weekly</changefreq>
|
||||||
|
</url>
|
||||||
|
|
||||||
|
<url>
|
||||||
|
<loc>https://box.tama.guru</loc>
|
||||||
|
<priority>0.3</priority>
|
||||||
|
<lastmod>2026-02-27</lastmod>
|
||||||
|
<changefreq>weekly</changefreq>
|
||||||
|
</url>
|
||||||
|
|
||||||
|
<url>
|
||||||
|
<loc>https://box.tama.guru/change-logs</loc>
|
||||||
|
<priority>0.3</priority>
|
||||||
|
<lastmod>2026-02-27</lastmod>
|
||||||
|
<changefreq>weekly</changefreq>
|
||||||
|
</url>
|
||||||
|
|
||||||
|
</urlset>
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,977 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="{{.LangCode}}">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width">
|
||||||
|
<title>{{ .Title }}</title>
|
||||||
|
<meta name="description" content="{{ if .MetaDescription }}{{ .MetaDescription }}{{ else }}{{ t .LangCode "site.description" }}{{ end }}">
|
||||||
|
<meta name="keywords" content="{{ t .LangCode "site.keywords" }}">
|
||||||
|
<!-- 预连接:UIkit 走公共 CDN(cdnjs.snrat.com),其余自托管库仍在本站 R2,均需预连接 -->
|
||||||
|
<link rel="preconnect" href="https://r2.337845818.best" crossorigin>
|
||||||
|
<link rel="preconnect" href="https://cdnjs.snrat.com" crossorigin>
|
||||||
|
<link rel="dns-prefetch" href="https://cn.vercount.one">
|
||||||
|
<!-- UIkit 3.3.3 切到公共 CDN(cdnjs.snrat.com,国内实测全量下载 ~0.25s,原 R2 自建 ~1.4-2.0s) -->
|
||||||
|
<link rel="stylesheet" href="https://cdnjs.snrat.com/ajax/libs/uikit/3.3.3/css/uikit.min.css"/>
|
||||||
|
<!-- Waline 评论区样式:非阻塞加载,不阻塞首屏渲染 -->
|
||||||
|
<link rel="stylesheet" href="https://r2.337845818.best/tamabox/cdn/waline/client/v2/waline-no-commits.css" media="print" onload="this.media='all'"/>
|
||||||
|
<script defer src="https://cdnjs.snrat.com/ajax/libs/uikit/3.3.3/js/uikit.min.js"></script>
|
||||||
|
<script defer src="https://cdnjs.snrat.com/ajax/libs/uikit/3.3.3/js/uikit-icons.min.js"></script>
|
||||||
|
<!-- UIkit 补丁:复刻原自建版 "modify-black-font"(官方版与自建版仅 3 处颜色差异——把有色容器内默认白字/白标题改为黑字)。
|
||||||
|
模板当前只用到 .uk-light 容器(用户背景封面,question/list.html、question-not-found.html;
|
||||||
|
其中 h3/p 已由 #usernamecolor/#introcolor 内联 style 覆盖),故只需补该容器的 3 处投影即可保持渲染一致。
|
||||||
|
若日后新增 .uk-card-primary/.uk-card-secondary/.uk-section-primary/.uk-tile-*/.uk-overlay-primary 等容器且需黑字,须同步扩展。 -->
|
||||||
|
<style>
|
||||||
|
.uk-light { color: rgba(0,0,0,.7); }
|
||||||
|
.uk-light .uk-h1, .uk-light .uk-h2, .uk-light .uk-h3, .uk-light .uk-h4, .uk-light .uk-h5, .uk-light .uk-h6,
|
||||||
|
.uk-light .uk-heading-2xlarge, .uk-light .uk-heading-large, .uk-light .uk-heading-medium, .uk-light .uk-heading-small, .uk-light .uk-heading-xlarge,
|
||||||
|
.uk-light h1, .uk-light h2, .uk-light h3, .uk-light h4, .uk-light h5, .uk-light h6 { color: #000; }
|
||||||
|
.uk-light .uk-table th { color: rgba(0,0,0,.7); }
|
||||||
|
</style>
|
||||||
|
<!-- dayjs/alpinejs/vconsole/waline.js 已迁 cdnjs.snrat.com(sha256 与官方一致,国内实测快 2-7x) -->
|
||||||
|
<script defer src="https://cdnjs.snrat.com/ajax/libs/dayjs/1.10.8/dayjs.min.js"></script>
|
||||||
|
<script defer src="https://cdnjs.snrat.com/ajax/libs/alpinejs/3.9.0/cdn.min.js"></script>
|
||||||
|
{{ if .VConsole }}
|
||||||
|
<script src="https://cdnjs.snrat.com/ajax/libs/vConsole/3.12.1/vconsole.min.js" type="application/javascript"></script>
|
||||||
|
<script>new window.VConsole()</script>
|
||||||
|
{{ end }}
|
||||||
|
<!-- jQuery 已改为按需加载:仅 easy.qrcode 二维码页(list/question-not-found/profile)自行引入 -->
|
||||||
|
<script defer src="https://r2.337845818.best/tamabox/cdn/time.box.js"></script>
|
||||||
|
<!--<script src="https://r2.337845818.best/tamabox/cdn/busuanzi.pure.mini.js"/></script>-->
|
||||||
|
<script defer src="https://cn.vercount.one/js"></script>
|
||||||
|
<script defer src="https://cdnjs.snrat.com/ajax/libs/waline/2.15.8/waline.js"></script>
|
||||||
|
{{ if eq .CaptchaType "math" }}
|
||||||
|
<!-- 算数验证码:弹窗模式,不影响原布局 -->
|
||||||
|
<style>
|
||||||
|
.captcha-equation-box {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
background: #f0f2f5;
|
||||||
|
border: 1px solid #dcdcdc;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 8px 8px 8px 16px;
|
||||||
|
gap: 6px;
|
||||||
|
transition: border-color 0.2s;
|
||||||
|
}
|
||||||
|
.captcha-equation-box:focus-within {
|
||||||
|
border-color: #1e87f0;
|
||||||
|
box-shadow: 0 0 0 3px rgba(30,135,240,0.12);
|
||||||
|
}
|
||||||
|
.math-captcha-modal-question {
|
||||||
|
font-size: 1.4rem;
|
||||||
|
font-family: "Courier New", monospace;
|
||||||
|
font-weight: 700;
|
||||||
|
color: #333;
|
||||||
|
letter-spacing: 1px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
#captcha-modal-answer {
|
||||||
|
width: 80px;
|
||||||
|
padding: 6px 10px;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 1.2rem;
|
||||||
|
font-family: "Courier New", monospace;
|
||||||
|
font-weight: 600;
|
||||||
|
border: 1px solid #ccc;
|
||||||
|
border-radius: 5px;
|
||||||
|
outline: none;
|
||||||
|
transition: border-color 0.15s, box-shadow 0.15s;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
#captcha-modal-answer:focus {
|
||||||
|
border-color: #1e87f0;
|
||||||
|
box-shadow: 0 0 0 2px rgba(30,135,240,0.2);
|
||||||
|
}
|
||||||
|
/* 隐藏数字输入框的上下箭头 */
|
||||||
|
#captcha-modal-answer::-webkit-inner-spin-button,
|
||||||
|
#captcha-modal-answer::-webkit-outer-spin-button {
|
||||||
|
-webkit-appearance: none;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
#captcha-modal-answer {
|
||||||
|
-moz-appearance: textfield;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
{{ else if .RecaptchaTurnstileStyle }}
|
||||||
|
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?compat=recaptcha" async defer></script>
|
||||||
|
<script>
|
||||||
|
document.addEventListener('DOMContentLoaded', function () {
|
||||||
|
document.querySelectorAll('.g-recaptcha').forEach(item => {
|
||||||
|
item.disabled = true;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function onSubmit() {
|
||||||
|
document.querySelectorAll('.g-recaptcha').forEach(item => {
|
||||||
|
item.disabled = false;
|
||||||
|
})
|
||||||
|
}</script>
|
||||||
|
{{ else }}
|
||||||
|
<script src="{{.RecaptchaDomain}}/recaptcha/api.js" async defer></script>
|
||||||
|
<script>function onSubmit() {document.getElementById('form').submit();}</script>
|
||||||
|
{{ end }}
|
||||||
|
{{ if ne SentryDSN "" }}
|
||||||
|
<script
|
||||||
|
src="https://browser.sentry-cdn.com/7.37.2/bundle.tracing.replay.min.js"
|
||||||
|
integrity="sha384-o0mU2P+zsvXua0Y6f/J55PKWZt3sZCv3qDqJe6J5lZklyIQkpgjBVqNnPWYWqGhf"
|
||||||
|
crossorigin="anonymous"
|
||||||
|
></script>
|
||||||
|
<script>
|
||||||
|
Sentry.init({
|
||||||
|
dsn: "{{ SentryDSN }}",
|
||||||
|
integrations: [new Sentry.BrowserTracing(), new Sentry.Replay()],
|
||||||
|
tracesSampleRate: 1.0,
|
||||||
|
replaysSessionSampleRate: 0.1,
|
||||||
|
replaysOnErrorSampleRate: 1.0,
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
{{ end }}
|
||||||
|
<style>
|
||||||
|
.grecaptcha-badge {visibility: hidden;}
|
||||||
|
.icon-container {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
.icon {
|
||||||
|
margin-left: 10px;
|
||||||
|
width: 20px; /* 设置图标的宽度 */
|
||||||
|
height: auto; /* 保持图标的高度自动调整 */
|
||||||
|
}
|
||||||
|
.emoji-placeholder {
|
||||||
|
display: inline-block;
|
||||||
|
animation: jump 0.5s ease-in-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes jump {
|
||||||
|
0%, 100% { transform: translateY(0); }
|
||||||
|
50% { transform: translateY(-5px); }
|
||||||
|
}
|
||||||
|
/* 防止 UIkit Dropbar 初始闪烁 */
|
||||||
|
.uk-dropbar {
|
||||||
|
opacity: 0;
|
||||||
|
visibility: hidden;
|
||||||
|
transition: opacity 0.2s ease, visibility 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.uk-dropbar.uk-open {
|
||||||
|
opacity: 1;
|
||||||
|
visibility: visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
a.uk-button.uk-button-link {
|
||||||
|
text-transform: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 移动端优化:缩小字体和间距,避免右侧空白 */
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.uk-logo {
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
.uk-navbar-nav a {
|
||||||
|
font-size: 0.78rem;
|
||||||
|
padding: 0 4px;
|
||||||
|
}
|
||||||
|
.emoji-placeholder {
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
/* 移动端用户名限宽省略,避免长英文用户名撑爆顶栏 */
|
||||||
|
.tb-nav-username {
|
||||||
|
max-width: 64px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
display: inline-block;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<!-- 深色模式:html[data-theme="dark"] 时覆盖 UIkit 3.3.3 编译主题的关键颜色 -->
|
||||||
|
<style>
|
||||||
|
html[data-theme="dark"] {
|
||||||
|
--tb-bg: #1a1d23;
|
||||||
|
--tb-surface: #242830;
|
||||||
|
--tb-surface-2: #2d323c;
|
||||||
|
--tb-border: #3a404c;
|
||||||
|
--tb-text: #d8dce4;
|
||||||
|
--tb-text-muted: #8b93a1;
|
||||||
|
--tb-primary: #5c8dff;
|
||||||
|
}
|
||||||
|
/* 根元素与 body 一起覆盖,确保整个视口(含内容不足一屏时的空白区)都是深色背景 */
|
||||||
|
html[data-theme="dark"],
|
||||||
|
html[data-theme="dark"] body {
|
||||||
|
background-color: var(--tb-bg) !important;
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
}
|
||||||
|
/* 通用表面容器 */
|
||||||
|
html[data-theme="dark"] .uk-card,
|
||||||
|
html[data-theme="dark"] .uk-card-default,
|
||||||
|
html[data-theme="dark"] .uk-card-secondary,
|
||||||
|
html[data-theme="dark"] .uk-dropbar,
|
||||||
|
html[data-theme="dark"] .uk-navbar-dropdown,
|
||||||
|
html[data-theme="dark"] .uk-modal-dialog,
|
||||||
|
html[data-theme="dark"] .uk-dropdown,
|
||||||
|
html[data-theme="dark"] .uk-offcanvas-bar,
|
||||||
|
html[data-theme="dark"] .uk-section,
|
||||||
|
html[data-theme="dark"] .uk-tile,
|
||||||
|
html[data-theme="dark"] .uk-panel,
|
||||||
|
html[data-theme="dark"] .uk-background-default,
|
||||||
|
html[data-theme="dark"] .uk-search-default .uk-search-input {
|
||||||
|
background-color: var(--tb-surface) !important;
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-navbar-container {
|
||||||
|
background-color: var(--tb-surface) !important;
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-navbar-nav > li > a,
|
||||||
|
html[data-theme="dark"] .uk-card a,
|
||||||
|
html[data-theme="dark"] .uk-link,
|
||||||
|
html[data-theme="dark"] a.uk-button-link,
|
||||||
|
html[data-theme="dark"] .uk-navbar-dropdown-nav > li > a,
|
||||||
|
html[data-theme="dark"] .uk-dropdown-nav > li > a,
|
||||||
|
html[data-theme="dark"] .uk-list a {
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-navbar-nav > li > a:hover,
|
||||||
|
html[data-theme="dark"] .uk-card a:hover,
|
||||||
|
html[data-theme="dark"] .uk-navbar-dropdown-nav > li > a:hover,
|
||||||
|
html[data-theme="dark"] .uk-dropdown-nav > li > a:hover {
|
||||||
|
color: var(--tb-primary) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-input,
|
||||||
|
html[data-theme="dark"] .uk-textarea,
|
||||||
|
html[data-theme="dark"] .uk-select {
|
||||||
|
background-color: var(--tb-surface-2) !important;
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
border-color: var(--tb-border) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-input:focus,
|
||||||
|
html[data-theme="dark"] .uk-textarea:focus,
|
||||||
|
html[data-theme="dark"] .uk-select:focus {
|
||||||
|
border-color: var(--tb-primary) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-text-muted,
|
||||||
|
html[data-theme="dark"] .uk-text-meta,
|
||||||
|
html[data-theme="dark"] .uk-text-secondary,
|
||||||
|
html[data-theme="dark"] .uk-text-muted a,
|
||||||
|
html[data-theme="dark"] .uk-text-small.uk-text-muted {
|
||||||
|
color: var(--tb-text-muted) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-divider-icon::after,
|
||||||
|
html[data-theme="dark"] hr,
|
||||||
|
html[data-theme="dark"] .uk-table th,
|
||||||
|
html[data-theme="dark"] .uk-table td,
|
||||||
|
html[data-theme="dark"] .uk-list-divider > li:nth-child(n+2) {
|
||||||
|
border-color: var(--tb-border) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-button-default {
|
||||||
|
background-color: var(--tb-surface-2) !important;
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
border-color: var(--tb-border) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-modal-title,
|
||||||
|
html[data-theme="dark"] h1, html[data-theme="dark"] h2, html[data-theme="dark"] h3,
|
||||||
|
html[data-theme="dark"] h4, html[data-theme="dark"] h5, html[data-theme="dark"] h6,
|
||||||
|
html[data-theme="dark"] .uk-card-title {
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-alert-warning,
|
||||||
|
html[data-theme="dark"] .uk-alert-danger,
|
||||||
|
html[data-theme="dark"] .uk-alert-success,
|
||||||
|
html[data-theme="dark"] .uk-alert-primary {
|
||||||
|
background-color: var(--tb-surface-2) !important;
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] #math-captcha-modal .uk-modal-dialog {
|
||||||
|
background-color: var(--tb-surface) !important;
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] #math-captcha-modal .captcha-equation-box {
|
||||||
|
background-color: var(--tb-surface-2) !important;
|
||||||
|
border-color: var(--tb-border) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] #math-captcha-modal .math-captcha-modal-question {
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] #math-captcha-modal #captcha-modal-answer {
|
||||||
|
background-color: var(--tb-surface) !important;
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
border-color: var(--tb-border) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] #math-captcha-modal #captcha-modal-answer::placeholder {
|
||||||
|
color: var(--tb-text-muted) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] #math-captcha-modal .uk-text-meta,
|
||||||
|
html[data-theme="dark"] #math-captcha-modal #captcha-modal-refresh {
|
||||||
|
color: var(--tb-text-muted) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] #math-captcha-modal #captcha-modal-refresh:hover {
|
||||||
|
color: var(--tb-primary) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-label {
|
||||||
|
color: #fff !important;
|
||||||
|
}
|
||||||
|
/* 自定义组件(探索页推荐卡片等)深色覆盖 */
|
||||||
|
html[data-theme="dark"] .recommend-card,
|
||||||
|
html[data-theme="dark"] .recommend-card:hover {
|
||||||
|
background-color: var(--tb-surface-2) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .explore-name a {
|
||||||
|
color: var(--tb-text) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .explore-name a:hover {
|
||||||
|
color: var(--tb-primary) !important;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .explore-intro {
|
||||||
|
color: var(--tb-text-muted) !important;
|
||||||
|
}
|
||||||
|
/* 切换按钮图标切换 */
|
||||||
|
#theme-toggle .tb-icon-dark, #theme-toggle-mobile .tb-icon-dark { display: none; }
|
||||||
|
html[data-theme="dark"] #theme-toggle .tb-icon-light,
|
||||||
|
html[data-theme="dark"] #theme-toggle-mobile .tb-icon-light { display: none; }
|
||||||
|
html[data-theme="dark"] #theme-toggle .tb-icon-dark,
|
||||||
|
html[data-theme="dark"] #theme-toggle-mobile .tb-icon-dark { display: inline; }
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<!-- 顶栏自适应:导航全部直接显示,窄屏时分级缩小字号/间距,保证英文/日文等长文字不溢出 -->
|
||||||
|
<style>
|
||||||
|
.uk-navbar-nav a {
|
||||||
|
font-size: 0.95rem;
|
||||||
|
padding: 0 10px;
|
||||||
|
}
|
||||||
|
/* 未登录移动端占位:桌面端隐藏,仅 ≤640px 显示(见下方 media 查询)。
|
||||||
|
桌面端布局与改动前完全一致,不受影响。 */
|
||||||
|
.tb-mobile-balancer { display: none; }
|
||||||
|
/* 桌面端保持 UIkit 原生居中三列布局(无需额外 CSS) */
|
||||||
|
.tb-navbar .uk-logo {
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
@media (max-width: 1200px) {
|
||||||
|
.uk-navbar-nav a {
|
||||||
|
font-size: 0.88rem;
|
||||||
|
padding: 0 8px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (max-width: 1000px) {
|
||||||
|
.uk-navbar-nav a {
|
||||||
|
font-size: 0.82rem;
|
||||||
|
padding: 0 6px;
|
||||||
|
}
|
||||||
|
.uk-logo {
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
/* 登录用户名限宽,过长省略号截断 */
|
||||||
|
.tb-nav-username {
|
||||||
|
max-width: 110px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
display: inline-block;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (max-width: 800px) {
|
||||||
|
.uk-navbar-nav a {
|
||||||
|
font-size: 0.78rem;
|
||||||
|
padding: 0 4px;
|
||||||
|
}
|
||||||
|
.uk-logo {
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
.tb-nav-username {
|
||||||
|
max-width: 80px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/* 手机端(≤640px):沿用 UIkit 桌面端 navbar 的原生三列定位。
|
||||||
|
不再重写 .uk-navbar-center / center-left / center-right 的定位,
|
||||||
|
避免 logo 被挤到下一行;底部语言与深色模式按钮仍由下方独立栏承载。 */
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.tb-navbar {
|
||||||
|
position: relative;
|
||||||
|
min-height: 56px;
|
||||||
|
overflow: visible;
|
||||||
|
}
|
||||||
|
.tb-navbar > .uk-navbar-center {
|
||||||
|
position: relative !important;
|
||||||
|
top: auto !important;
|
||||||
|
left: auto !important;
|
||||||
|
right: auto !important;
|
||||||
|
bottom: auto !important;
|
||||||
|
transform: none !important;
|
||||||
|
display: flex !important;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 100%;
|
||||||
|
min-height: 56px;
|
||||||
|
white-space: nowrap;
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
}
|
||||||
|
.tb-navbar .uk-navbar-center-left,
|
||||||
|
.tb-navbar .uk-navbar-center-right {
|
||||||
|
position: static !important;
|
||||||
|
top: auto !important;
|
||||||
|
left: auto !important;
|
||||||
|
right: auto !important;
|
||||||
|
bottom: auto !important;
|
||||||
|
transform: none !important;
|
||||||
|
display: flex !important;
|
||||||
|
align-items: center;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.tb-navbar .uk-navbar-center-left > div,
|
||||||
|
.tb-navbar .uk-navbar-center-right > div {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.tb-navbar .uk-navbar-nav {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
}
|
||||||
|
.tb-navbar .uk-navbar-nav > li > a,
|
||||||
|
.tb-navbar .uk-logo {
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
/* 未登录:移动端显示与「我的」等宽的隐藏占位,使左栏「探索+占位」与
|
||||||
|
右栏「注册/登录」两项等宽,logo 真正居中,左右视觉平衡 */
|
||||||
|
.tb-mobile-balancer { display: block; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<!-- 标签样式的按钮(管理页置顶等):
|
||||||
|
尺寸完全继承 .uk-label(font-size/padding/line-height/text-transform 等),
|
||||||
|
仅覆盖 button 元素特有的默认样式(边框/字体族/光标等),保证与相邻 span 标签完全一致。 -->
|
||||||
|
<style>
|
||||||
|
.tb-label-btn {
|
||||||
|
border: none !important;
|
||||||
|
cursor: pointer;
|
||||||
|
font-family: inherit;
|
||||||
|
margin: 0;
|
||||||
|
vertical-align: middle;
|
||||||
|
outline: none;
|
||||||
|
background-image: none;
|
||||||
|
box-sizing: border-box;
|
||||||
|
-webkit-appearance: none;
|
||||||
|
appearance: none;
|
||||||
|
}
|
||||||
|
.tb-label-btn:hover {
|
||||||
|
opacity: 0.85;
|
||||||
|
}
|
||||||
|
/* 公开页置顶小图标:仅一个图钉,不占行高、不影响原布局 */
|
||||||
|
.tb-pin-flag {
|
||||||
|
font-size: 0.9em;
|
||||||
|
margin-right: 4px;
|
||||||
|
vertical-align: -1px;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<!-- 页脚统计加载动画:替代 fontawesome 的 fa-spinner(纯 CSS,不引字体库) -->
|
||||||
|
<style>
|
||||||
|
.tb-spinner {
|
||||||
|
display: inline-block;
|
||||||
|
width: 0.9em;
|
||||||
|
height: 0.9em;
|
||||||
|
border: 2px solid rgba(128, 128, 128, 0.25);
|
||||||
|
border-top-color: #666;
|
||||||
|
border-radius: 50%;
|
||||||
|
vertical-align: -2px;
|
||||||
|
animation: tb-spin 0.8s linear infinite;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .tb-spinner {
|
||||||
|
border-color: rgba(255, 255, 255, 0.2);
|
||||||
|
border-top-color: #bbb;
|
||||||
|
}
|
||||||
|
@keyframes tb-spin {
|
||||||
|
to { transform: rotate(360deg); }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<!-- Markdown 渲染排版(问题/回答/追问正文,左对齐以保留排版格式) -->
|
||||||
|
<style>
|
||||||
|
/* 纯文本列表:保留换行与连续空格(pre-wrap),不渲染 Markdown 大字号/彩色 */
|
||||||
|
.tb-preline {
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
/* 纯文本列表:超过 5 行截断并显示省略号(不足 5 行则完整显示) */
|
||||||
|
.tb-clamp-5 {
|
||||||
|
display: -webkit-box;
|
||||||
|
-webkit-box-orient: vertical;
|
||||||
|
-webkit-line-clamp: 5;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.md-body {
|
||||||
|
line-height: 1.7;
|
||||||
|
text-align: left;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
.md-body p { margin: 0.5em 0; }
|
||||||
|
.md-body h1, .md-body h2, .md-body h3,
|
||||||
|
.md-body h4, .md-body h5, .md-body h6 {
|
||||||
|
margin: 0.8em 0 0.4em;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
.md-body ul, .md-body ol { padding-left: 1.6em; margin: 0.5em 0; }
|
||||||
|
.md-body li { margin: 0.2em 0; }
|
||||||
|
.md-body blockquote {
|
||||||
|
border-left: 3px solid #d3d1c7;
|
||||||
|
margin: 0.6em 0;
|
||||||
|
padding: 0.2em 1em;
|
||||||
|
color: #5f5e5a;
|
||||||
|
}
|
||||||
|
.md-body pre {
|
||||||
|
background: #f5f5f5;
|
||||||
|
padding: 0.8em 1em;
|
||||||
|
border-radius: 6px;
|
||||||
|
overflow-x: auto;
|
||||||
|
margin: 0.6em 0;
|
||||||
|
}
|
||||||
|
.md-body code {
|
||||||
|
background: #f0f0f0;
|
||||||
|
padding: 0.1em 0.35em;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 0.9em;
|
||||||
|
}
|
||||||
|
.md-body pre code { background: none; padding: 0; }
|
||||||
|
.md-body img { max-width: 100%; height: auto; }
|
||||||
|
.md-body table { border-collapse: collapse; margin: 0.6em 0; }
|
||||||
|
.md-body th, .md-body td {
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
padding: 0.4em 0.8em;
|
||||||
|
}
|
||||||
|
.md-body hr { margin: 1em 0; }
|
||||||
|
html[data-theme="dark"] .md-body blockquote {
|
||||||
|
border-color: #3a404c;
|
||||||
|
color: #8b93a1;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .md-body pre,
|
||||||
|
html[data-theme="dark"] .md-body code { background: #2d323c; }
|
||||||
|
html[data-theme="dark"] .md-body th,
|
||||||
|
html[data-theme="dark"] .md-body td { border-color: #3a404c; }
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<!-- 投票结果占比条:UIkit 3 已无 .uk-progressbar 类(那是 UIkit 2 的),
|
||||||
|
模板用 <div class="uk-progress"><div class="uk-progressbar"> 结构,需补一套填充样式,
|
||||||
|
否则内层填充无高度/背景,所有占比条都只剩外层灰色轨道,看起来一模一样。 -->
|
||||||
|
<style>
|
||||||
|
.uk-progress {
|
||||||
|
-webkit-appearance: none;
|
||||||
|
-moz-appearance: none;
|
||||||
|
appearance: none;
|
||||||
|
height: 10px;
|
||||||
|
margin: 0;
|
||||||
|
border: none;
|
||||||
|
border-radius: 6px;
|
||||||
|
background-color: #e5e5e5;
|
||||||
|
overflow: hidden;
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
.uk-progressbar {
|
||||||
|
display: block;
|
||||||
|
height: 100%;
|
||||||
|
background-color: #1e87f0;
|
||||||
|
border-radius: 6px 0 0 6px;
|
||||||
|
transition: width 0.3s ease;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-progress {
|
||||||
|
background-color: var(--tb-border);
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .uk-progressbar {
|
||||||
|
background-color: var(--tb-primary);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<!-- 移动端底部操作栏:固定底栏承载语言切换与深色模式,桌面端隐藏 -->
|
||||||
|
<style>
|
||||||
|
#tb-mobile-utils {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
/* 顶栏不再容纳语言/深色按钮,恢复原有导航空间 */
|
||||||
|
.tb-nav-utils {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
/* 手机端隐藏登录用户名(左边仅保留"探索"),保证 logo 居中、
|
||||||
|
两侧各不超过 2 个短按钮,避免用户名宽度挤压布局 */
|
||||||
|
.tb-nav-username {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
/* 固定底部操作栏 */
|
||||||
|
#tb-mobile-utils {
|
||||||
|
display: flex;
|
||||||
|
position: fixed;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
z-index: 1000;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 8px 12px calc(8px + env(safe-area-inset-bottom));
|
||||||
|
background: rgba(255, 255, 255, 0.92);
|
||||||
|
-webkit-backdrop-filter: blur(8px);
|
||||||
|
backdrop-filter: blur(8px);
|
||||||
|
box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.08);
|
||||||
|
}
|
||||||
|
#tb-mobile-utils .uk-select {
|
||||||
|
width: 110px;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] #tb-mobile-utils {
|
||||||
|
background: rgba(36, 40, 48, 0.92);
|
||||||
|
box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.4);
|
||||||
|
}
|
||||||
|
/* 给页面底部预留空间,避免页脚内容被固定底栏遮挡 */
|
||||||
|
body {
|
||||||
|
padding-bottom: 56px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<!-- Commit 6d0a3ad -->
|
||||||
|
<meta property="og:site_name" content="{{ t .LangCode "site.title" }}" />
|
||||||
|
<meta property="og:type" content="website" />
|
||||||
|
<meta property="og:title" content="{{ if .IsUserPage }}{{ .PageUser.Name }} - {{ t .LangCode "site.title" }}{{ else }}{{ t .LangCode "site.title" }}{{ end }}" />
|
||||||
|
<meta property="og:url" content="{{ .ExternalURL }}{{ .CurrentURI }}" />
|
||||||
|
<meta property="og:description" content="{{ if .IsUserPage }}{{ .PageUser.Name }} - {{ t .LangCode "site.description" }}{{ else }}{{ t .LangCode "site.description" }}{{ end }}" />
|
||||||
|
{{ if .NoIndex }}<meta name="robots" content="noindex">{{ end }}
|
||||||
|
{{ if .IsUserPage }}
|
||||||
|
<meta property="og:image" content="{{ .PageUser.Avatar }}?og-image=1" />
|
||||||
|
<meta property="og:image:alt" content="{{ .PageUser.Name }}" />
|
||||||
|
<meta itemprop="image" content="{{ .PageUser.Avatar }}?og-image=1"/>
|
||||||
|
<meta name="msapplication-TileImage" content="{{ .PageUser.Avatar }}"/>
|
||||||
|
<link rel="shortcut icon" href="{{ .PageUser.Avatar }}?og-image=1"/>
|
||||||
|
<link rel="apple-touch-icon" href="{{ .PageUser.Avatar }}?og-image=1"/>
|
||||||
|
<link rel="icon" sizes="192x192" href="{{ .PageUser.Avatar }}?og-image=1">
|
||||||
|
<meta name="twitter:image:src" content="{{ .PageUser.Avatar }}?og-image=1" />
|
||||||
|
{{ else }}
|
||||||
|
<meta itemprop="image" content="https://r2.337845818.best/tamabox/tamabox_low.png"/>
|
||||||
|
<meta name="msapplication-TileImage" content="https://r2.337845818.best/tamabox/tamabox_low.png"/>
|
||||||
|
<link rel="shortcut icon" href="https://r2.337845818.best/tamabox/tamabox_low.png" />
|
||||||
|
<link rel="apple-touch-icon" href="https://r2.337845818.best/tamabox/tamabox_low.png"/>
|
||||||
|
<link rel="icon" sizes="192x192" href="https://r2.337845818.best/tamabox/tamabox_low.png">
|
||||||
|
<meta name="twitter:image:src" content="https://r2.337845818.best/tamabox/tamabox_low.png" />
|
||||||
|
{{ end }}
|
||||||
|
|
||||||
|
<!-- Google and Bing -->
|
||||||
|
<meta name="google-site-verification" content="fEPwRRJfiGsgwc5SINBQwZhPK8F0cwRaOvRx0YRurI4" />
|
||||||
|
<meta name="msvalidate.01" content="2F185E8E63C93635F50B3574F3B31E42" />
|
||||||
|
<script defer src="https://mami.tama.guru/tamami.js" data-website-id="c42ebe8b-9281-4da0-83a4-8f18b3e710fe"></script>
|
||||||
|
</head>
|
||||||
|
<nav class="uk-navbar-container uk-margin tb-navbar" uk-navbar>
|
||||||
|
<div class="uk-navbar-center">
|
||||||
|
<div class="uk-navbar-center-left">
|
||||||
|
<div>
|
||||||
|
<ul class="uk-navbar-nav">
|
||||||
|
<!-- 探索链接,始终显示 -->
|
||||||
|
<li><a href="/explore">{{t .LangCode "nav.explore"}}</a></li>
|
||||||
|
{{ if .IsLogged }}
|
||||||
|
<!-- 我的:进入自己的提问箱主页(与右侧「提问/设置」形成左右均衡) -->
|
||||||
|
<li><a href="/_/{{ .LoggedUser.Domain }}">{{t .LangCode "nav.mine"}}</a></li>
|
||||||
|
{{ else }}
|
||||||
|
<!-- 移动端占位:未登录时左栏仅「探索」一项,与右栏「注册/登录」两项不等宽,
|
||||||
|
导致 logo 整体被拉向左(偏左)。移动端(≤640px)显示一个与「我的」等宽的隐藏占位,
|
||||||
|
使左右视觉平衡;桌面端由 .tb-mobile-balancer 隐藏,保持原布局完全不变。 -->
|
||||||
|
<li class="tb-mobile-balancer" aria-hidden="true"><a tabindex="-1" style="visibility:hidden">{{t .LangCode "nav.mine"}}</a></li>
|
||||||
|
{{ end }}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<a class="uk-navbar-item uk-logo" href="/"><span class="emoji-placeholder" aria-label="random animal">🐺</span>{{t .LangCode "site.logoSuffix"}}</a>
|
||||||
|
|
||||||
|
<div class="uk-navbar-center-right">
|
||||||
|
<div>
|
||||||
|
{{ if .IsLogged }}
|
||||||
|
<ul class="uk-navbar-nav">
|
||||||
|
<li><a href="/user/questions">{{t .LangCode "nav.ask"}}</a></li>
|
||||||
|
</ul>
|
||||||
|
<ul class="uk-navbar-nav">
|
||||||
|
<li><a href="/user/profile">{{t .LangCode "nav.settings"}}</a></li>
|
||||||
|
</ul>
|
||||||
|
{{ else}}
|
||||||
|
<ul class="uk-navbar-nav">
|
||||||
|
<li><a href="/register">{{t .LangCode "nav.register"}}</a></li>
|
||||||
|
</ul>
|
||||||
|
<ul class="uk-navbar-nav">
|
||||||
|
<li><a href="/login">{{t .LangCode "nav.login"}}</a></li>
|
||||||
|
</ul>
|
||||||
|
{{ end }}
|
||||||
|
{{ if not .IsUserPage }}
|
||||||
|
<!-- 语言切换(紧凑图标,点击展开;移动端隐藏,见底部操作栏) -->
|
||||||
|
<ul class="uk-navbar-nav tb-nav-utils">
|
||||||
|
<li>
|
||||||
|
<a href="#" aria-label="{{t .LangCode "common.lang"}}" title="{{t .LangCode "common.lang"}}">🌐</a>
|
||||||
|
<div class="uk-navbar-dropdown" uk-drop="mode: click; pos: bottom-right">
|
||||||
|
<ul class="uk-nav uk-navbar-dropdown-nav">
|
||||||
|
{{ range .SupportedLangs }}
|
||||||
|
<li class="{{ if eq .Code $.LangCode }}uk-active{{ end }}">
|
||||||
|
<a href="/i18n/{{ .Code }}?to={{ urlquery $.CurrentURI }}">{{ .Name }}</a>
|
||||||
|
</li>
|
||||||
|
{{ end }}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
{{ end }}
|
||||||
|
<!-- 深色模式切换(紧凑图标;移动端隐藏,见底部操作栏) -->
|
||||||
|
<ul class="uk-navbar-nav tb-nav-utils">
|
||||||
|
<li>
|
||||||
|
<a href="#" id="theme-toggle" title="{{t .LangCode "common.theme"}}" aria-label="{{t .LangCode "common.theme"}}">
|
||||||
|
<span class="tb-icon-light">🌙</span><span class="tb-icon-dark">☀️</span>
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
document.addEventListener("DOMContentLoaded", function() {
|
||||||
|
const emojis = ["🐺","🐗","🐻","🐨","🐼","🐹","🐭","🐰","🦊","🐮","🐷","🐽","🐸","🐒","🦍","🐔","🐧","🐦","🐤","🐦⬛","🦅","🦉","🦇","🐴","🦄","🐝","🦎","🦖","🦕","🐙","🦑","🦐","🦞","🦀","🐡","🐠","🐟","🐬","🐳","🐋","🦈","🐊","🐅","🐆","🦓","🦍","🦧","🐘","🦛","🦏","🐪","🐫","🦒","🦘","🐃","🐂","🐄","🐎","🐖","🐏","🐑","🦙","🐐","🦌","🐕","🐩","🦮","🐕🦺","🐈","🐋","🐳","🐬","🐉","🐲"];
|
||||||
|
const placeholder = document.querySelector('.emoji-placeholder');
|
||||||
|
if (placeholder) {
|
||||||
|
placeholder.textContent = emojis[Math.floor(Math.random() * emojis.length)];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<!-- 移动端固定底部操作栏:语言切换 + 深色模式(桌面端隐藏) -->
|
||||||
|
<div id="tb-mobile-utils">
|
||||||
|
{{ if not .IsUserPage }}
|
||||||
|
<select id="mobile-lang-select" class="uk-select uk-form-small" aria-label="{{t .LangCode "common.lang"}}">
|
||||||
|
{{ range .SupportedLangs }}
|
||||||
|
<option value="{{ .Code }}" {{ if eq .Code $.LangCode }}selected{{ end }}>{{ .Name }}</option>
|
||||||
|
{{ end }}
|
||||||
|
</select>
|
||||||
|
{{ end }}
|
||||||
|
<button type="button" id="theme-toggle-mobile" class="uk-button uk-button-default uk-button-small"
|
||||||
|
title="{{t .LangCode "common.theme"}}" aria-label="{{t .LangCode "common.theme"}}">
|
||||||
|
<span class="tb-icon-light">🌙</span><span class="tb-icon-dark">☀️</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
// 深色模式:读取 cookie 应用主题,按钮切换并持久化
|
||||||
|
var THEME_COOKIE = 'theme';
|
||||||
|
function getTheme() {
|
||||||
|
var m = document.cookie.match(/(?:^|;\s*)theme=([^;]*)/);
|
||||||
|
return m ? m[1] : '';
|
||||||
|
}
|
||||||
|
function applyTheme(theme) {
|
||||||
|
if (theme === 'dark') {
|
||||||
|
document.documentElement.setAttribute('data-theme', 'dark');
|
||||||
|
} else {
|
||||||
|
document.documentElement.removeAttribute('data-theme');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function toggleTheme() {
|
||||||
|
var next = getTheme() === 'dark' ? 'light' : 'dark';
|
||||||
|
applyTheme(next);
|
||||||
|
var expires = new Date(Date.now() + 365 * 24 * 3600 * 1000).toUTCString();
|
||||||
|
document.cookie = THEME_COOKIE + '=' + next + '; path=/; max-age=' + (365 * 24 * 3600) + '; SameSite=Lax';
|
||||||
|
}
|
||||||
|
// 首屏前应用,避免闪烁
|
||||||
|
applyTheme(getTheme());
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
// 桌面顶栏按钮与移动端底部按钮都绑定
|
||||||
|
var buttons = document.querySelectorAll('#theme-toggle, #theme-toggle-mobile');
|
||||||
|
buttons.forEach(function(btn) {
|
||||||
|
btn.addEventListener('click', function(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
toggleTheme();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 移动端底部语言切换:onchange 跳转到 /i18n/{code},保留当前页面位置
|
||||||
|
var langSel = document.getElementById('mobile-lang-select');
|
||||||
|
if (langSel) {
|
||||||
|
langSel.addEventListener('change', function() {
|
||||||
|
if (!this.value) return;
|
||||||
|
var to = window.location.pathname + window.location.search;
|
||||||
|
window.location.href = '/i18n/' + encodeURIComponent(this.value) + '?to=' + encodeURIComponent(to);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{{ if .IsPixel }}
|
||||||
|
<div>
|
||||||
|
{{ else }}
|
||||||
|
<div class="uk-container uk-container-xsmall">
|
||||||
|
{{ end }}
|
||||||
|
|
||||||
|
{{ if eq .CaptchaType "math" }}
|
||||||
|
<!-- 算数验证码弹窗 --><div id="math-captcha-modal" uk-modal>
|
||||||
|
<div class="uk-modal-dialog uk-modal-body uk-text-center">
|
||||||
|
<h3 class="uk-modal-title">{{t .LangCode "captcha.title"}}</h3>
|
||||||
|
<p class="uk-text-meta">{{t .LangCode "captcha.hint"}}</p>
|
||||||
|
<div class="captcha-equation-box">
|
||||||
|
<span id="captcha-modal-question" class="math-captcha-modal-question">{{t .LangCode "captcha.loading"}}</span>
|
||||||
|
<input type="number" id="captcha-modal-answer" placeholder="?" autocomplete="off" inputmode="numeric">
|
||||||
|
</div>
|
||||||
|
<div style="margin-top:6px;">
|
||||||
|
<button type="button" class="uk-button uk-button-text uk-text-small" id="captcha-modal-refresh">{{t .LangCode "captcha.refresh"}}</button>
|
||||||
|
</div>
|
||||||
|
<div id="captcha-modal-error" class="uk-text-danger uk-text-small" style="display:none;min-height:20px;"></div>
|
||||||
|
<div class="uk-margin-small-top">
|
||||||
|
<button type="button" class="uk-button uk-button-primary" id="captcha-modal-submit">{{t .LangCode "captcha.submit"}}</button>
|
||||||
|
<button type="button" class="uk-button uk-button-default uk-modal-close">{{t .LangCode "common.cancel"}}</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
var CAPTCHA_I18N = {
|
||||||
|
loading: "{{t .LangCode "captcha.loading"}}",
|
||||||
|
loadFailed: "{{t .LangCode "captcha.loadFailed"}}",
|
||||||
|
loadRetry: "{{t .LangCode "captcha.loadRetry"}}",
|
||||||
|
inputAnswer: "{{t .LangCode "captcha.inputAnswer"}}",
|
||||||
|
wrongAnswer: "{{t .LangCode "captcha.wrongAnswer"}}",
|
||||||
|
verifyFailed: "{{t .LangCode "captcha.verifyFailed"}}",
|
||||||
|
needPassword: "{{t .LangCode "ask.needPassword"}}",
|
||||||
|
needEmail: "{{t .LangCode "ask.pleaseEmail"}}"
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var captchaId = '';
|
||||||
|
var pendingForm = null;
|
||||||
|
var pendingNeedPassword = false;
|
||||||
|
var verifying = false;
|
||||||
|
|
||||||
|
function fetchCaptcha() {
|
||||||
|
var qEl = document.getElementById('captcha-modal-question');
|
||||||
|
var errEl = document.getElementById('captcha-modal-error');
|
||||||
|
var ansEl = document.getElementById('captcha-modal-answer');
|
||||||
|
qEl.textContent = CAPTCHA_I18N.loading;
|
||||||
|
fetch('/api/captcha/generate')
|
||||||
|
.then(function(r) { return r.json(); })
|
||||||
|
.then(function(data) {
|
||||||
|
if (data.code === 0 && data.data) {
|
||||||
|
captchaId = data.data.id;
|
||||||
|
qEl.textContent = data.data.question;
|
||||||
|
if (errEl) errEl.style.display = 'none';
|
||||||
|
if (ansEl) { ansEl.value = ''; ansEl.focus(); }
|
||||||
|
} else {
|
||||||
|
qEl.textContent = CAPTCHA_I18N.loadFailed;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(function() {
|
||||||
|
qEl.textContent = CAPTCHA_I18N.loadRetry;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCSRFToken() {
|
||||||
|
var input = document.querySelector('input[name="_csrf"]');
|
||||||
|
return input ? input.value : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function doSubmit(form) {
|
||||||
|
// 将 captcha 答案填入隐藏字段
|
||||||
|
var ans = document.getElementById('captcha-modal-answer').value.trim();
|
||||||
|
var hidden = form.querySelector('[name="g-recaptcha-response"]');
|
||||||
|
if (hidden) hidden.value = captchaId + ':' + (ans || '0');
|
||||||
|
|
||||||
|
UIkit.modal('#math-captcha-modal').hide();
|
||||||
|
|
||||||
|
// 处理 AskPassword(提问箱密码)
|
||||||
|
if (pendingNeedPassword) {
|
||||||
|
UIkit.modal.prompt(CAPTCHA_I18N.needPassword, '', 'password')
|
||||||
|
.then(function(password) {
|
||||||
|
if (password) {
|
||||||
|
var pwInput = document.getElementById('ask_password_input');
|
||||||
|
if (pwInput) pwInput.value = password;
|
||||||
|
form.submit();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
form.submit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证按钮
|
||||||
|
document.getElementById('captcha-modal-submit').addEventListener('click', function() {
|
||||||
|
if (verifying) return;
|
||||||
|
var ans = document.getElementById('captcha-modal-answer').value.trim();
|
||||||
|
if (!ans) {
|
||||||
|
var errEl = document.getElementById('captcha-modal-error');
|
||||||
|
errEl.textContent = CAPTCHA_I18N.inputAnswer;
|
||||||
|
errEl.style.display = 'block';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
verifying = true;
|
||||||
|
fetch('/api/captcha/verify', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-CSRF-Token': getCSRFToken()
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ id: captchaId, answer: parseInt(ans, 10) })
|
||||||
|
})
|
||||||
|
.then(function(r) { return r.json(); })
|
||||||
|
.then(function(data) {
|
||||||
|
verifying = false;
|
||||||
|
if (data.correct) {
|
||||||
|
if (pendingForm) doSubmit(pendingForm);
|
||||||
|
} else {
|
||||||
|
var errEl = document.getElementById('captcha-modal-error');
|
||||||
|
errEl.textContent = CAPTCHA_I18N.wrongAnswer;
|
||||||
|
errEl.style.display = 'block';
|
||||||
|
fetchCaptcha(); // 自动刷新题目
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(function() {
|
||||||
|
verifying = false;
|
||||||
|
var errEl = document.getElementById('captcha-modal-error');
|
||||||
|
errEl.textContent = CAPTCHA_I18N.verifyFailed;
|
||||||
|
errEl.style.display = 'block';
|
||||||
|
fetchCaptcha();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 回车提交
|
||||||
|
document.getElementById('captcha-modal-answer').addEventListener('keydown', function(e) {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
document.getElementById('captcha-modal-submit').click();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 刷新按钮
|
||||||
|
document.getElementById('captcha-modal-refresh').addEventListener('click', fetchCaptcha);
|
||||||
|
|
||||||
|
// 拦截所有带 class="math-captcha-trigger" 的按钮
|
||||||
|
document.addEventListener('click', function(e) {
|
||||||
|
var btn = e.target.closest('.math-captcha-trigger');
|
||||||
|
if (!btn) return;
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
var form = btn.closest('form');
|
||||||
|
if (!form) return;
|
||||||
|
pendingForm = form;
|
||||||
|
|
||||||
|
// 检查是否需要提问密码
|
||||||
|
pendingNeedPassword = !!(form.querySelector('#ask_password_input'));
|
||||||
|
|
||||||
|
// 邮箱校验(提问页面)
|
||||||
|
var notifyCb = document.getElementById('notify-checkbox');
|
||||||
|
var emailInput = document.getElementById('email-input');
|
||||||
|
if (notifyCb && notifyCb.checked && emailInput && emailInput.value.trim() === '') {
|
||||||
|
UIkit.modal.alert(CAPTCHA_I18N.needEmail);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchCaptcha();
|
||||||
|
UIkit.modal('#math-captcha-modal').show();
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
{{ end }}
|
||||||
@@ -0,0 +1,309 @@
|
|||||||
|
{{template "base/header" .}}
|
||||||
|
<!-- 头像直连 R2:crossorigin 让 favicon 也以 CORS 模式请求,确保浏览器缓存的响应都带 ACAO;
|
||||||
|
?v=2 击穿历史上被「无 ACAO 响应」污染的缓存条目(R2 对无 Origin 请求的响应无 Vary,可缓存 31 天) -->
|
||||||
|
<link rel="shortcut icon" href="{{.PageUser.Avatar}}?v=2" crossorigin="anonymous"/>
|
||||||
|
<link rel="apple-touch-icon" href="{{.PageUser.Avatar}}?v=2" crossorigin="anonymous"/>
|
||||||
|
<link rel="icon" sizes="192x192" href="{{.PageUser.Avatar}}?v=2" crossorigin="anonymous">
|
||||||
|
<style>
|
||||||
|
/* 投票列表:与探索页"全部投票"一致的列表行样式 */
|
||||||
|
.profile-votes-list { display: grid; gap: 0; }
|
||||||
|
.profile-vote-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 16px;
|
||||||
|
min-width: 0;
|
||||||
|
padding: 14px 16px;
|
||||||
|
border-bottom: 1px solid var(--tb-border, #e9e9e9);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
.profile-vote-item:first-child { border-top: 1px solid var(--tb-border, #e9e9e9); }
|
||||||
|
.profile-vote-item:hover { background: var(--tb-surface-hover, #f8fbff); text-decoration: none; }
|
||||||
|
.profile-vote-content { min-width: 0; }
|
||||||
|
.profile-vote-title {
|
||||||
|
display: block;
|
||||||
|
overflow: hidden;
|
||||||
|
color: var(--tb-text, #333);
|
||||||
|
font-size: 0.98rem;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1.45;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.profile-vote-meta {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 7px;
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
.profile-vote-meta .uk-label { font-size: 0.72rem; line-height: 1.6; }
|
||||||
|
.profile-vote-action {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
color: var(--tb-primary, #1e87f0);
|
||||||
|
font-size: 0.82rem;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .profile-vote-item { border-color: var(--tb-border); }
|
||||||
|
html[data-theme="dark"] .profile-vote-title { color: var(--tb-text); }
|
||||||
|
html[data-theme="dark"] .profile-vote-item:hover { background: rgba(78, 168, 245, 0.10); }
|
||||||
|
/* 个人主页 Tab:与探索页一致的胶囊切换样式 */
|
||||||
|
/* 个人主页 Tab:全宽等分,置于主体顶部,作为一级导航(移动端整行可点) */
|
||||||
|
.profile-tabs {
|
||||||
|
display: flex;
|
||||||
|
gap: 4px;
|
||||||
|
padding: 4px;
|
||||||
|
margin-top: 20px;
|
||||||
|
margin-bottom: 18px;
|
||||||
|
border: 1px solid var(--tb-border, #e5e5e5);
|
||||||
|
border-radius: 9px;
|
||||||
|
background: var(--tb-surface-2, #fafafa);
|
||||||
|
}
|
||||||
|
.profile-tab {
|
||||||
|
flex: 1;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 9px 15px;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--tb-text-muted, #666);
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
transition: background 0.2s ease, color 0.2s ease;
|
||||||
|
}
|
||||||
|
.profile-tab:hover { color: var(--tb-primary, #1e87f0); }
|
||||||
|
.profile-tab.is-active {
|
||||||
|
background: var(--tb-surface, #fff);
|
||||||
|
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.10);
|
||||||
|
color: var(--tb-primary, #1e87f0);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
/* 功能关闭时置灰禁用的 Tab(如投票功能关闭) */
|
||||||
|
.profile-tab.is-disabled,
|
||||||
|
.profile-tab:disabled {
|
||||||
|
cursor: not-allowed;
|
||||||
|
color: var(--tb-text-muted, #999);
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
.profile-tab.is-disabled:hover { color: var(--tb-text-muted, #999); }
|
||||||
|
.profile-panel[hidden] { display: none !important; }
|
||||||
|
html[data-theme="dark"] .profile-tabs {
|
||||||
|
border-color: var(--tb-border);
|
||||||
|
background: var(--tb-surface-2);
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .profile-tab { color: var(--tb-text-muted); }
|
||||||
|
html[data-theme="dark"] .profile-tab.is-active { background: var(--tb-surface); color: var(--tb-primary); }
|
||||||
|
html[data-theme="dark"] .profile-tab.is-disabled { color: var(--tb-text-muted); opacity: 0.55; }
|
||||||
|
</style>
|
||||||
|
<div class="uk-card uk-card-default uk-text-center">
|
||||||
|
<div class="uk-flex uk-flex-center uk-flex-middle uk-background-cover uk-light" style="min-height: 260px;" data-src="{{ .PageUser.Background }}" uk-img>
|
||||||
|
<div class="uk-card-body">
|
||||||
|
<img class="uk-border-circle uk-box-shadow-large" src="{{ if .PageUser.Avatar }}{{ .PageUser.Avatar }}?v=2{{ else }}{{ .DefaultAvatar }}{{ end }}" crossorigin="anonymous" style="width: 100px; height: 100px; max-width: 100%; max-height: 100%;">
|
||||||
|
<h3 id="usernamecolor">{{ .PageUser.Name }}</h3>
|
||||||
|
<p id="introcolor">{{ .PageUser.Intro }}</p>
|
||||||
|
<div class="icon-container">
|
||||||
|
{{ if and .PageUser.Acfunlink (ne .PageUser.Acfunlink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Acfunlink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/ailicili.png" alt="acfunlink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
{{ if and .PageUser.Bililink (ne .PageUser.Bililink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Bililink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/bili.png" alt="bililink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
{{ if and .PageUser.Weibolink (ne .PageUser.Weibolink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Weibolink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/weibo.png" alt="weibolink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
{{ if and .PageUser.Xiaohongshulink (ne .PageUser.Xiaohongshulink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Xiaohongshulink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/xiaohongshu.png" alt="xiaohongshulink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
{{ if and .PageUser.Bloglink (ne .PageUser.Bloglink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Bloglink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/blog.png" alt="bloglink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
document.getElementById("usernamecolor").style.color = "{{.PageUser.Usernamecolor}}";
|
||||||
|
document.getElementById("introcolor").style.color = "{{.PageUser.Introcolor}}";
|
||||||
|
</script>
|
||||||
|
<div>
|
||||||
|
<div class="uk-card uk-card-default uk-card-small uk-card-body">
|
||||||
|
{{ if .CanAsk }}
|
||||||
|
<!-- jQuery 已改为按需加载:defer 按文档顺序先于 easy.qrcode 执行,保证就绪 -->
|
||||||
|
<script defer src="https://cdnjs.snrat.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
|
||||||
|
<script defer src='https://r2.337845818.best/tamabox/cdn/js/remake/easy.qrcode.min.js' type="text/javascript" charset="utf-8"></script>
|
||||||
|
<center><div id="boxqrimg"></div></center>
|
||||||
|
<script type="text/javascript">
|
||||||
|
document.addEventListener('DOMContentLoaded', function () {
|
||||||
|
var options = {
|
||||||
|
text: window.location.href,
|
||||||
|
width: 200,
|
||||||
|
height: 200,
|
||||||
|
// 与 Profile 编辑器保持一致:仅当启用自定义前景色时,才把 Qrcodebackcolor 作为前景色;
|
||||||
|
// 否则强制黑色 #000000,避免未勾选却显示自定义前景色、与 Profile 预览不一致。
|
||||||
|
colorDark: ({{.PageUser.UseCustomQRColor}} ? "{{.PageUser.Qrcodebackcolor}}" : "#000000") || "#000000",
|
||||||
|
colorLight: "{{.PageUser.Qrcodecolor}}" || "#FFFFFF",
|
||||||
|
dotScale: parseFloat("{{.PageUser.Dotscale}}") || 0.4,
|
||||||
|
dotScaleTiming: parseFloat("{{.PageUser.Dotscale}}") || 0.4,
|
||||||
|
dotScaleA: parseFloat("{{.PageUser.Dotscale}}") || 0.4,
|
||||||
|
correctLevel: QRCode.CorrectLevel.H,
|
||||||
|
logo: (function () {
|
||||||
|
// ?v=2:击穿曾被无 ACAO 响应污染的浏览器缓存条目;仅对 http(s) 绝对地址追加
|
||||||
|
var a = "{{.PageUser.Avatar}}" || "{{.DefaultAvatar}}";
|
||||||
|
return a ? (a.indexOf("http") === 0 ? a + "?v=2" : a) : undefined;
|
||||||
|
})(),
|
||||||
|
logoWidth: 60,
|
||||||
|
logoHeight: 60,
|
||||||
|
logoBackgroundTransparent: true,
|
||||||
|
// 直连 R2 等跨域图片须以 CORS 模式加载,canvas 才不被污染、可正常导出
|
||||||
|
crossOrigin: 'anonymous',
|
||||||
|
backgroundImage: ("{{.PageUser.BackgroundImage}}" ? "{{.PageUser.BackgroundImage}}" : undefined),
|
||||||
|
backgroundImageAlpha: parseFloat("{{.PageUser.Backgroundimagealpha}}") || 0.8,
|
||||||
|
autoColor: false,
|
||||||
|
PO: "{{.PageUser.Qrcodepdpcolor}}" || "#000000",
|
||||||
|
PI: "{{.PageUser.Qrcodepdpcolor}}" || "#000000",
|
||||||
|
AO: '',
|
||||||
|
AI: '',
|
||||||
|
timing: "{{.PageUser.Qrcodepdpcolor}}" || "#000000"
|
||||||
|
};
|
||||||
|
new QRCode(document.getElementById("boxqrimg"), options);
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<p class="uk-text-center uk-text-small">{{t .LangCode "ask.scan" .PageUser.Name}}<br>{{ if .RegisterOnlyAsk }}{{t .LangCode "ask.registerOnly"}}{{ else }}{{t .LangCode "ask.anonymous"}}{{ end }}</p>
|
||||||
|
|
||||||
|
<div class="uk-text-center uk-margin-small-top">
|
||||||
|
<a id="share-btn" href="/_/{{ .PageUser.Domain }}/share-card" download class="uk-button uk-button-default uk-button-small">
|
||||||
|
📤 {{t .LangCode "ask.share"}}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="share-loading-overlay" style="display:none; position: fixed; top:0; left:0; width:100%; height:100%; background: rgba(255,255,255,0.85); z-index:9999;">
|
||||||
|
<div style="display:flex; flex-direction:column; align-items:center; justify-content:center; height:100%;">
|
||||||
|
<div uk-spinner="ratio: 2" class="uk-margin-bottom"></div>
|
||||||
|
<p class="uk-text-large uk-text-muted">{{t .LangCode "ask.generating"}}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var btn = document.getElementById('share-btn');
|
||||||
|
var overlay = document.getElementById('share-loading-overlay');
|
||||||
|
if (!btn || !overlay) return;
|
||||||
|
btn.addEventListener('click', function(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
overlay.style.display = 'block';
|
||||||
|
btn.style.pointerEvents = 'none';
|
||||||
|
fetch(btn.href)
|
||||||
|
.then(function(response) {
|
||||||
|
if (!response.ok) throw new Error('{{t .LangCode "ask.networkError"}}');
|
||||||
|
return response.blob();
|
||||||
|
})
|
||||||
|
.then(function(blob) {
|
||||||
|
var url = URL.createObjectURL(blob);
|
||||||
|
var a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = '{{t .LangCode "ask.shareFilename"}}';
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
setTimeout(function() {
|
||||||
|
document.body.removeChild(a);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}, 100);
|
||||||
|
})
|
||||||
|
.catch(function(err) {
|
||||||
|
alert('{{t .LangCode "ask.genFailed"}}');
|
||||||
|
console.error(err);
|
||||||
|
})
|
||||||
|
.finally(function() {
|
||||||
|
overlay.style.display = 'none';
|
||||||
|
btn.style.pointerEvents = 'auto';
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
{{ end }}
|
||||||
|
{{template "base/alert" .}}
|
||||||
|
|
||||||
|
<!-- 提问 / 投票 切换:默认显示提问,支持 ?tab=votes 直达(服务端初始态)与 #votes hash 覆盖 -->
|
||||||
|
<div class="profile-tabs" role="tablist">
|
||||||
|
<button type="button" class="profile-tab{{ if eq .ActiveProfileTab "questions" }} is-active{{ end }}" data-profile-tab="questions" role="tab" aria-selected="{{ if eq .ActiveProfileTab "questions" }}true{{ else }}false{{ end }}">{{t .LangCode "explore.questionsTab"}}</button>
|
||||||
|
{{ if .VoteEnabled }}
|
||||||
|
<button type="button" class="profile-tab{{ if eq .ActiveProfileTab "votes" }} is-active{{ end }}" data-profile-tab="votes" role="tab" aria-selected="{{ if eq .ActiveProfileTab "votes" }}true{{ else }}false{{ end }}">{{t .LangCode "explore.votesTab"}}</button>
|
||||||
|
{{ else }}
|
||||||
|
<!-- 投票功能关闭:保留 Tab 展示但置灰禁用,hover 提示原因 -->
|
||||||
|
<button type="button" class="profile-tab is-disabled" disabled aria-disabled="true" uk-tooltip="{{ .VoteClosedMessage }}">{{t .LangCode "explore.votesTab"}} <span uk-icon="icon: lock; ratio: 0.8"></span></button>
|
||||||
|
{{ end }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="profile-panel" data-profile-panel="questions"{{ if eq .ActiveProfileTab "votes" }} hidden{{ end }}>
|
||||||
|
{{template "question/new-question-template" .}}
|
||||||
|
|
||||||
|
{{ if ne (len .PageQuestions) 0 }}
|
||||||
|
<p class="uk-text-left uk-text-muted uk-text-small">{{t .LangCode "ask.history" .PageUser.Name}} ({{ .AnsweredCount }})</p>
|
||||||
|
{{ template "question/history-template" . }}
|
||||||
|
{{ end }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="profile-panel" data-profile-panel="votes"{{ if ne .ActiveProfileTab "votes" }} hidden{{ end }}>
|
||||||
|
{{ if .PageVotes }}
|
||||||
|
<!-- 匿名投票板块:箱主"进行中"的公开投票(列表行样式,与探索页"全部投票"一致) -->
|
||||||
|
<div class="profile-votes-list">
|
||||||
|
{{ range .PageVotes }}
|
||||||
|
<a href="/vote/{{ .LinkToken }}" class="profile-vote-item">
|
||||||
|
<div class="profile-vote-content">
|
||||||
|
<span class="profile-vote-title" title="{{ .Title }}">{{ .Title }}</span>
|
||||||
|
<span class="profile-vote-meta">
|
||||||
|
{{ if eq .Type "single" }}<span class="uk-label uk-label-primary">{{t $.LangCode "vote.typeSingle"}}</span>{{ end }}
|
||||||
|
{{ if eq .Type "multiple" }}<span class="uk-label uk-label-primary">{{t $.LangCode "vote.typeMultiple"}}</span>{{ end }}
|
||||||
|
{{ if eq .Type "rating" }}<span class="uk-label uk-label-primary">{{t $.LangCode "vote.typeRating"}}</span>{{ end }}
|
||||||
|
{{ if eq .Type "rank" }}<span class="uk-label uk-label-primary">{{t $.LangCode "vote.typeRank"}}</span>{{ end }}
|
||||||
|
{{ if eq .Type "form" }}<span class="uk-label uk-label-primary">{{t $.LangCode "vote.typeForm"}}</span>{{ end }}
|
||||||
|
<span class="uk-text-meta">{{ .CreatedAt.Format "2006-01-02" }}</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span class="profile-vote-action">{{t $.LangCode "vote.page.goVote"}} <span uk-icon="icon: arrow-right; ratio: .8"></span></span>
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
</div>
|
||||||
|
{{ else }}
|
||||||
|
<div class="uk-alert uk-alert-primary uk-margin-remove-top">{{t .LangCode "explore.noVotes"}}</div>
|
||||||
|
{{ end }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
var tabs = document.querySelectorAll('[data-profile-tab]');
|
||||||
|
var panels = document.querySelectorAll('[data-profile-panel]');
|
||||||
|
function showPanel(name) {
|
||||||
|
tabs.forEach(function(tab) {
|
||||||
|
var active = tab.dataset.profileTab === name;
|
||||||
|
tab.classList.toggle('is-active', active);
|
||||||
|
tab.setAttribute('aria-selected', active ? 'true' : 'false');
|
||||||
|
});
|
||||||
|
panels.forEach(function(panel) {
|
||||||
|
panel.hidden = panel.dataset.profilePanel !== name;
|
||||||
|
});
|
||||||
|
if (window.history && window.history.replaceState) {
|
||||||
|
window.history.replaceState({}, document.title, window.location.pathname + window.location.search + (name === 'votes' ? '#votes' : ''));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tabs.forEach(function(tab) {
|
||||||
|
tab.addEventListener('click', function() { showPanel(tab.dataset.profileTab); });
|
||||||
|
});
|
||||||
|
// 仅当投票 Tab 可点击(功能开启)时才响应 #votes hash,避免投票关闭时切到空面板
|
||||||
|
if (window.location.hash === '#votes' && document.querySelector('[data-profile-tab="votes"]')) {
|
||||||
|
showPanel('votes');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
{{template "base/footer" .}}
|
||||||
+105
@@ -0,0 +1,105 @@
|
|||||||
|
{{template "base/header" .}}
|
||||||
|
<!--<link rel="stylesheet" href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-y/uikit/3.3.3/css/uikit.min.css">-->
|
||||||
|
<!-- 头像直连 R2:crossorigin 让 favicon 也以 CORS 模式请求,确保浏览器缓存的响应都带 ACAO;
|
||||||
|
?v=2 击穿历史上被「无 ACAO 响应」污染的缓存条目 -->
|
||||||
|
<link rel="shortcut icon"
|
||||||
|
href="{{.PageUser.Avatar}}?v=2" crossorigin="anonymous"/>
|
||||||
|
<link rel="apple-touch-icon"
|
||||||
|
href="{{.PageUser.Avatar}}?v=2" crossorigin="anonymous"/>
|
||||||
|
<link rel="icon" sizes="192x192"
|
||||||
|
href="{{.PageUser.Avatar}}?v=2" crossorigin="anonymous">
|
||||||
|
<div class="uk-card uk-card-default uk-text-center">
|
||||||
|
<div class="uk-flex uk-flex-center uk-flex-middle uk-background-cover uk-light" style="min-height: 260px;" data-src="{{ .PageUser.Background }}" uk-img>
|
||||||
|
<div class="uk-card-body">
|
||||||
|
<img class="uk-border-circle uk-box-shadow-large" src="{{ if .PageUser.Avatar }}{{ .PageUser.Avatar }}?v=2{{ else }}{{ .DefaultAvatar }}{{ end }}" crossorigin="anonymous" style="width: 100px; height: 100px; max-width: 100%; max-height: 100%;">
|
||||||
|
<h3 id="usernamecolor">{{ .PageUser.Name }}</h3>
|
||||||
|
<p id="introcolor">{{ .PageUser.Intro }}</p>
|
||||||
|
<div class="icon-container">
|
||||||
|
{{ if and .PageUser.Acfunlink (ne .PageUser.Acfunlink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Acfunlink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/ailicili.png" alt="acfunlink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
{{ if and .PageUser.Bililink (ne .PageUser.Bililink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Bililink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/bili.png" alt="bililink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
{{ if and .PageUser.Weibolink (ne .PageUser.Weibolink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Weibolink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/weibo.png" alt="weibolink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
{{ if and .PageUser.Xiaohongshulink (ne .PageUser.Xiaohongshulink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Xiaohongshulink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/xiaohongshu.png" alt="xiaohongshulink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
{{ if and .PageUser.Bloglink (ne .PageUser.Bloglink "none") }}
|
||||||
|
<a href="https://{{.PageUser.Bloglink}}" target="_blank">
|
||||||
|
<img src="https://r2.337845818.best/tamabox/icon/social/blog.png" alt="bloglink" class="icon">
|
||||||
|
</a>
|
||||||
|
{{ end }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
document.getElementById("usernamecolor").style.color = {{.PageUser.Usernamecolor}};
|
||||||
|
document.getElementById("introcolor").style.color = {{.PageUser.Introcolor}};
|
||||||
|
</script>
|
||||||
|
<div>
|
||||||
|
<div class="uk-card uk-card-default uk-card-small uk-card-body">
|
||||||
|
{{ if .CanAsk }}
|
||||||
|
<!-- jQuery 按需加载(同步,保证下方内联二维码初始化就绪) -->
|
||||||
|
<script src="https://cdnjs.snrat.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
|
||||||
|
<script src='https://r2.337845818.best/tamabox/cdn/js/remake/easy.qrcode.min.js' type="text/javascript" charset="utf-8"></script>
|
||||||
|
<center><div id="boxqrimg"></div></center>
|
||||||
|
<script type="text/javascript">
|
||||||
|
var options = {
|
||||||
|
text: window.location.href,
|
||||||
|
width: 200,
|
||||||
|
height: 200,
|
||||||
|
// 与 Profile 编辑器保持一致:仅当启用自定义前景色时,才把 Qrcodebackcolor 作为前景色;
|
||||||
|
// 否则强制黑色 #000000,避免未勾选却显示自定义前景色、与 Profile 预览不一致。
|
||||||
|
colorDark: ({{.PageUser.UseCustomQRColor}} ? "{{.PageUser.Qrcodebackcolor}}" : "#000000") || "#000000",
|
||||||
|
colorLight: "{{.PageUser.Qrcodecolor}}" || "#FFFFFF",
|
||||||
|
dotScale: parseFloat("{{.PageUser.Dotscale}}") || 0.4,
|
||||||
|
dotScaleTiming: parseFloat("{{.PageUser.Dotscale}}") || 0.4,
|
||||||
|
dotScaleA: parseFloat("{{.PageUser.Dotscale}}") || 0.4,
|
||||||
|
correctLevel: QRCode.CorrectLevel.H,
|
||||||
|
logo: (function () {
|
||||||
|
// ?v=2:击穿曾被无 ACAO 响应污染的浏览器缓存条目;仅对 http(s) 绝对地址追加
|
||||||
|
var a = "{{.PageUser.Avatar}}" || "{{.DefaultAvatar}}";
|
||||||
|
return a ? (a.indexOf("http") === 0 ? a + "?v=2" : a) : undefined;
|
||||||
|
})(),
|
||||||
|
logoWidth: 60,
|
||||||
|
logoHeight: 60,
|
||||||
|
logoBackgroundTransparent: true,
|
||||||
|
// 直连 R2 等跨域图片须以 CORS 模式加载,canvas 才不被污染、可正常导出
|
||||||
|
crossOrigin: 'anonymous',
|
||||||
|
backgroundImage: ("{{.PageUser.BackgroundImage}}" ? "{{.PageUser.BackgroundImage}}" : undefined),
|
||||||
|
backgroundImageAlpha: parseFloat("{{.PageUser.Backgroundimagealpha}}") || 0.8,
|
||||||
|
autoColor: false,
|
||||||
|
PO: "{{.PageUser.Qrcodepdpcolor}}" || "#000000",
|
||||||
|
PI: "{{.PageUser.Qrcodepdpcolor}}" || "#000000",
|
||||||
|
AO: '',
|
||||||
|
AI: '',
|
||||||
|
timing: "{{.PageUser.Qrcodepdpcolor}}" || "#000000"
|
||||||
|
};
|
||||||
|
new QRCode(document.getElementById("boxqrimg"), options);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<p class="uk-text-center uk-text-small">扫码向@{{ .PageUser.Name }}提问<br>{{ if .RegisterOnlyAsk }}{{t .LangCode "ask.registerOnly"}}{{ else }}{{t .LangCode "ask.anonymous"}}{{ end }}</p>
|
||||||
|
{{ end }}
|
||||||
|
{{template "base/alert" .}}
|
||||||
|
{{template "question/new-question-template" .}}
|
||||||
|
|
||||||
|
<hr class="uk-divider-icon">
|
||||||
|
{{ if ne (len .PageQuestions) 0 }}
|
||||||
|
<p class="uk-text-left uk-text-muted uk-text-small">@{{ .PageUser.Name }} 以前回答过的问题 ({{ .AnsweredCount }})</p>
|
||||||
|
{{ template "question/history-template" . }}
|
||||||
|
{{ end }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{{template "base/footer" .}}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -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 <span class=\"uk-text-bold\">\"Show my tags on the homepage\"</span>. This feature is off by default. To get discovered here, go to <a href=\"/user/profile\" class=\"uk-text-bold\">your profile settings</a> 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.<b>This action cannot be undone. Please be careful!</b>",
|
||||||
|
"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": "<strong>Please save the private link below!</strong> Since you didn't leave an email, this link (including the token) is your <strong>only credential</strong> 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",
|
||||||
|
}
|
||||||
@@ -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": "ここでは<span class=\"uk-text-bold\">「ホームでタグを表示」</span>を有効にしたユーザーを紹介しています。この機能は初期状態でオフです。自分の質問箱を見つけてもらいたい場合は <a href=\"/user/profile\" class=\"uk-text-bold\">個人設定</a> から有効にしてください。",
|
||||||
|
"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": "いつでもアカウントを停止できます。停止後はログインできなくなり、質問箱のページや質問にもアクセスできなくなります。新しい質問も受け付けられません。<b>この操作は取り消せません。ご注意ください!</b>",
|
||||||
|
"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": "<strong>以下のプライベートリンクを必ず保存してください!</strong>メールアドレスを入力しなかったため、このリンク(トークンを含む)が質問の確認・回答の受信・追加質問のための<strong>唯一の証拠</strong>です。失くすと復元できません。",
|
||||||
|
"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つのパスワードが一致しません",
|
||||||
|
}
|
||||||
@@ -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": "此处展示已开启<span class=\"uk-text-bold\">“在首页展示我的标签”</span>的用户。该功能默认关闭,若希望自己的提问箱在这里被发现,请前往 <a href=\"/user/profile\" class=\"uk-text-bold\">个人设置</a> 手动开启。",
|
||||||
|
"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": "您随时可以选择停用您的账号。停用后,您的账号将无法登录,您的提问箱页面以及提问将无法访问,其他人也无法再给您发送新的提问。<b>该操作无法撤销!请谨慎操作!</b>",
|
||||||
|
"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": "<strong>请务必保存下面的私密链接!</strong>由于你没有留下邮箱,此链接(含口令 Token)是你查看提问、接收回答与继续追问的<strong>唯一凭证</strong>,丢失后将无法找回。",
|
||||||
|
"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": "两次输入的密码不一致",
|
||||||
|
}
|
||||||
@@ -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": "此處展示已開啟<span class=\"uk-text-bold\">「在首頁展示我的標籤」</span>的使用者。該功能預設關閉,若希望自己的提問箱在這裡被發現,請前往 <a href=\"/user/profile\" class=\"uk-text-bold\">個人設定</a> 手動開啟。",
|
||||||
|
"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": "您隨時可以選擇停用您的帳號。停用後,您的帳號將無法登入,您的提問箱頁面以及提問將無法訪問,其他人也無法再給您發送新的提問。<b>該操作無法撤銷!請謹慎操作!</b>",
|
||||||
|
"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": "<strong>請務必保存下面的私密連結!</strong>由於你沒有留下信箱,此連結(含口令 Token)是你查看提問、接收回答與繼續追問的<strong>唯一憑證</strong>,遺失後將無法找回。",
|
||||||
|
"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": "兩次輸入的密碼不一致",
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
<p class="{{ if .IsPixel }}uk-container{{end}} uk-text-right uk-text-muted uk-text-small">
|
||||||
|
{{t .LangCode "site.footer.visitor" `<span id="busuanzi_value_site_uv"><span class="tb-spinner"></span></span>` | safe}} | {{t .LangCode "site.footer.pageview" `<span id="busuanzi_value_page_pv"><span class="tb-spinner"></span></span>` | safe}}
|
||||||
|
<br>Powered by NekoBox | {{ ICP }}<br>{{t .LangCode "site.footer.runtime"}}:<span id="box_runtime"></span>
|
||||||
|
<br>
|
||||||
|
<!--<a href="/pixel">画板</a> | -->
|
||||||
|
<a href="https://box.tama.guru/_/tamakyi" target="_blank">{{t .LangCode "site.footer.admin"}}</a>
|
||||||
|
| <a href="https://blog.tama.guru" target="_blank">{{t .LangCode "site.footer.notice"}}</a>
|
||||||
|
| <a href="https://chat.tama.guru" target="_blank">{{t .LangCode "site.footer.chat"}}</a>
|
||||||
|
| <a href="https://share.tama.guru" target="_blank">{{t .LangCode "site.footer.drive"}}</a>
|
||||||
|
| <a href="https://status.tama.guru" target="_blank">{{t .LangCode "site.footer.status"}}</a>
|
||||||
|
| <a href="https://tama.guru" target="_blank">{{t .LangCode "site.footer.nav"}}</a>
|
||||||
|
</p>
|
||||||
|
<br>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// 提交反馈(P0):点击任意表单的提交按钮后,立即把触发按钮变成「转圈 + 本地化文字」,
|
||||||
|
// 并禁用表单内全部按钮,物理阻止在上传/网络慢时的重复点击与重复提交。
|
||||||
|
// 浏览器前进/后退(bfcache)回到本页时自动复位,避免停留在禁用或转圈状态。
|
||||||
|
// 纯内联反馈,不使用全屏遮罩。
|
||||||
|
var SUBMIT_I18N = {
|
||||||
|
submitting: '{{t .LangCode "common.submitting"}}',
|
||||||
|
uploading: '{{t .LangCode "common.uploading"}}'
|
||||||
|
};
|
||||||
|
|
||||||
|
function tbResetSubmitButtons() {
|
||||||
|
document.querySelectorAll('button[data-tb-submitting]').forEach(function(b) {
|
||||||
|
b.disabled = false;
|
||||||
|
b.removeAttribute('data-tb-submitting');
|
||||||
|
var orig = b.getAttribute('data-tb-restore');
|
||||||
|
if (orig !== null) {
|
||||||
|
b.innerHTML = orig;
|
||||||
|
b.removeAttribute('data-tb-restore');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('submit', function(e) {
|
||||||
|
var form = e.target;
|
||||||
|
if (!form || form.tagName !== 'FORM') return;
|
||||||
|
|
||||||
|
// 页面级提交反馈必须尊重前置校验:投票编辑页等 onsubmit 返回 false 时,
|
||||||
|
// submit 事件仍可能继续到达此监听器;此时绝不能切换到“提交中”状态。
|
||||||
|
if (e.defaultPrevented || form.getAttribute('data-tb-skip-submit-feedback') === '1') {
|
||||||
|
form.removeAttribute('data-tb-skip-submit-feedback');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 下载 / 新窗口类表单(target="_blank",如导出):当前页不发生导航,也没有 bfcache
|
||||||
|
// 复位机会,进入“提交中”状态后按钮会永远卡在转圈 + 禁用。这类表单直接跳过提交反馈。
|
||||||
|
if (form.getAttribute('target') === '_blank') return;
|
||||||
|
|
||||||
|
// 触发提交的按钮(programmatic submit 时 e.submitter 为 null,回退到首个 submit 按钮)
|
||||||
|
var trigger = e.submitter || form.querySelector('button[type="submit"]');
|
||||||
|
|
||||||
|
// 表单含已选中的文件 → 提示“上传中”,否则“提交中”
|
||||||
|
var hasFile = false;
|
||||||
|
form.querySelectorAll('input[type="file"]').forEach(function(f) {
|
||||||
|
if (f.files && f.files.length > 0) hasFile = true;
|
||||||
|
});
|
||||||
|
var label = hasFile ? SUBMIT_I18N.uploading : SUBMIT_I18N.submitting;
|
||||||
|
|
||||||
|
if (trigger && trigger.tagName === 'BUTTON') {
|
||||||
|
trigger.setAttribute('data-tb-restore', trigger.innerHTML);
|
||||||
|
trigger.innerHTML = '<span uk-spinner="ratio: 0.6"></span> ' + label;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 禁用表单内所有按钮,防止重复提交
|
||||||
|
form.querySelectorAll('button').forEach(function(b) {
|
||||||
|
b.disabled = true;
|
||||||
|
b.setAttribute('data-tb-submitting', '1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// bfcache 还原时复位按钮
|
||||||
|
window.addEventListener('pageshow', tbResetSubmitButtons);
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
{
|
||||||
|
"page": 1,
|
||||||
|
"perPage": 3,
|
||||||
|
"totalItems": 3,
|
||||||
|
"totalPages": 1,
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"collectionId": "tamabox",
|
||||||
|
"collectionName": "tamabox-changelogs",
|
||||||
|
"content": "新增:用户私信功能上线,可在「我的」页查看匿名来信。<br>\n修复:移动端问题列表间距过窄的问题。<br>\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": "修复:部分旧浏览器下时间显示异常。<br>\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"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,78 @@
|
|||||||
|
<p class="{{ if .IsPixel }}uk-container{{end}} uk-text-right uk-text-muted uk-text-small">
|
||||||
|
<br>Powered by NekoBox | {{ ICP }}<br>{{t .LangCode "site.footer.runtime"}}:<span id="box_runtime"></span>
|
||||||
|
<br>
|
||||||
|
<!--<a href="/pixel">画板</a> | -->
|
||||||
|
<a href="https://box.tama.guru/_/tamakyi" target="_blank">{{t .LangCode "site.footer.admin"}}</a>
|
||||||
|
| <a href="https://blog.tama.guru" target="_blank">{{t .LangCode "site.footer.notice"}}</a>
|
||||||
|
| <a href="https://chat.tama.guru" target="_blank">{{t .LangCode "site.footer.chat"}}</a>
|
||||||
|
| <a href="https://share.tama.guru" target="_blank">{{t .LangCode "site.footer.drive"}}</a>
|
||||||
|
| <a href="https://status.tama.guru" target="_blank">{{t .LangCode "site.footer.status"}}</a>
|
||||||
|
| <a href="https://tama.guru" target="_blank">{{t .LangCode "site.footer.nav"}}</a>
|
||||||
|
</p>
|
||||||
|
<br>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// 提交反馈(P0):点击任意表单的提交按钮后,立即把触发按钮变成「转圈 + 本地化文字」,
|
||||||
|
// 并禁用表单内全部按钮,物理阻止在上传/网络慢时的重复点击与重复提交。
|
||||||
|
// 浏览器前进/后退(bfcache)回到本页时自动复位,避免停留在禁用或转圈状态。
|
||||||
|
// 纯内联反馈,不使用全屏遮罩。
|
||||||
|
var SUBMIT_I18N = {
|
||||||
|
submitting: '{{t .LangCode "common.submitting"}}',
|
||||||
|
uploading: '{{t .LangCode "common.uploading"}}'
|
||||||
|
};
|
||||||
|
|
||||||
|
function tbResetSubmitButtons() {
|
||||||
|
document.querySelectorAll('button[data-tb-submitting]').forEach(function(b) {
|
||||||
|
b.disabled = false;
|
||||||
|
b.removeAttribute('data-tb-submitting');
|
||||||
|
var orig = b.getAttribute('data-tb-restore');
|
||||||
|
if (orig !== null) {
|
||||||
|
b.innerHTML = orig;
|
||||||
|
b.removeAttribute('data-tb-restore');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('submit', function(e) {
|
||||||
|
var form = e.target;
|
||||||
|
if (!form || form.tagName !== 'FORM') return;
|
||||||
|
|
||||||
|
// 页面级提交反馈必须尊重前置校验:投票编辑页等 onsubmit 返回 false 时,
|
||||||
|
// submit 事件仍可能继续到达此监听器;此时绝不能切换到“提交中”状态。
|
||||||
|
if (e.defaultPrevented || form.getAttribute('data-tb-skip-submit-feedback') === '1') {
|
||||||
|
form.removeAttribute('data-tb-skip-submit-feedback');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 下载 / 新窗口类表单(target="_blank",如导出):当前页不发生导航,也没有 bfcache
|
||||||
|
// 复位机会,进入“提交中”状态后按钮会永远卡在转圈 + 禁用。这类表单直接跳过提交反馈。
|
||||||
|
if (form.getAttribute('target') === '_blank') return;
|
||||||
|
|
||||||
|
// 触发提交的按钮(programmatic submit 时 e.submitter 为 null,回退到首个 submit 按钮)
|
||||||
|
var trigger = e.submitter || form.querySelector('button[type="submit"]');
|
||||||
|
|
||||||
|
// 表单含已选中的文件 → 提示“上传中”,否则“提交中”
|
||||||
|
var hasFile = false;
|
||||||
|
form.querySelectorAll('input[type="file"]').forEach(function(f) {
|
||||||
|
if (f.files && f.files.length > 0) hasFile = true;
|
||||||
|
});
|
||||||
|
var label = hasFile ? SUBMIT_I18N.uploading : SUBMIT_I18N.submitting;
|
||||||
|
|
||||||
|
if (trigger && trigger.tagName === 'BUTTON') {
|
||||||
|
trigger.setAttribute('data-tb-restore', trigger.innerHTML);
|
||||||
|
trigger.innerHTML = '<span uk-spinner="ratio: 0.6"></span> ' + label;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 禁用表单内所有按钮,防止重复提交
|
||||||
|
form.querySelectorAll('button').forEach(function(b) {
|
||||||
|
b.disabled = true;
|
||||||
|
b.setAttribute('data-tb-submitting', '1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// bfcache 还原时复位按钮
|
||||||
|
window.addEventListener('pageshow', tbResetSubmitButtons);
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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, "[email protected]", &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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 `<li>` 加 `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(含 <b>)保留在其按钮组下方(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 面板改两段结构:私聊专属 = `<section class="tb-pcard chat-zone">` 内含 FeatureChat partial + `<hr>` + 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。
|
||||||
|
|
||||||
@@ -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 后新增补丁 `<style>`(.uk-light 黑字 3 条规则 + 扩展警告注释)
|
||||||
|
4. 头部 preconnect 增加 `https://cdnjs.snrat.com`(注释同步更新,原"全部归拢 R2"说法过时)
|
||||||
|
- 验证:go test ./templates(TestTemplatesParse/TestTemplateCrossReferences/TestRenderPublicQuestionList 等)全 PASS;CSS 括号配对/规则数 3 条自检通过。
|
||||||
|
- 未做(用户排除):Rocket Loader(cloudflare-static/rocket-loader.min.js 1100ms)需在 Cloudflare 后台关闭 Speed→Rocket Loader。
|
||||||
|
- 注意:原 R2 路径 `.../expire-1-y/uikit/3.3.3/css/modify-black-font/uikit.min.css` 仍保留可访问(回滚用)。若日后引入 .uk-card-primary 等容器需黑字,须扩展补丁(参考此节差异清单)。
|
||||||
|
|
||||||
|
## UIkit 迁移生产/测试环境验收(对比通过)
|
||||||
|
|
||||||
|
- 部署后对比(真实浏览器 computed style 实测,agent-browser eval,注意本会话模型不可读图、勿再用"看截图"断言):
|
||||||
|
- 生产 box.tama.guru/_/tamakyi(旧代码):uikitSheet=r2 modify-black-font;.uk-light 容器色 rgba(0,0,0,.7);navbar_bg rgb(248,248,248);username 内联色 rgb(0,123,255)(小狼账号自设蓝)、intro rgb(205,76,108)(自设粉)。
|
||||||
|
- 测试 box-dev-api.337845818.best/_/admin6(新部署):uikitSheet=cdnjs.snrat.com 官方;.uk-light 容器色 rgba(0,0,0,.7)(补丁生效=modify-black-font 等价);navbar_bg rgb(248,248,248) 一致;username/intro 内联色 rgb(0,0,0)(admin6 账号默认黑,非 CSS 差异)。
|
||||||
|
- 结论:UIkit 相关 computed style 两环境逐值一致 → 迁移无回归。用户名/简介颜色差异仅来自各账号服务端颜色字段。
|
||||||
|
- 环境坑记录:agent-browser 冷启动需 `agent-browser install`(Chrome 152 下载 193MB,卡住原因=缺浏览器);open+eval 组合命令易超时被 auto-background,应 open 与 eval 分两条命令执行;本环境 curl 落盘/-o /dev/null 偶报 error 23 但不影响数据(可改 stdout+管道)。Chrome 位置 C:\Users\Tamakyi Gekka\.agent-browser\browsers\chrome-152.0.7977.82。
|
||||||
|
|
||||||
|
## uikit R2 vs snrat 国内外测速(5 次全量下载中位,2026-09-05)
|
||||||
|
|
||||||
|
- 国内本机:OLD-css 0.864s→NEW 0.200s(4.3x);OLD-js 0.796→NEW 0.163(4.9x);OLD-icons 0.824→NEW 0.177(4.7x)。三资源合计 2.48s→0.54s,净省 ~1.9s。
|
||||||
|
- 国外 check-host.net 多节点(两轮):CSS p50 R2 240-358ms vs snrat 233-420ms ≈ 打平(R2 偶发长尾 max 3.3-4.8s,snrat 平稳 ≤896ms);JS p50 R2 372ms vs snrat 647ms,R2 快 ~40%。
|
||||||
|
- 结论:snrat 国内完胜;海外 R2(Cloudflare 全球边缘)略优/打平。站点访客以国内为主 → 切 snrat 净收益大。若未来在意海外可 geo 双源(国内 snrat / 海外 R2),当前不做(过度设计)。
|
||||||
|
- 测速脚本已归档 dev/bench-cdn.sh(cn=国内 5 次全量取中位 / global=check-host.net 海外 p50/p90),cn 模式冒烟通过(复测数据与基线一致)。
|
||||||
|
|
||||||
|
## 部署架构澄清(用户补充 + 实测确认)
|
||||||
|
|
||||||
|
- 用户架构:正式 box.tama.guru 与测试 box-dev-api.337845818.best 均经 Cloudflare Tunnel 开放;box.tama.guru 是国内走腾讯 EdgeOne 的双入口。
|
||||||
|
- 实测(国内本机/出口视角):box.tama.guru → 43.174.247.43 Server: TencentEdgeOne(HTML 无 rocket-loader 注入,干净);box-dev-api.337845818.best & r2.337845818.best → 172.67.144.141 Server: cloudflare CF-RAY AMS(HTML 含 rocket-loader);cdnjs.snrat.com → 101.227.21.24(国内节点)。
|
||||||
|
- 推论:Rocket Loader 只在 Cloudflare 边缘对走 CF 的请求注入 → 仅影响海外路径与测试域名;国内 EdgeOne 路径 HTML 干净(EdgeOne 回源直连源站不经 CF HTML 重写)。本机出口连 CF 落在 AMS(阿姆斯特丹)→ 本机测 R2 慢不代表真实国内用户(其可能经 CF 亚洲/香港节点),但 snrat 国内节点快是实打实。
|
||||||
|
- 待用户确认:① 之前 1100ms rocket-loader 截图是否来自海外/测试域名或未接 EdgeOne 前 ② r2.337845818.best 是否也接 EdgeOne(未接 → 静态资源国内仍可能慢,是后续优化重点)③ CF 侧 Rocket Loader zone 开关位置。
|
||||||
|
- 【用户澄清+盘点完成】①截图=PageSpeed(海外探测),非国内 ②r2.337845818.best 未接 EdgeOne ③DNS 分流架构:dnspod 按境内/境外解析 box.tama.guru,境内 EdgeOne/境外 Cloudflare。据此修正认知:国内不受 Rocket Loader 影响;国内真实瓶颈=R2 的 CF 国际链路。全量盘点 r2 静态资源(outputs/r2-assets-cdn-audit-2026-09-05.md):sha256 校验 6 个 JS 库(jquery/dayjs/alpine/cropperjs/vConsole/waline.js)=纯官方原版;实测 R2 每资源 0.72-1.10s vs snrat 0.15-0.42s(2-7.4×);关键认知=公共 CDN(cdnjs.cloudflare/jsdelivr 0.6-1.8s)≠快,要选 snrat 国内节点。waline-no-commits.css 为刻意定制(39 条 .wl-card display:none 隐藏评论列表,与官方选择器全同)不可直换官方。easy.qrcode=remake 定制、neko-pixel 0.0.21 npm 查无、time.box.js/图片图标=专属 → 无公共源。建议:方案 A(R2 接 EdgeOne 根治定制文件)+方案 B(A 组 5 库迁 snrat) 组合,待用户批准。
|
||||||
|
- 【重大认知修正 + 方案落地】itdog 大陆多节点测速(用户截图):box.tama.guru(EO新加坡,43.174.247.43)大陆均值 3.2-3.6s、三网骨干峰值 9-11s(四川电信 11.1s);box-dev-api(纯 CF,172.67.144.141/147.52/80.1)大陆均值 5.7-6.5s、峰值 12s。**反向分布**:港澳台/新疆/内陆部分省份反而 300-500ms。结论:① CF 与 EO 单走大陆都慢 3-12s,CF tunnel 不是备案前解药,删 DNS 分流的方案被证伪 ② R2 大陆实测 ~250ms 正常,静态资源非瓶颈 ③ 真正瓶颈=大陆→境外源站(EO新加坡/CF边缘)动态页链路。Rocket Loader 用户已手动关闭,HTTP/3 已开启。后端审计初步:box-dev-api 的 /favicon.ico→302 首页、robots.txt 1.1-2.4s(本机 AMS 视角)、cf-cache-status: BYPASS → 静态未缓存且每次回源,存疑点待大陆视角复核。根本解决路径只剩备案+大陆 CDN(腾讯云/阿里云,或 CF 中国伙伴京东云/世纪互联),备案前可做项=静态库迁 snrat。方案 B 已落地:jquery3.7.1/dayjs1.10.8/alpine3.9.0/cropper1.6.2(js+css 用 min 版)/vConsole3.12.1/waline2.15.8 共 7 文件全部 sha256 校验一致后 R2→cdnjs.snrat.com(4 文件:header/list/question-not-found/profile),备份在 .workbuddy/backup/cdn-migration-20260905/,go test templates 通过。R2 保留:easy.qrcode remake/waline-no-commits.css/time.box.js/pickr(1.10.1 snrat 404 未收录)/neko-pixel 0.0.21/logo/社交图标。
|
||||||
|
- 【snrat 部署验收通过】用户部署 box-dev-api 后用浏览器实测 admin6 主页:HTML 全部 snrat 引用已生效(uikit/css/js/icons、dayjs/alpinejs、waline.js/jquery/min),无 Rocket Loader 注入。document.readyState=complete,UIkit/Dayjs/jQuery/Waline 全局对象全部存在,UIkit 组件(navbar、tab、表单、按钮)渲染完整、.uk-light 补丁正确生效、定制文件(waline-no-commits/easy.qrcode remake/time.box.js/社交图标)继续走 R2 无回归。截图已存 outputs/admin6-snrat-check.png。验收小波折:open+eval 组合命令易卡顿(已分步解决),首次 eval 在 defer 脚本未执行完时探测 typeof UIkit=false 属时序问题,等 3s 后 UIkit=true。
|
||||||
|
- 【生产部署验收通过】box.tama.guru 主页/用户页 HTML 引用全部确认(uikit/dayjs/alpinejs/jquery/waline.js → cdnjs.snrat.com,旧 R2 库残留=0,定制文件 waline-no-commits/time.box.js/tamabox_low.png 继续 R2 200 可达)。浏览器实测 /_/tamakyi:UIkit/dayjs/jQuery/Waline 全局对象全部就位(UIkit=function)、navbar rgb(248,248,248)、.uk-light rgba(0,0,0,.7) 补丁生效、用户名 rgb(0,123,255) 账号自设色、28 UIkit 按钮,无回归。截图 outputs/prod-tamakyi-snrat-check.png。⚠️ 踩坑记录:agent-browser 探测 defer JS 库有显著时序窗口——本机(AMS 出口)拉 snrat 国内节点 133KB uikit.min.js 需数秒,过早 eval typeof UIkit=false 属假阴性;且 CDN 无 Timing-Allow-Origin 时 resource timing 全 0 属正常。正确姿势:open 后 sleep≥8 再 eval,或先 fetch 触发等待;判断库是否成功以全局对象(typeof)为准,勿信 resource timing。
|
||||||
|
- 【后端审计补完】澄清两个疑点+确认一个真问题:① /favicon.ico、/robots.txt、/ 的 302 是 curl -sSI(HEAD) 假象——flamego f.Get 路由对 HEAD 不匹配返回 302,GET 全部 200,浏览器无影响,撤稿之前"favicon 302"结论。② 真问题:route.go 的 favicon/robots/sitemap/llms/llms-full 5 个 embed handler 只设 Content-Type 无 Cache-Control → CF cf-cache-status: BYPASS、EdgeOne Age:0 每次回源 tunnel。全项目仅 share.go:501 share-card 设了 public max-age=300;/static/* 由 flamego.Static CacheControl 统一 86400。③ 动态页 HTML 无缓存头是预期(个性化),edge 每次回源属免备案架构使然。待批修复:5 个 handler 各加 Cache-Control: public, max-age=86400(约 5 行,纯增益)。源站不在本机(无 cloudflared/tamabox 进程),localhost 直测不可行。
|
||||||
|
- 【修复落地】route.go 5 个 embed 静态 handler(/favicon.ico /robots.txt /sitemap.xml /llms.txt /llms-full.txt)各加 Cache-Control: public, max-age=86400。验证:gofmt 干净 + go build -overlay 编译通过 + go test ./internal/route/ 通过。⚠️ 环境坑记录:Windows 本机全量 go build/go test 会因 chai2010/webp@v1.4.0(cgo 依赖 libwebp) 报 undefined webpGetInfo 等——需用 dev/webpstub 机制:dev/overlay.json 已失效(指向旧仓库路径 TamaBox-v4-time),正确姿势=自建 overlay 把 internal/storage/s3.go 替换为 stub(s3.go 导出符号仅 MaxUploadBytes/UploadAvatarToS3/UploadBackgroundToS3/UploadPictureToS3/ConvertStaticImageToWebP + oss.go 引用的私有 isSupportedImage),本次 stub 存 %TEMP%/s3_stub_tamabox.go、overlay 存 %TEMP%/ov-tamabox.json,命令:go build/test -overlay=...。部署链:Dockerfile CGO_ENABLED=0 + go build ./cmd/(生产无碍)。
|
||||||
|
- 【测试环境缓存修复验收】box-dev-api 5 路径(favicon/robots/sitemap/llms/llms-full)响应均已带 Cache-Control: public, max-age=86400(HTTP 200)。⚠️ CF 缓存机制要点:无 cookie 首访 → session 中间件 Set-Cookie(flamego_session) → cf-cache-status: BYPASS 永不缓存;带有效 cookie 请求 → 不 Set-Cookie → MISS→HIT(Age 递增) 正常缓存。真实浏览器=先访问 HTML 已种 cookie→后续 favicon 等请求均带 cookie→缓存命中;无 cookie 场景仅 curl 首访/搜索引擎爬虫(低频,可接受)。测试环境通过,用户将部署生产。若日后想让爬虫也命中缓存:把静态路由挪到 session 中间件之前或让 session 跳过静态路径(本次未做)。
|
||||||
|
- 【答疑】/.well-known/pki-validation/fileauth.txt 删除后仍被爬:① 线上实测两环境均 302→/(Go http.Redirect 标准输出),文件内容确已删除生效;② 请求持续=全网证书/安全扫描器将 .well-known/pki-validation 与 acme-challenge 同列标准探测目标,按字典批量扫所有域名,与文件是否存在无关;③ 302 来源=route.go:396 f.NotFound handler(先 ab.Record 404 计数再 ctx.Redirect("/"),注释说明 flamego NotFound 先写 404 再 302);④ 噪音放大:探测 302→扫描器跟随→再请求 / 首页,日志翻倍且 CDN 不缓存 302(EO-Cache-Status: MISS/DYNAMIC)每次回源。治理可选:CDN 规则边缘拦 .well-known/*(推荐,零回源)/f.NotFound 对探测路径直接 404 不 302/autoban 敏感路径加速封禁。等待用户选方向。
|
||||||
|
- 【架构澄清+瓶颈定位实验设计】用户澄清架构:海外=CF+tunnel+优选网络;国内=EdgeOne 直连源站 IP(回源不走 tunnel)。质疑"大陆→境外源站"归因。回应要点:大陆用户连的是 EO 节点非源站(此前表述简写失准),但 EO 国际站无大陆 PoP(43.174.247.43=新加坡),"境外段"=大陆→EO 新加坡节点(itdog 3-11s 证据即此段)。分离实验:生产 robots.txt 已确认 EO HIT 缓存(MISS→HIT Age 2/3,证明 cache-control 5 行修复已部署生产生效)→ 用户 itdog 对比 robots.txt(HIT 零回源) vs /_/tamakyi(每次回源),差异=EO→源站回源段+源站处理;若 robots 也 3s+ 则瓶颈纯在大陆→EO 段与回源方式无关。需用户补测+告知源站位置(决定回源段性质:源站大陆则 EO 新加坡→大陆回源也属国际链路)。
|
||||||
|
- 【链路分解实测完成】用户确认服务器在境外。三组实测:① 本机 curl(AMS 出口):robots.txt(EO HIT 零回源) 0.6-2.2s 波动 vs 动态页 /_/tamakyi ttfb 0.87-1.46s——EO HIT 也波动大,非回源差异;② check-host.net 全球 25 节点:robots.txt(EO HIT) p50=1258ms min505(us2) vs 动态页(回源) p50=1217ms min735(jp1)——**两者几乎相同**→ 证明 EO→境外源站回源段快(服务器境外),动态页不比零回源静态慢;③ agent-browser 页面级(AMS):TTFB 348ms、HTML download 555ms、load_total 1.1s、最慢资源 log beacon 1944ms。结论:动态页慢的根因=用户→EO 新加坡节点段(大陆 itdog 3-11s 因国际出口拥塞;连欧美节点也 0.5-2.7s 因 EO 国际站无大陆 PoP 且节点网络质量差),与回源方式(tunnel/优选/直连IP)无关。对照:snrat(国内 cdnjs 镜像) 全球 p50 仅 257ms ≪ EO p50 1258ms,EO 国际站全球表现差。根治=备案+大陆 CDN。
|
||||||
|
- 【HTML 压缩评估】生产 /_/tamakyi:原文 61,125B(内联 style 11 块 19,972B + 内联 script 10 块 14,048B + 外链 9js/2css + 空白 4KB)。gzip 已在源站开启(internal/route/gzip.go GzipHandler 挂 http.Server 最外层,处理 204/304/嗅探/Flusher,不主动 flush 单块输出;EO 透传带 Vary),gzip-9 后仅 14,966B(24%)。无显式 Flush 调用点 → 无多次 RTT 问题。结论:压缩已最优;555ms download 主因是高 RTT 非体积;内联 CSS 20KB 是设计(高 RTT 下内联优于外链+缓存),不建议外链化;剩余微优化(minify 内联块/去空白)收益 <1KB gzip,无意义。真正优化=降 RTT(大陆 CDN)。
|
||||||
|
- 【EO 优选调研】结论:①有,社区"EO 优选 IP"玩法与 CF 优选同原理:EO 官方 CNAME 把大陆调度到新加坡(43.174.247.43 AS139341 ACE)慢,社区做法=DNS 改 A 记录直指香港等优质 EO 边缘 IP(43.174.150.x 香港同 AS)。数据源 wetest.vip(page/edgeone/address_v4 需登录,15min 更新)/cf2dns 面板/archlinuxcn forum 教程。②实测:xhh 教程香港 IP 43.174.150.199/119 已失效(000,时效性强需活源+月度更新);EO 大陆可达节点列表(EdgeOne-ips-Checker available_eofreecn_ips 167 个大陆 IP)接口 2026-07-31 停服 8-31 下线,实测全 000 → B 类已死。③EO 官方内建"自研协议优化/回源链路探测"(类 Argo)但无法解决无大陆 PoP;优选只能把边缘从新加坡换香港(大陆 3-11s→预计 50-200ms,待 itdog 验证)。④落地=dnspod 境内线路解析值改 A 记录指向活香港 EO IP(多 IP+TTL60-300s+月度更新),境外保持 CF。风险:灰色玩法/证书 SNI 需实测/EO 不承诺。结论已回复用户,未动手改 DNS。
|
||||||
|
|
||||||
|
## EO 优选方案 B 免费实测(用户排除付费 wetest.vip 后执行)
|
||||||
|
- 【用户确认】方案 B=自扫或公开 CNAME 均可,不限香港,周边区域比新加坡好即可。
|
||||||
|
- 【免费公开源全灭实测】wetest.vip 需会员(公开页0 IP);*.v1/v4.eo.fastlydns.cn、eo.072103.xyz、eo.088086.xyz 全部 NXD;蓝点网/雾创岛 43.174.150.x 香港 IP 证书已退回 *.cdn.myqcloud.com(CDN 通用池) 全失效。博客佐证(2026-02):"EO 现在不能使用优选节点,非适用节点返回 418"。
|
||||||
|
- 【方法论修正】TLS 握手成功≠可用(腾讯 CDN 泛播池也握手);正确判据=schannel 证书校验过(CN=box.tama.guru)+HTTP 200+Server: TencentEdgeOne。
|
||||||
|
- 【扫描事实】43.174/43.175 全 /16 抽样(3072)+官方段/HK/JP 细扫(56 /24≈14000 IP):能服务 box.tama.guru 的 EO 池 9 段全新加坡(192-195/218/240-241/246-247);EO 泛播确实同步全球——HK(43.175.115/119/43.174.126 共8 IP)、东京(43.175.16/17/18/113 共6)、大阪 107.217、AMS/DXB 零星可服务。
|
||||||
|
- 【南宁电信视角(真实大陆)】官方新加坡 TCP 180ms/TTFB 0.8-1.0s 反而最优;香港候选 351-377ms/TTFB 1.3-1.8s、东京 276-299ms/TTFB 1.1-4.0s(不稳) 均更慢 → 官方 CNAME 即 EO 对大陆优化调度,自扫候选跨境路由绕。单点结论≠全国,华南可能反转,已列 15 个候选 IP 待用户 itdog 多节点验证(报告 outputs/eo-free-probe-2026-09-05.md)。
|
||||||
|
- 【工具沉淀】dev/eo-probe-ips.py(TLS快速预筛)、dev/eo-probe-v2.py(schannel 严格判定,可复用任意域名)、dev/eo-scan-all.py(TCP+openssl 两段式大范围扫描)。
|
||||||
|
- 【下一步】用户 itdog 验证候选 vs 新加坡;若均不优→方案 B 到此为止(免费优选时代窗口 2025中-2026初已关),剩余=备案+大陆CDN 或维持现状。
|
||||||
|
|
||||||
|
## 头像+二维码加载慢诊断(个人主页 /_/tamakyi,南宁电信实测)
|
||||||
|
- 【根因1 P0】R2( r2.337845818.best ) 图片对象全部无 Cache-Control(仅 ETag+Last-Modified,cf-cache-status: DYNAMIC);头像 Last-Modified=当天→启发式缓存≈0→每次页面加载重下头像。304 也 1.05s(RTT 省不掉)。上传代码 s3.go PutObjectInput 从未设 CacheControl(已确认)。
|
||||||
|
- 【根因2 P0】R2 纯 CF 国际链路:南宁实测每资源 0.78-1.4s(头像 0.9-1.05s/背景 297KB 1.39s/logo js 0.96s/1.6KB time.box.js 也 0.9s=RTT 主导);snrat 大陆镜像 0.3-0.5s 作对照。
|
||||||
|
- 【根因3 P1】easy.qrcode.min.js(52KB,R2) logo 分支:头像 onload 才绘制,onerror 仅 console.error 无降级→头像挂/失败=二维码永久空白。
|
||||||
|
- 【根因4 P1】头像缓存键分裂:header.html icon/favicon 用 ?og-image=1(646-648),list.html+页面头像+QR logo 用 ?v=2 → 一页下载 2 份。
|
||||||
|
- 【根因5 P1】背景 box_background.png 303KB 未压缩 PNG(2024-08 上传未变)。
|
||||||
|
- 【根因6 P2】defer 统计脚本拖 DOMContentLoaded:vercount 1.24s(波动2.7s)/mami 波动3.7s → 二维码初始化(DCL)被拖。
|
||||||
|
- 【修复方向】P0① s3.go 加 CacheControl public,max-age=31536000,immutable(图片 key 随机不可变安全);P0② easy.qrcode onerror 降级无 logo 绘制+超时;P1③ 统一头像 query 键(og-image=1 无 Go 处理疑似遗留);P1④ 背景转 WebP≤60KB;P1⑤ 统计脚本 async;P2⑥⑦⑧(R2 前接 EO 回源=治本)。
|
||||||
|
- 报告 outputs/avatar-qrcode-slow-2026-09-05.md;抓包快照 outputs/tb-page-snapshot.html;库源码已存 dev/easy.qrcode.min.js、dev/time.box.js。
|
||||||
|
|
||||||
|
## P0 批落地:s3.go immutable 缓存头 + 二维码降级渲染(用户批准后执行)
|
||||||
|
- 【用户授权】"先备份当前源码,然后尝试吧"→ 执行诊断报告的 P0-① 与 P0-②。
|
||||||
|
- 【备份】.workbuddy/backup/p0-avatar-qrcode-20260905/(s3.go + header.html + list.html + question-not-found.html + profile.html,含修改前版本;header.html 修改前版本用脚本从当前版精确移除新增块生成,已与 cdn-migration 基线比对仅差上午 10 行 CDN 迁移改动,验证一致)。
|
||||||
|
- 【改动1 s3.go】uploadPictureToS3 的 PutObjectInput 增加 CacheControl: public, max-age=31536000, immutable(key=picture/日期/随机hex 内容不可变,安全)。SDK v1.47.5 PutObjectInput.CacheControl 字段验证存在;gofmt 通过。
|
||||||
|
- 【改动2 header.html】<body> 后新增全局 window.tbRenderQR(el, getOptions):核心修复 easy.qrcode logo/背景图加载失败仅 console.error 无降级导致二维码永久空白。策略=已知可用层立即绘制(logo 记忆命中零等待一次成型)→ 未知层先省略画基础码(立即可扫)→ Image 探针判定后重绘升级版;失败记忆 _tbQrGood/_tbQrBad 按 URL 同会话缓存;3s 超时兜底;迟到 onload 仍能补 logo。实测 8 个行为用例全过(node stub QRCode/Image)。
|
||||||
|
- 【改动3 三个调用点】list.html(公开主页)/question-not-found.html:new QRCode→tbRenderQR;profile.html updatePreview 同改(debounce 高频重绘场景靠 URL 记忆避免闪烁)。背景图分支(库内无 onerror 同风险)一并纳入降级。
|
||||||
|
- 【验证】go test ./templates/ 全绿(TestTemplatesParse/CrossReferences 等);8 行为用例 PASS;改动 diff 已复核为纯增量。
|
||||||
|
- 【部署注意】缓存头只对新上传对象生效;历史对象需手动(可用 CF 批量 purge 或 R2 重新上传);模板改动无后端逻辑变化。待用户部署后浏览器验证:二次访问头像应 0ms 级、头像坏链时二维码仍可扫。
|
||||||
|
|
||||||
|
## CORS/画布污染核查(P0-② 二维码降级改动安全性)
|
||||||
|
- 【结论】当前部署不会引发 CORS 失败或 canvas 污染。三个前提实测:① R2 已配 CORS 白名单,box.tama.guru 与 box-dev-api.337845818.best 均返回 ACAO(localhost:3000/example.com/裸域 无 ACAO);② list/profile options 显式 crossOrigin:'anonymous'(注释注明"直连 R2 跨域图须 CORS 模式"),tbRenderQR 默认同值,与库内 new Image 的 CORS 模式一致,探针与库绘制走同一缓存键;③ easy.qrcode 内部 makeImage 后调 this._elCanvas.toDataURL("image/png")(catch 后 console.error + 提示 "Configured crossOrigin:'anonymous'")——库开发者已内置该诊断。
|
||||||
|
- 【污染免疫原理】canvas 污染只发生在"no-cors 隐式加载成功但无 ACAO"的中间态;tbRenderQR 探针失败(onerror)→ 根本不 drawImage → 无污染;成功 → 响应必带 ACAO → 干净。不存在绘制了却污染的路径。
|
||||||
|
- 【边界提醒】R2 CORS 白名单只有 2 个源;新增页面域名/本地开发需先加白名单,否则 anonymous 探针 onerror → 降级基础码(可扫但永不带 logo,不报错)。favicon/og-image/meta 均非 canvas 上下文,无需 CORS 无污染风险(header.html 640-653 直指 R2)。
|
||||||
|
|
||||||
|
## P0 批测试环境验证(agent-browser 实测 box-dev-api.337845818.best/_/admin6)
|
||||||
|
- 【静态部署检查】HTML 含 tbRenderQR 2 次(helper 定义+1 调用)/ crossOrigin:'anonymous' 1 次 / logoBackgroundTransparent 2 次 / new QRCode(document.getElementById 为 0(已替换)→ 三处调用点全部到位。
|
||||||
|
- 【正常路径】#boxqrimg canvas 200x200、toDataURL 成功(base64 长 28578 无污染)、中心 20x20 像素全为非白非黑"other"且色相分布为深色照片调(4,4,3 棕色系 96 像素、7,6,1 等)→ 头像 logo 已绘制升级版。
|
||||||
|
- 【降级路径】临时 div 用坏头像 URL(不存在 picture path)调 tbRenderQR:立即态 canvas 已生成(len 4226 紧凑基础码、exportable true);3s 后状态保持(childCount 1、exportable true);_tbQrBad 写入坏 URL;_tbQrGood 同时记录真实页面头像 9af3e38?v=2 与背景图 25e2d84 → 双向印证降级免疫污染。
|
||||||
|
- 【加载中排查】页面 2 个 uk-spinner:"正在生成分享图…"(分享卡区正常态)+ captcha modal 内的"加载中..."(rect 全 0 不可见);"加载更多 加载中..."按钮 display:none → 均非主诉"全屏加载中"覆盖层。用户主诉已消除。
|
||||||
|
- 【截图】outputs/tb-dev-test-qr.png 全页、tb-dev-test-qr-crop.png 头部裁切:头像、用户名、提问按钮、二维码均已显示,无加载中残留。
|
||||||
|
- 【代理坑提醒】agent-browser open <url> 因测试站境外+defer 脚本多会卡 load 等待;可靠做法:先 agent-browser open (about:blank 启动 daemon) → 再 open <url> 导航 → 然后 sleep ≥10s 让 defer 脚本就绪再 eval。
|
||||||
|
- 【结论】P0 批(s3.go immutable 缓存头 + 二维码降级)测试环境验证全部通过,可部署生产。
|
||||||
|
|
||||||
|
## P0 批正式环境验证(agent-browser 实测 box.tama.guru/_/tamakyi)
|
||||||
|
- 【静态部署】HTML 60.1KB;tbRenderQR 2 次/调用点 1 处替换/crossOrigin 'anonymous' 1 次/logoBackgroundTransparent 2 次/new QRCode(document.getElementById 0;头像引用 r2.337845818.best/.../2e571390...(2026/09/05 新传)→ 与测试环境一致部署完整。
|
||||||
|
- 【正常路径】#boxqrimg canvas 200x200 exportable len 31726;中心 20x20 像素全为深色照片调(7,7,7 灰+蓝黑系)→ 头像 logo 已绘制。
|
||||||
|
- 【降级路径】坏 URL 测试:立即态 len 4226 基础码、3s 后保持 stillCanvas exportable len 4226 不空白;badMem=1、goodMem 含 2 个真实 URL(头像 2026/09/05 新头像 + 背景图 2024/09/22)→ 双向印证探针与降级免疫污染均正常。
|
||||||
|
- 【加载中残留】visibleLoading=[](精确定位 rect>0 且文本含"加载中"的可见元素);之前的 uk-spinner/captcha/loadmore 在生产页同样不可见。
|
||||||
|
- 【截图】outputs/tb-prod-test-qr.png:头像、二维码码眼完整、无加载中遮挡 → 与测试环境一致通过。
|
||||||
|
- 【坑补充】第一次 `agent-browser open | open URL` 链式启动 3+ 分钟无输出卡死(即使之前测试环境用同样命令成功),最终拆成单条独立命令即恢复。原因可能是 Chromium 冷启动资源紧张或 chain 顺序导致首条 stdin 未及时关闭。经验:永远单条命令、第一条单独跑。
|
||||||
|
- 【结论】P0 批正式环境全部通过;图片缓存头对老对象(2024/09/22 背景图)暂不生效,新上传对象生效,需要时间自然过渡。
|
||||||
|
|
||||||
|
## autoban 误伤诊断(用户 app.ini: window=10s, sensitive=10, 404=20, duration=15min, trust_proxy=true)
|
||||||
|
- 【机制】全站仅 2 个计数入口:中间件敏感路径 defer Record(autoban.go:39)+ f.NotFound 404 Record(route.go:403)。业务路由/模板 77 URL × 39 敏感词零碰撞 → 正常页面不误计。
|
||||||
|
- 【误伤根因】正常用户 10s 内凑不出 10 敏感/20 404 → 误伤必是"他人探测记到自己键上":P0-A IP 键折叠(EO 未透传 EO-Client-IP 时全大陆回退到 43.174.247.x 新加坡边缘共享键;CF tunnel 异常时回退 127.0.0.1);P0-B CGNAT 共享出口连坐(国内 NAT444 常态,管理员自伤主因);P1-C IPv6 /64 聚合连坐;P1-D 双 CDN 未删对端权威头可被伪造头定向嫁祸。
|
||||||
|
- 【止血配置】window 60s + sensitive 30 + 404 100 + security_alert_email 开(先看封禁 IP 判断折叠)。治本=EO 开回源 IP 透传 + 源站防火墙锁 CDN 网段 + 双 CDN 删对端头。
|
||||||
|
- 【代码增强候选】登录 session 豁免计数、封禁 logrus 日志、UA 二次确认。报告 outputs/autoban-false-positive-2026-09-05.md。
|
||||||
|
|
||||||
|
## autoban 策略修正实施:ban_track_notfound(用户选定"配置开关版")
|
||||||
|
- 【背景】生产新误伤案例 106.7.154.160(真实国内电信 IP,非 CDN 边缘):样本 /_/Liarcs×4 + /×2 全是计数事件;但 domain/题目不存在走 302(Pager/Questioner 均 ctx.Redirect)不计数 → 能进 f.NotFound 的多为非 GET 探测或未注册路径;告警 paths 仅 6 条且受 2min cleanup 影响可跨窗口累积 ≠ 触发原因;触发=10s 内 ≥20 次 f.NotFound 或 ≥10 敏感。疑似共享出口(CGNAT)连坐或目标性探测。
|
||||||
|
- 【评估结论】敏感通道 35 项扫描特征与业务路由全表零重叠→零误伤;404 通道是唯一误伤源但价值低(主流字典必碰敏感项;/_/{domain} 枚举靠 200/302 区分本来就抓不到)→ 砍 404 计数收益>损失。
|
||||||
|
- 【改动 5 文件,备份 .workbuddy/backup/autoban-track-notfound-20260905/】
|
||||||
|
1. internal/conf/static.go:Security 加 BanTrackNotFound bool `ini:"ban_track_notfound"`(默认 false)
|
||||||
|
2. internal/security/autoban/autoban.go:Options.TrackNotFound、Banner.trackNotFound、New 赋值;Record 对 KindNotFound && !trackNotFound 直接 return
|
||||||
|
3. internal/route/route.go:Options 传 TrackNotFound: conf.Security.BanTrackNotFound;f.NotFound 注释同步
|
||||||
|
4. internal/security/autoban/autoban_test.go:newTestBanner 默认 TrackNotFound:true;新增 TestNotFoundTrackDisabledByDefault;TestDefaults 断言 trackNotFound==false
|
||||||
|
5. conf/app.sample.ini:security 段加 ban_track_notfound = false + 注释(真实 app.ini 在各部署环境,需用户同步补键或留空=默认关)
|
||||||
|
- 【验证】gofmt 干净;go vet OK;go test 三包全绿(route/conf/autoban,带 -overlay=tb_overlay.json 规避 cgo webp);新用例 PASS。
|
||||||
|
- 【部署提醒】测试/生产 app.ini 无需强制加键(缺省 false 即关闭 404 计数);若想恢复 404 计数置 true。conf/app.ini 不在本地副本(conf/ 仅 app.sample.ini)。
|
||||||
|
|
||||||
|
## ban_track_notfound 测试环境实测(box-dev-api,出口=本机南宁电信)
|
||||||
|
- 【正常路径】/ + /_/admin3..admin9 全 200 无 403;不存在 domain ×8 → 302 不封(业务 302 通道确认);admin6 页 SSR title「admin6 - 狼的提问箱」正常。
|
||||||
|
- 【404 洪水】未注册路径 ×30 → 全 302(location:/) 不封(TrackNotFound=false 预期,但受 enable_auto_ban 前提约束)。
|
||||||
|
- 【敏感×37 异常】/.env /admin /wp-login.php 等共 37 个敏感路径(默认阈值 10 的 3.7 倍)→ 全 302 无 403。302 均为服务端 f.NotFound Redirect(location:/ + securityHeaders + CF NEL),确认到达应用层 → 疑似测试环境 enable_auto_ban=false(或阈值极高/实例未跑新二进制),需用户核对 app.ini + 日志后才能定论。若 enable=false,本测无法验证 TrackNotFound 语义,建议测试环境 enable_auto_ban=true 后重测。
|
||||||
|
- 【教训】agent-browser open 境外站再次卡死(>3.5min),TaskStop 清理;渲染验证降级 curl 抽查 HTML 即可。
|
||||||
|
|
||||||
|
## ban_track_notfound 测试环境复测通过(22:17-22:35,出口 222.218.124.37)
|
||||||
|
- 【上轮误判根因】串行 curl 每个请求间隔 1-2s(南宁→CF→源 RTT),13 个敏感请求跨 18s > 10s 窗口 → 永不达阈值;日志时间戳证实。非配置问题。
|
||||||
|
- 【复测方法】xargs -P 25 并发打,窗口内密集命中。
|
||||||
|
- 【结果】① 正常路径 / + admin3-9 全 200;② 纯 404 并发 x25 → 全 302 无 403(TrackNotFound=false 生效);③ 敏感路径并发 x25 → 前~10 个 302 后 15 个全 403(阈值10触发封禁);④ 封禁后 / 与 /_/admin6 也 403(IsBanned 全局生效)。
|
||||||
|
- 【副作用】本机出口 IP 222.218.124.37 被测试环境临时封禁 15min(约至 22:35 自动解除);测试环境日志可见该批 403 + 若有 security_alert_email 会收到告警(含样本路径)。
|
||||||
|
- 【结论】修复语义完整闭环:正常业务放行、纯404豁免、敏感扫描封禁。部署生产即可。
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
# 2026-09-06
|
||||||
|
|
||||||
|
## 移除 vercount 第三方页脚统计(用户确认"不用就去掉")
|
||||||
|
- 【诊断】cn.vercount.one 实际 = Vercel 托管 + CF 前置(104.21.1.96),cf-cache-status DYNAMIC 每次回源跨洋;南宁实测 js ttfb ~1.9s(DNS 0.72s 高);脚本内部 DOMContentLoaded 后才 fetch events.vercount.one(ttfb ~3s,才是页脚 spinner 真瓶颈);且慢 defer 会推迟 DOMContentLoaded ~1.4s。页脚仅展示 site_uv/page_pv 两徽标(busuanzi 兼容命名)。
|
||||||
|
- 【决策】第三方装饰统计非必须 → 用户选彻底移除(非动态注入方案)。备份 .workbuddy/backup/remove-vercount-20260906/。
|
||||||
|
- 【改动 7 文件】
|
||||||
|
1. templates/base/header.html:删 dns-prefetch cn.vercount.one;删 busuanzi 注释行与 <script defer vercount>;删专用 .tb-spinner CSS 块(含 dark 覆盖)
|
||||||
|
2. templates/base/footer.html:删整行 visitor/pageview 统计(busuanzi_value_site_uv/page_pv)
|
||||||
|
3-6. internal/i18n/dict_{zh_cn,zh_tw,en,ja}.go:删 site.footer.visitor/pageview 两个 key
|
||||||
|
7. internal/i18n/i18n_test.go:visitor 参数填充断言改指 auth.recover.greeting(保 %s 覆盖)
|
||||||
|
- 【验证】残留 grep 全空;gofmt clean;go test ./internal/i18n/ + ./templates/ 全绿。
|
||||||
|
- 【未动】static/tamabox.changelogs.json 为 2024 停更归档;根 CHANGELOG.md 是否追加条目待用户确认。
|
||||||
|
|
||||||
|
## umami 数据展示放弃 + tamami.js 加载优化(方案A load 注入)
|
||||||
|
- 【umami 取数可行性】mami.tama.guru = Vercel 托管 Next.js(CNAME vercel-dns-017.com);umami v2 API 全需登录(/api/websites 401、login 空体 zod 400);新版 umami 无 Share 功能 → 用户放弃 umami 数据恢复页脚统计,footer 维持无统计徽标(vercount 移除后现状)。
|
||||||
|
- 【mami 慢根因】Vercel 无国内节点,白天/冷访问 1-2s+;tamami.js 4.6KB 缓存头好(public max-age=86400, Age=303024 靠 CDN 兜底)凌晨命中 0.3s;用户体感慢主因=umami 后台(Next.js 动态回源)+ 白天边缘波动。defer 在 head 会推迟 DOMContentLoaded(同 vercount 问题)。
|
||||||
|
- 【R2 方案排除】实测 R2 直链 0.80-1.56s 比 Vercel 缓存命中 0.28-0.35s 更慢(凌晨南宁),印证 UIkit 当初迁 cdnjs.snrat.com 的原因。
|
||||||
|
- 【脚本能力确认】tamami.js 内部:host = data-host-url 优先否则脚本同源,拼 /api/send 上报 → 静态搬迁可行但无快托管点故弃。
|
||||||
|
- 【改动】templates/base/header.html(备份 .workbuddy/backup/tamami-load-inject-20260906/):638 行 <script defer tamami.js> → window load 后 createElement 注入 + setAttribute data-website-id。效果:mami 再慢不阻塞页面关键事件;PV 统计损失≈0(load 后立即上报当前页)。
|
||||||
|
- 【验证】go test ./templates/ 通过。
|
||||||
|
- 【未做】mami 接入 EdgeOne(方案C)未实施——用户暂选 A;上报 /api/send 跨洋延迟/丢失为 Vercel 托管固有限制。
|
||||||
|
|
||||||
|
## 全站外部资源加载体检(南宁凌晨实测 2 次取快值)
|
||||||
|
- 【健康】snrat 全家(uikit css/js/icons/dayjs/alpine/waline) 0.14-0.32s;www.recaptcha.net 0.17s;cf-turnstile 0.61s;bytecdntp 0.065s(注释未启用);cdn.github.red 0.15s;sentry-cdn 0.32s(仅 SentryDSN 非空才加载)。
|
||||||
|
- 【🔴唯一慢域=R2】time.box.js 0.7-1.7s(header 全站 defer 1.6KB,纯装饰 runtime 倒计时,硬编码 2023-06-01 起算,无外部依赖);neko-pixel umd 0.87s(pixel页);waline R2 源/home.html bytecdntp 均注释残留未启用(实际 waline 走 snrat)。图片类(头像/social icons)同 R2 慢但异步非阻塞,缓存头已 immutable。
|
||||||
|
- 【发现】header 的 vConsole 有 .VConsole 开关;sentry script 无 defer/async 且 tracesSampleRate=1.0——若生产 SentryDSN 启用则同步阻塞+高采样开销(需用户确认是否启用)。
|
||||||
|
- 【未决】time.box.js 优化方案待用户选(内联 footer / load 注入 / 不动);SentryDSN 生产是否配置待确认。
|
||||||
|
|
||||||
|
## time.box.js 内联到 footer(用户选"内联",备份 .workbuddy/backup/timebox-inline-20260906/)
|
||||||
|
- 【背景】加载体检确认 R2 是全站唯一慢域(0.71-1.68s),公共路径只剩 time.box.js(header 全站 defer 1.6KB 存活倒计时,无外部依赖)拖慢 DOMContentLoaded。
|
||||||
|
- 【改动】① header.html 删 <script defer r2 cdn/time.box.js>;② footer.html box_runtime 后内联紧凑版 IIFE:功能等价 + 修 2 个原版 bug(先赋值后判空会抛错;DOMContentLoaded 后首个 1s 才显示)。
|
||||||
|
- 【验证】time.box.js 引用清零(仅注释提及);go test ./templates/ 通过。
|
||||||
|
- 【待确认】SentryDSN 生产是否配置(若启用 sentry bundle 250KB 同步阻塞 + tracesSampleRate=1.0);R2 旧对象 time.box.js 可留作兼容不动。
|
||||||
|
|
||||||
|
## 测试环境部署验证通过(box-dev-api,01:19-01:21)
|
||||||
|
- 【tamami load 注入】主页+admin6:旧 defer src=mami.tama.guru 标签残留 0;addEventListener("load") 注入监听器 1;内联代码含 createElement+data-website-id 与源码一致。
|
||||||
|
- 【time.box.js 内联】主页+admin6:time.box.js 外链 0;id="box_runtime" 元素 1;footer 内联脚本(Date.UTC(2023 + setInterval(tick))就位。
|
||||||
|
- 【说明】未做浏览器 JS 行为验证(box-dev 境外站 agent-browser 有卡死史);SSR HTML 结构与源码逐字一致 + 标准 API 逻辑,判定部署生效。文案「存活」未出现因 curl 无语言 cookie 回退 en。
|
||||||
|
|
||||||
|
## EO(生产 box.tama.guru) vs CF(测试 box-dev) 速度实测对比(南宁,凌晨 01:36,http1.1)
|
||||||
|
- 【归属】prod: Server TencentEdgeOne IP 43.174.246/247.43(EO 新加坡);dev: Server cloudflare 104.21.47.52/172.67.144.141,但 CF-RAY 后缀 AMS(阿姆斯特丹)与实测 conn ~0.24s 矛盾(疑 Ray 字段不准/边缘非 AMS)。
|
||||||
|
- 【数据】①动态首页 8 轮 TTFB:prod 0.86-1.69s 均~1.22 vs dev 1.06-1.81s 均~1.49 → EO 快 ~0.27s;②连接阶段 8 轮:prod conn 0.20/TLS 中位 0.43(2次>0.9s 尖峰)vs dev conn 0.25/TLS 0.53(平稳无尖峰)→ EO 网络层快 50-100ms 但稳定性差;③favicon 静态 6 轮:prod 0.60-1.41 均0.84(有1.4s尖峰)vs dev 0.70-0.85 均0.75 → CF 反而更稳更快。
|
||||||
|
- 【结论】EO vs CF 对南宁同一量级互有胜负,无碾压差异;动态页 EO 略快,静态/稳定性 CF 优。差异更多源于回源链路+边缘抖动而非 CDN 标签本身。局限:凌晨单点、http1.1、生产/测试后端实例不同(变量未隔离);白天高峰需复测。
|
||||||
|
|
||||||
|
## EO vs CF 正式 A/B(01:40-01:47,南宁,http1.1,后端不同服务器-残余变量已注明)
|
||||||
|
- 【方法】robots.txt(静态文本近零后端耗时)30 轮交替 + 随机 query 强制回源 15 轮 + 此前 TCP/TLS/首页/favicon 数据汇总。
|
||||||
|
- 【robots 30轮】EO med 0.61s/mean 0.74/p90 1.16/>1s×7;CF med 1.16/mean 1.34/p90 2.23/全部>1s(min 1.03)。
|
||||||
|
- 【强制回源 15轮】EO med 0.83/mean 0.97;CF med 1.56/mean 1.68(CF min 1.39)→ EO 快 ~0.7s 近 2 倍。
|
||||||
|
- 【综合】TCP 0.20vs0.25、TLS 0.43vs0.53、首页 1.22vs1.49:大样本下 EO 全面领先;favicon 6轮小样本 CF 略快(缓存状态差异)不改变结论。
|
||||||
|
- 【坑】本机 Windows curl(Schannel) 不支持 --http2,勿用于 A/B;上轮 --http2 全失败 999。Bash 同名 /tmp 文件曾出现残留污染→用 $$ 文件名。
|
||||||
|
- 【说明】CF 回源走 tunnel(cloudflared)、EO 回源直连;源站不同为残余变量,strict A/B 需同源(把 dev 挂 EO 或 prod 挂 CF)。
|
||||||
|
|
||||||
|
## autoban 敏感特征补强:sensitiveFragments 片段匹配(用户选"补强 WP 特征表",备份 .workbuddy/backup/wp-fragments-20260906/)
|
||||||
|
- 【背景】生产日志见 wlwmanifest 扫描://wp/wp-includes/wlwmanifest.xml、//news/...、//2018/...(枚举前缀变体)全部 302 放行。根因:① 所有未注册路径走 f.NotFound→ctx.Redirect("/") 得 302(非 404,注释"先写404"与实际不符,flamego Redirect 覆盖状态);② TrackNotFound=false 后 404 不计数;③ IsSensitivePath 前缀匹配抓不到中部敏感段 + 特征表无 wp-includes/xmlrpc/wlwmanifest。
|
||||||
|
- 【改动 autoban.go】新增 sensitiveFragments 数组(子串匹配强指纹,仅 WP 特征业务必无):/wp-includes/、/wp-json/、/wp-cron.php、/wp-trackback.php、/wp-admin、/wp-content、/wp-login.php、/wlwmanifest.xml、/xmlrpc.php、/wordpress;IsSensitivePath 增加 Contains 第二循环(大小写不敏感)。前缀表 sensitivePaths 保留不动(防 /administratorx 类误伤语义不变)。
|
||||||
|
- 【测试】TestIsSensitivePath 补 9 正例(含日志真实形态 //wp/wp-includes/wlwmanifest.xml 等)+ 6 负例(/_/tamakyi、/_/admin6、/api/v1/question/xxx、/explore、/i18n 不误伤)。
|
||||||
|
- 【验证】gofmt clean;autoban 全测 PASS;route 带 overlay 编译+测试通过(IsSensitivePath 由 internal/route/autoban.go:35 中间件调用,改匹配器全链生效)。
|
||||||
|
|
||||||
|
## 域名迁移方案:box.tama.guru → box.shiroko.one(方案阶段,未动代码)
|
||||||
|
- 【用户决策】tama.guru 不续费(2026-12-24 到期,RDAP 实证,注册商 DNSPod)→ 硬过渡;新域 box.shiroko.one;Bing+GSC 全套;umami 随迁 mami.shiroko.one。方案文档 outputs/domain-migration-box-shiroko-2026-09-06.md。
|
||||||
|
- 【取证要点】shiroko.one 未配置(NS=spaceship,http 200 为注册商 Parking Page);tama.guru apex=导航页 Hugo/CF Pages,box 走 DNSPod 三线路(境内 EO/境外+默认 CF SaaS);mami=Vercel。
|
||||||
|
- 【SEO 现状】box sitemap 仅 8 条(/ /explore /register /login /_/tamakyi /change-logs),explore 是唯一内容页;robots Disallow /_/ 与 sitemap 提交 /_/tamakyi 矛盾;页面无 canonical;og:url/邮件链接均依赖必填配置 external_url;static/robots.txt+sitemap.xml go:embed 硬编码旧域;register.go:64 Bloglink 硬编码;censor TrustedHosts 含 tama.guru/337845818.best;R2 CORS 白名单需加新域。
|
||||||
|
- 【核心机制】301 逐 URL 是唯一可靠保排名路径;Bing Site Move 工具可用性不稳定(2021 传闻下线)仅加速器;Site Move 后新域 6 个月禁再迁;通行 301 保持 6-12 月 vs 本方案仅 3.5 月窗口=R1 主风险,靠索引面小+早切换(≤10/01)+IndexNow 缓解。
|
||||||
|
- 【301 载体推荐】旧域 DNS 切换日统一 CNAME → CF Pages 跳转项目(_redirects: /* https://box.shiroko.one/:splat 301!),与源站/旧 CDN 解耦;弃"源站 nginx 按 Host 301"(回源 Host=旧域会成环)。
|
||||||
|
- 【开放项待用户】站群 blog/status/share/chat 是否迁(影响 footer/home 内链);/_/tamakyi 是否保(决定 robots/sitemap 取舍);cloudflared ingress 是否按 hostname。
|
||||||
|
|
||||||
|
## 域名迁移批1落地:全项目 tama.guru → shiroko.one(本地代码,备份 .workbuddy/backup/domain-shiroko-20260906/)
|
||||||
|
- 【用户决策】其他 blog 之类子域一并调整到 shiroko.one;/_/tamakyi 不保(sitemap 移除,robots 维持 Disallow /_/);先做本地操作。
|
||||||
|
- 【替换规则】*.tama.guru → *.shiroko.one(box/blog/chat/share/status/mami),apex tama.guru → shiroko.one。
|
||||||
|
- 【改 11 文件】static/robots.txt(Sitemap行);static/sitemap.xml(5条换域+删/_/tamakyi+去重旧域无斜杠重复项+lastmod全刷2026-09-06);static/llms.txt(6处);static/llms-full.txt(7处);templates/base/footer.html(6条链接);templates/base/header.html(umami注释同步+验证token加迁移提醒注释);templates/home.html(站长箱/投票/Markdown/4条blog链/explore);route/auth/register.go:64 Bloglink默认值;internal/security/censor/text.go(TrustedHosts 新增 shiroko.one,**保留** tama.guru 过渡期);conf/app.sample.ini(补齐缺失的必填项 external_url,conf.go:36 强制校验,原模板缺失→照抄即启动失败);dev/eo-*.py(3脚本 --host 默认值)。
|
||||||
|
- 【关键发现】① header 的 mami src 此前已先行改为 mami.shiroko.one(仅注释待同步);② google-site-verification(636行) 与 msvalidate.01(7行+637行重复) 是域名绑定 token,新域验证后必须替换 content,否则 GSC/Bing 无法验证新站→Site Move/Change of Address 无法提交;③ app.sample.ini 缺 external_url 必填键(模板缺陷)。
|
||||||
|
- 【验证】sitemap XML 解析通过(5条无重复);go test ./templates/ + ./internal/security/censor/ 通过;route/auth、static、internal/conf 带 overlay 编译通过。
|
||||||
|
- 【方案文档同步】outputs/domain-migration-box-shiroko-2026-09-06.md:§0 补两条决策;§11 开放项标 1/2 已答并新增 token 项;新增 §12 批1实施记录;附批次标批1完成。
|
||||||
|
- 【待用户操作】blog/chat/share/status 各子域实际服务搬迁(否则新域链接成死链);censor 旧域条目待旧域到期后删。
|
||||||
|
|
||||||
|
## IndexNow key 文件 302 修复(static/index-now/<key>.txt 无法访问)
|
||||||
|
- 【现象】用户新建 static/index-now/66e5e0911b0941f2ba7dbfbbd961e9be.txt 并改 fs.go 的 //go:embed,但访问 302 跳首页。
|
||||||
|
- 【根因】internal/route/route.go:138 的 flamego.Static 中间件 **Prefix="/static"** 只接管 /static/... 前缀;而 robots.txt/sitemap.xml/llms*.txt/favicon.ico 等根目录静态文件**每个都是单独注册的 f.Get handler**。新文件无对应路由 → 落 f.NotFound → ctx.Redirect("/") 得 302。embed 本身没问题(实测 FS.Open 可读,内容正确)。
|
||||||
|
- 【修复】route.go:① import 加 regexp;② 包级 var indexNowKeyPattern = `^[0-9a-f]{32}\.txt$`(防路径穿越);③ 在 llms-full.txt 路由后加 f.Get("/index-now/{key}"),校验白名单后 static.FS.Open("index-now/"+key),Content-Type text/plain + max-age=86400,失败 404。备份 .workbuddy/backup/domain-shiroko-20260906/route.go.bak。
|
||||||
|
- 【新增回归测试】internal/route/indexnow_route_test.go TestIndexNowKeyFileRoute:正确key→200+内容;路径穿越(..%2f 与 ../../)、合法格式但不存在、后缀不符→全 404。用 flamego.NewWithLogger(io.Discard) 构造最小实例(不依赖 New())。
|
||||||
|
- 【flamego 关键行为】internal/route/tree.go placeholderTree.match 把整个路径段赋给参数,**不排除点号** → /index-now/{key} 能匹配 <key>.txt。
|
||||||
|
- 【验证】gofmt clean;带 overlay 编译 ./internal/route/ 通过;route/static/templates 三包测试 ok。
|
||||||
|
- 【部署提醒】需重新编译部署(embed+路由均在二进制内);IndexNow 提交时 keyLocation 填完整 URL https://box.shiroko.one/index-now/66e5e0911b0941f2ba7dbfbbd961e9be.txt;旧域 301 后该路径会被重定向,搜索引擎校验需 200 直出,故切换后应用新域 keyLocation 重新提交。
|
||||||
|
|
||||||
|
## 域名变更全员邮件通知脚本(dev/notify_domain_change.py,不碰项目源码)
|
||||||
|
- 【需求】用户改了站点域名,想向全体未注销用户发邮件通知;要求复用生产 conf/app.ini 的 DB+SMTP,不动项目源码。
|
||||||
|
- 【依据】① users 表软删除用 gorm.Model,未注销=deleted_at IS NULL;收件=email 列;可顺带取 name/domain 做个性化。② 发信对齐 internal/mail/mail.go:发件人"TamaBox <mail.account>",465=隐式SSL 否则 STARTTLS,支持 mail.skip_tls_verify。③ DSN 拼装见 internal/conf/db.go(postgres sslmode=disable+search_path=schema)。
|
||||||
|
- 【实现】独立 Python 脚本:读 NEKOBOX_CONFIG_PATH 或 -c,configparser 设 strict=False(容忍示例 [upload] 重复键 image_endpoint)、去引号、去行内注释;fetch_recipients 查未注销有邮箱用户;smtp_login 复用生产配置;模板用 {{占位符}} 避免与 HTML 大括号冲突。
|
||||||
|
- 【安全开关】默认 --dry-run;--send 才真发;--to 单测地址;--limit N 小批量;单条失败隔离+汇总;每封 --delay 默认 0.3s 防限流。
|
||||||
|
- 【验证】py_compile OK;对 app.sample.ini 实测 load_config 解析正确(external_url 去引号、重复键容忍);render 模板无残留占位符。依赖 psycopg2-binary(Postgres)/pymysql(MySQL)。
|
||||||
|
- 【增强·四语言】TamaBox 为四语言站点,给脚本加 LANG_TEMPLATES(zh-CN/zh-TW/en/ja),fetch_recipients 多取 language 列;发送时按 users.language 选模板,回退 用户语言→[app] default_lang→zh-CN;--subject/--html/--plain 为全局覆盖。effective_templates() 选模板,build_message() 内统一 render 后才拼装(曾一度漏 render 已在自检发现并修正)。去掉默认模板 emoji。复测:四语言 text/plain+text/html 双部、box_link/site 就位、无残留占位符(正文 base64 传输编码属正常,解码核验通过)。
|
||||||
|
|
||||||
|
## 用户问"前端还有什么要改造的" + "box.tama.guru 接 CF 自定义主机名如何配 301"
|
||||||
|
- 【诊断残留】grep 全项目:tama.guru 残留仅在 sitemap.xml 注释、header.html 验证 token 提醒注释、censor/text.go(过渡期有意保留)、outputs/(文档)——即迁移批1已完成,无业务代码残留旧域。
|
||||||
|
- 【R2 硬编码仍散落】`r2.337845818.best` 约 14 处:header.html(preconnect/waline css/favicon/OG)、pixel.html(neko-pixel css+js)、question-not-found.html & list.html(social icons + easy.qrcode.min.js)、user/profile.html(qrcode js + pickr css/js)、route/question/share.go(social icons);waline serverURL `waline.337845818.best` 在 home.html/item.html。建议抽 `CdnBase`/`WalineURL` 模板变量集中管理(为同源化/换域铺路)。
|
||||||
|
- 【301 指引(CF 自定义主机名架构)】规则建在承载该自定义主机名的 zone 上;迁移未完成前**不要**整站 301 到 shiroko.one(会断线上)。①现在做:SSL/TLS→Always Use HTTPS(http→https 自动301)+ www 规范化 Redirect Rule;②切换时做:Bulk Redirects(box.tama.guru→https://box.shiroko.one, 301, include subpaths+query)或 Single Redirect Dynamic `concat("https://box.shiroko.one", http.request.uri.path, http.request.uri.query!=""?concat("?",http.request.uri.query):"")`;③SEO 配套:sitemap 已换域重提交 GSC/Bing、旧域 DNS 保 6-12 月、header 638-639 行验证 token + 第7行 msvalidate.01 新域重新验证替换、canonical/OG 指向新域。
|
||||||
|
- 【架构提醒】A/B 实测 EO 国内比 CF 快约 2 倍(EO 0.61 vs CF 1.16,CF 走 tunnel 回源);box.tama.guru 接 CF 后国内(南宁电信)失 EO 提速优势,规划 box.shiroko.one CDN 时建议继续用 EO 或 CF China 保国内速。
|
||||||
|
|
||||||
|
## 通知脚本三要求落地(dev/notify_domain_change.py,不碰项目源码)
|
||||||
|
- 【需求】①发送前打印 DB 总用户/已注销/未注销/未注销有邮箱数,须人工 yes 确认才发;②不一口气发完留间隔;③正文明确换域原因+用户动作:新域 box.shiroko.one、旧域 2026-12-24 到期、期间 301 转发、到期后旧域停用;Why=.guru 连年涨价一年三百出头遭不住;Do=记新域+替换此前分享的二维码。
|
||||||
|
- 【改动】抽 connect_db() 供 fetch_recipients/fetch_counts 复用;新增 fetch_counts() 打统计;main 发送前打印五类统计;--send 路径加 input("yes") 人工确认(EOFError→中止,--yes 跳过);--delay 默认 1.0s,新增 --pause-every/--pause-for 分批长暂停;四语言模板全重写,加 {{old_domain}}/{{expire_date}} 占位符与「为什么/该做什么」问答段;--old-domain 默认 box.tama.guru、--expire-date 默认 2026-12-24(均可覆盖)。
|
||||||
|
- 【验证】py_compile OK;四语言 build_message 解码核验:新域名/旧域名/2026-12-24/301 均就位、无残留 {{占位符}}、text/plain+text/html 双部。
|
||||||
|
|
||||||
|
## 通知脚本二次微调(硬编码域名 + 价格模糊 + 无语言默认简中)
|
||||||
|
- 【改动】① 新旧域名+到期日改为模块级硬编码常量 NEW_DOMAIN=box.shiroko.one / OLD_DOMAIN=box.tama.guru / EXPIRE_DATE=2026-12-24,删除 --old-domain/--expire-date 参数;site 与 box_link 改用硬编码新域(不再依赖 app.external_url,故移除其空值中止判断)。② 四语言「为什么换」文案去掉具体金额与「遭不住」,改为「.guru 连续涨价/续费成本越来越高」把原因写清。③ 语言回退:空语言直接→zh-CN(不再先落 default_lang);未知语言→default_lang→zh-CN。
|
||||||
|
- 【验证】py_compile OK;源码 grep 无「三百/over 300/年間300/遭不住」;四语言渲染含 box.shiroko.one/box.tama.guru/2026-12-24/301、无占位符;回退逻辑 空/未知→zh-CN、en→en。
|
||||||
|
|
||||||
|
## 通知脚本加「断点续发」+「按语言分群」
|
||||||
|
- 【改动】① 断点续发:新增 load_sent_state/record_sent/reset_state(JSONL 逐行追加,崩溃安全);默认状态文件 DEFAULT_STATE=脚本同目录 notify_state.json(--state 可改);发送前 load 已发邮箱集合并过滤,打印「已跳过 N 封 / 剩余待发送 N 封」;每成功一封 record 一行;--reset-state(仅 --send 时)清空后全量重发;测试 --to 模式不写状态避免污染。② 按语言分群:resolve_lang() 统一语言解析(空→zh-CN、未知→default_lang→zh-CN);发送前打印「按语言分布」统计;main 发送循环改为按 LANG_ORDER=[zh-CN,zh-TW,en,ja]+其他 分组,每组打印「[语言分组 gi/gn] 语言(标签) : 本组 N 封」,组间 --group-pause 默认 3.0s(0 关);组内仍走 --delay/--pause-every。
|
||||||
|
- 【验证】py_compile OK;monkeypatch DB+SMTP 实测:RUN1(--limit 3)→发3、state 3 行且分组正确;RUN2(同 state 续发)→跳过3、发剩余3(zh-CN 组2+ja 组1)、state 6 行;RUN3(再续发)→跳过6、发0;RUN4(--reset-state)→清空并全量重发2。空语言/未知语言均归 zh-CN。
|
||||||
|
- 【增强】捕获 send_message 返回字典(RCPT TO 阶段被拒收的 {addr:(code,err)}),非空时计为「[SMTP 拒收]」失败(不计入 sent、不写断点状态、可续发重试),避免误把"已被拒收"算成成功。验证:2 收件人第 2 封返回 550 拒收→成功1/失败1、state 仅1行。
|
||||||
|
- 【用户现象】实测运行时显示"成功 N 封"但收不到信;定位:SMTP 250 OK 仅代表 RCPT TO 接收,不等于投递成功;截图收件人全是 *@admin.com(含 admin3x/admin4 等大概率不存在账号),最可能是收件不存在→退信回到 From(mail_account) 而未被监控,或发件域 SPF/DKIM 未对齐被静默丢信。建议用 `--to 真实外部邮箱 --send` 隔离验证。
|
||||||
|
- 【增强】notify_domain_change.py 加「监控报告」+「测试模式命中数据库」:① 每次运行结束写 notify_report.json(JSON,含 db_stats/lang_distribution/sent/failed/smtp_rejected/skipped_already_sent/failed_list/config(无密码)/test_mode),`--report PATH` 改路径、`--no-report` 关闭,dry-run 与 send 都会写;② `--to 邮箱` 先查库,命中则套用该用户姓名/域名/语言,未命中按 zh-CN。验证:en 命中→英文主题、未命中→中文主题、报告字段与 SMTP 拒收单独计数均正确。
|
||||||
|
|
||||||
|
## 通知脚本模板修正(box_link 路径 + 头部致谢/群发 + 底部版权)
|
||||||
|
- 【用户反馈】实测邮件内容两点问题:① 提问箱个性域名实际为 `box.shiroko.one/_/xxx`(项目 templates/profile.html 与 base/footer.html 均为 `/_/{domain}` 路径),脚本写成 `box.shiroko.one/xxx` 不对;② 邮件头部应先感谢用户使用提问箱并说明是群发站内信;③ 底部加 `© 2026 狼的提问箱`。
|
||||||
|
- 【改动】发送循环 box_link 由 `https://{NEW_DOMAIN}/{domain}` 改为 `https://{NEW_DOMAIN}/_/{domain}`;四语言 HTML+纯文本模板(zh-CN/zh-TW/en/ja)头部问候后新增「首先感谢使用(狼的提问箱)」+「这是群发的站内通知邮件,请放心查阅」两段;底部系统通知行追加 `© 2026 狼的提问箱`(英 Wolf's Question Box / 日 狼の質問箱 / 繁 狼的提問箱)。
|
||||||
|
- 【验证】py_compile OK;四语言解码核验:box_link 含 `/_/`、致谢+群发+版权关键词均就位、无残留 {{占位符}}。
|
||||||
|
|
||||||
|
## 通知脚本去外部依赖(零 pip 安装)
|
||||||
|
- 【用户痛点】当前脚本依赖 psycopg2-binary(Postgres)/ pymysql(MySQL),但环境 pip install 基本不可用,装不了第三方包。
|
||||||
|
- 【改动】DB 层改为「零依赖优先」:默认 auto 驱动优先调用系统自带命令行客户端 psql(Postgres)/mysql(MySQL),纯标准库 subprocess,无需 pip;仅当客户端都不存在时才回退 psycopg2/pymysql(可选 pip 安装)。新增 _build_pg_uri(密码 URL 编码)、_choose_driver、_psql_query(-X -t -A -F '\x1f' -P null=\N -P footer=off)、_mysql_query(临时 cnf 传密码避免进程参数泄露)、_lib_query、run_query 统一入口;fetch_recipients/fetch_counts 改为接收 args 并调 run_query;新增 --db-driver {auto,psql,mysql,psycopg2,pymysql};load_config 增加 db_sslmode(默认 disable,与旧 psycopg2 行为一致);PG 统计用 COUNT FILTER(WHERE...) ,MySQL 用 SUM(CASE...);main 打印 [DB 驱动]。
|
||||||
|
- 【验证】py_compile OK;monkeypatch 实测:驱动选择(pg有psql→psql / mysql有mysql→mysql / 无客户端但可import psycopg2→lib / 全无→psql报错路径);psql 路径解析(含空语言/空名/语言NULL→空);mysql 路径解析;E2E 经 psql 路径 dry-run 写报告、send 6 封(按 zh-CN3/zh-TW1/en1/ja1 分组、空语言+未知fr回退zh-CN)、RESUME 跳过6发0、--to 命中库用户发往其邮箱。
|
||||||
|
- 【结论】现在只需 Python 标准库 + 服务器上的 psql/mysql 客户端即可运行,彻底不依赖 pip。
|
||||||
|
|
||||||
|
## 通知脚本 bug 修复:language 列不存在导致 FATAL
|
||||||
|
- 【现象】用户用 `python3 notify_domain_change.py -c ./auto/conf/app.ini --to [email protected] --send` 报 `ERROR: column "language" does not exist`。
|
||||||
|
- 【根因】GORM 模型 `User.Language` 默认 column=language,但线上 `nekobox` 库 schema 较旧,users 表无 language 列(可能叫 lang 或根本没有该列)。脚本此前在 fetch_recipients 里硬编码 `SELECT ..., language FROM users`。
|
||||||
|
- 【修复】新增 resolve_lang_column(cfg, args):默认 auto 探测 information_schema.columns 的 candidates(language/lang),找到即用、都不存在返回 None(调用处用 `NULL AS language` 兜底,全员回退默认语言);新增 `--lang-column` 参数可手动指定(如 --lang-column=lang)。fetch_recipients 改用探测到的列名拼 SQL;main 打印 `[语言列]` 行。mock 验证 4 场景(lang 命中/lang 缺失→NULL/显式指定/language 命中)均正确。
|
||||||
|
- 【给用户建议】直接重跑即可;若库里列叫 lang 会自动识别,若真无该列则全员按 [app] default_lang(ja) 模板发送,不影响发信。
|
||||||
|
|
||||||
|
## 通知脚本「依旧报错」二次排查:版本标记 + 改名验证法
|
||||||
|
- 【现象】首轮修完用户报「依旧不行,报错一致」。初判为用户在 Linux 服务器跑的是仓库根 `/home/tamakyi/Github/Tamabox_v4/notify_domain_change.py`(state_file 路径证伪),而工作区仅 `dev/notify_domain_change.py` 一份;用户坚称没用错文件。
|
||||||
|
- 【加版本标记】SCRIPT_VERSION = "2026-09-06.langdetect.v2",main 配置头打印 `[版本] SCRIPT_VERSION = ...`。作用:运行输出若无此行即证明跑的不是最新副本,把"是否用错文件"变成客观判定(不再靠争论)。
|
||||||
|
- 【改名验证】建议用户在服务器 `mv notify_domain_change.py notify_mail_v2.py` + `find . -name __pycache__ -exec rm -rf` 后跑新名,强制重编译以排除陈旧 .pyc / 同名模块作祟(用户自己提出的怀疑点)。
|
||||||
|
- 【结论】修复后版本不可能再出现 `column "language" does not exist`(查询已无 language 字面量);若改名+清缓存后仍报该错且带 [版本] 行,则需查 information_schema 探测是否异常。
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
# 2026-09-07
|
||||||
|
|
||||||
|
## notify_domain_change.py 语言列探测 v3(langprobe)
|
||||||
|
- 上轮 information_schema 探测在线上误报(探测说 language 存在、真实查询报列不存在,疑似跨 schema 同名表干扰)。
|
||||||
|
- 本轮重写为「真实试跑探测」`detect_lang_column()`:依次执行 `SELECT ... language / lang / NULL`(LIMIT 1),哪个能跑通用哪个;NULL 兜底必然成功,不会再因列缺失 FATAL。
|
||||||
|
- `fetch_recipients(cfg, args, lang_expr=...)` 与 `main` 调用链对齐;版本号提升为 `2026-09-06.langprobe.v3`。
|
||||||
|
- 6 场景 mock 验证全过:language 报错→降级 lang;全缺失→NULL 回退 default_lang(ja);显式 --lang-column;自动探测拼 SQL 正确。
|
||||||
|
- 测试脚本两处自身 bug(dict 键名 language 非 lang;mock 对 NULL 查询仍返回 'en')已修正后 ALL_PASS。
|
||||||
|
|
||||||
|
## v4(rfc5322.schema):QQ 邮箱 550 退信 + 统计全 0 两个问题
|
||||||
|
- 550 退信根因:`From: 狼的提问箱 <tamabox@...>` 中文显示名未做 RFC2047 编码,QQ(mx3.qq.com)回 550 "From header is missing or invalid"。修复:`formataddr((str(Header(显示名, utf-8)), 地址))` 编码 From,Subject 同样用 Header 编码,并补 Message-ID。
|
||||||
|
- 统计全 0 根因:psql 未限定 schema,search_path 命中了别的 schema 里的同名空 users 表(也解释了 v2 information_schema 探测误报 language 存在)。修复:新增 `resolve_users_table()` 枚举所有 schema 的 users 表并逐个 COUNT,选有数据(其次带 language 列)的 schema,全部查询用 `"schema".users` 限定;main 打印 `[DB 连接]` 与 `[users 表]` 诊断行,全空时警告。
|
||||||
|
- 5 场景 mock 验证 ALL_PASS(schema 定位/语言探测/counts/全空回退/From+Subject 编码与 Message-ID)。版本 `2026-09-07.rfc5322.schema.v4`。
|
||||||
|
|
||||||
|
## 新项目 mail-broadcast/(站内信群发工具)
|
||||||
|
- 用户确认 v4 后收件正常、数据正确,但邮件里提问箱链接显示成站点首页而非 `/_/个性域名`;要求新建独立可复用项目、四语言模板拆成独立 HTML。
|
||||||
|
- 新建 `mail-broadcast/`:`broadcast.py`(通用化:去掉硬编码域名,`--site-url`/`--box-prefix`/`--var k=v` 自定义占位符;缺失占位符置空并上报)+ `templates/{zh-CN,zh-TW,en,ja}.{html,subject.txt}`(plain 可选,缺省由 HTML 自动抽取纯文本,HTMLParser 实现)+ README.md。
|
||||||
|
- 保留 v4 全部 DB/SMTP 能力:schema 定位、语言列试跑探测、断点续发、分群限速、SMTP 拒收捕获、RFC2047 From/Subject、Message-ID。语言回退保持「空→zh-CN、未知→default_lang→zh-CN」。
|
||||||
|
- 预览区直接打印每个收件人解析后的 box_link,方便发现链接问题。
|
||||||
|
- 7 场景 mock 测试 ALL_PASS(含四语言渲染 box_link、缺失占位符上报、From 编码)。
|
||||||
|
|
||||||
|
## params.ini 参数文件 + --interactive 交互模式
|
||||||
|
- 用户新需求:运行时直接读参数文件,或运行后再交互。
|
||||||
|
- 新增 `params.ini`([site] site_url/box_prefix + [vars] 自定义占位符 + [send] to/delay/group_pause),默认自动读取脚本同目录 params.ini,`--params`/`--no-params` 可控;优先级 CLI > 文件 > 默认。
|
||||||
|
- 安全边界:参数文件不提供 --send/--yes,正式发送必须命令行显式指定 + 终端确认。
|
||||||
|
- `--interactive/-i`:逐项确认 site_url/box_prefix,自动扫描模板占位符(collect_template_placeholders 排除内置)逐个提问(模板加新占位符会被自动发现),可选测试邮箱,可选保存回 params.ini(save_params)。
|
||||||
|
- 踩坑:测试脚本两次自身 bug(回答顺序没按字母序、Args 类属性 vs 实例属性);跑挂的测试曾把 params.ini 写坏,已恢复标准值。7 场景 ALL_PASS。
|
||||||
|
|
||||||
|
## conf 路径纳入 params.ini 与交互模式
|
||||||
|
- params.ini 新增 `[path] config`(预填 ./auto/conf/app.ini);`-c` 默认值改为 None,解析优先级:CLI > params.ini > 环境变量 TAMABOX_CONFIG_PATH > ./conf/app.ini。
|
||||||
|
- `--interactive` 第一步先问配置文件路径(在 load_config 之前),保存回 params.ini 时含 config 路径(save_params 签名加 config 参数)。
|
||||||
|
- 5 场景测试 ALL_PASS(params 读取/优先级/save round-trip 含 config/交互完整流程/标准值恢复)。
|
||||||
|
|
||||||
|
## 交互选运行方式 + 模板对齐原程序邮件样式
|
||||||
|
- 用户新需求:① send 之类的决策放进交互里而不是命令行;② 模板配色样式参照原程序 templates/mail/。
|
||||||
|
- run_interactive 重构:占位符问完后进入「运行方式」选择(1 演练/2 测试/3 群发,默认回车=演练);模式 2 问测试邮箱、模式 3 可问 limit(试水)并可选择是否保留最终确认(答 n → args.yes=True)。args.send/to/yes/limit 就地写入,交互全程无需 --send/--to/--yes。
|
||||||
|
- 四语言模板重写为原程序 Google 风格:白底 #FFFFFF、#dadce0 细边框 8px 圆角卡片(max-width 516px)、标题 24px 带下边框、正文 Roboto 14px rgba(0,0,0,0.87)、次要信息 rgba(0,0,0,0.54)、新域名高亮框 #e8f0fe/#c6dafc、按钮 #4184F3 蓝底白字、页脚 11px rgba(0,0,0,0.54)。新增 `{{year}}` 内置占位符(ctx 用 datetime.now),run_interactive 的 builtin 集合同步排除。
|
||||||
|
- 测试踩坑:render() 返回 (结果, missing) 元组需解包;群发路径交互共 8 次输入。24 项检查 ALL_PASS(四语言 box_link/按钮链接/配色/#year/占位符完整 + 4 交互场景 + From 头 ASCII)。
|
||||||
|
|
||||||
|
## 默认交互模式 + 单文件通用模板(--single)
|
||||||
|
- 用户新需求:① 默认就是交互模式不用手输;② 新增单文件模式(不按语言,所有人发同一个通用模板,模板单独存放便于以后复用)。
|
||||||
|
- 默认交互:`--interactive` 改 default=None,parse 后判定——未给 --send/--to/--yes/--dry-run 之一即自动进入交互;`--no-interactive` 强制关闭(脚本化用)。
|
||||||
|
- 单文件模式:templates/single.html + single.subject.txt(保留名,load_templates 排除不混入语言列表;load_single_template 单独加载,plain 自动抽取)。`--single` CLI 或交互「模板模式」选 2。发送时 grouping 固化为 single 组(不 resolve_lang),ctx 仍含每人 box_link/name/site/year;报告加 template_mode。
|
||||||
|
- single.html 样式对齐原程序邮件,正文内容区用 HTML 注释标注「编辑这里」,含可复制的强调框示例。
|
||||||
|
- 15 项检查 ALL_PASS(single 不混语言/加载/渲染/构建 + 4 交互组合场景)。
|
||||||
|
|
||||||
|
## 交互只问缺失项(不再每次重复确认战役参数)
|
||||||
|
- 用户反馈:site_url/box_prefix/old_domain/expire_date 这类一次性参数每次交互都问很烦,直接写死到这次 html 即可。
|
||||||
|
- run_interactive 重构:开头打印「[参数确认]」摘要(沿用 params.ini/CLI/app.ini 的值),**有值一律不问**;只补问 ① 完全没值的 site_url(main 里先做 external_url 兜底)② 模板用到但 extra_vars 里还没有值的自定义占位符。box_prefix 不再询问(默认 /_/,CLI 可覆盖)。
|
||||||
|
- 配置文件路径同理:CLI/params.ini 明确给了就打印沿用不问,仅默认猜测时才 ask。
|
||||||
|
- 想改值:编辑 params.ini,或把一次性内容写死进模板 html 并删掉对应 {{占位符}}(占位符删了就不会被问)。
|
||||||
|
- 测试踩坑:mock 回答数按实际提问数对齐(占位符 2 个非 3 个;摘要走 print 非 input 需 redirect_stdout 捕获)。7 项检查 ALL_PASS。
|
||||||
|
|
||||||
|
## 文案修正:模板问句人称
|
||||||
|
- 用户指出邮件模板「我该做什么?」应为「你该做什么?」(站方对收件人的口吻)。
|
||||||
|
- 已修 templates/zh-CN.html 与 zh-TW.html 对应问句;渲染验证通过、无残留。en(What should I do?)/ ja(何をすればよいですか?)保持读者视角的惯用表达未改。
|
||||||
|
|
||||||
|
## --limit 与断点续发顺序 bug 修复
|
||||||
|
- 用户反馈:第一次发送部分成功,第二次 --limit 10 时「已跳过 10、剩余 0、一条没发」。
|
||||||
|
- 根因:main 中 --limit 截取在断点续发过滤之前执行,limit 永远取名单头部那批已发用户,跳过后剩 0。
|
||||||
|
- 修复:调整顺序为「先剔除已发 → 再取前 N」,--limit 提示语带上已剔除数量;补 had_state 标志控制「剩余待发送」打印。
|
||||||
|
- 6 项回归测试 ALL_PASS(跳过+limit 组合、无重叠、limit>剩余、全已发、状态读写往返)。
|
||||||
|
|
||||||
|
## 退信核查功能(bouncecheck.v2)
|
||||||
|
- 背景:SMTP 250≠送达,阿里云对限流/无效地址先收下再异步退信到发件箱,用户要求发送后核查真实送达。
|
||||||
|
- 新增零依赖 IMAP 退信扫描:--check-bounces 登录发件箱(imaplib 993,IMAP 域名由 smtp.→imap. 推导),两段式拉取(先头部命中退信特征再取全文),--since-days 默认 3。
|
||||||
|
- 退信解析三层:标准 DSN(message/delivery-status, Action:failed)→ 中文「收信地址/收件人」标签 → 正文地址兜底(剔除发件人与 daemon/postmaster);主题关键词 + multipart/report 双判定。
|
||||||
|
- --prune-state 把退信用户从 broadcast_state.json 剔除 → 重跑自动补发;已核查 Message-ID 存 broadcast_bounces_seen.json 防重复报告。交互运行方式新增「4) 退信核查」(并移到模板模式之前,该模式跳过模板提问)。
|
||||||
|
- 12 项单元测试 ALL_PASS(含用户真实退信格式、标准 DSN、限流退信全角冒号、prune 往返)。防御修正:正则加 (?<![A-Za-z0-9]) 防乱码前缀吞地址;测试须用 message_from_bytes 贴近 IMAP 真实路径(message_from_string 双编码会污染解析)。
|
||||||
|
|
||||||
|
## 退信核查拆分三档(仅核查/仅剔除/剔除并补发)
|
||||||
|
- 用户要求「仅剔除、不一定剔除后直接发送」。交互运行方式 4 下新增子选项:1 仅核查(默认,不改清单)/ 2 仅剔除(更新清单后结束,本次不发送)/ 3 剔除并补发(剔除后继续正常发送流程,发送前仍有统计确认)。
|
||||||
|
- CLI 对应:--check-bounces 仅核查;--check-bounces --prune-state 仅剔除;--prune-state --send 剔除并补发(main 分支在 args.send 时不 sys.exit,落回正常发送流程)。
|
||||||
|
- 4 项交互 mock 测试 ALL_PASS;README 同步。
|
||||||
|
|
||||||
|
## 退信扫描起点改为群发首条记录
|
||||||
|
- 用户反馈:固定近 3 天会把群发无关的退信/邮件扫进来。
|
||||||
|
- 新增 resolve_scan_start():auto(默认)取 broadcast_state.json 最早一条 ts - 1 天余量;--since YYYY-MM-DD 显式指定;无记录/无 ts 回退 --since-days(默认3)。IMAP search 用 SINCE 日期,控制台打印 [扫描起点] 说明。
|
||||||
|
- 6 项测试 ALL_PASS(最早记录-1天/显式日期/非法日期回退/无清单回退/无 ts 回退)。
|
||||||
|
|
||||||
|
## 移除扫描起点 -1 天余量
|
||||||
|
- 用户反馈:提前 1 天余量导致扫描范围仍偏大。改为 auto 模式精确从群发首条记录的 ts 开始(不再 -1 天);--since 显式日期与空清单回退 --since-days 逻辑不变。
|
||||||
|
- 3 项测试 ALL_PASS(精确首条 ts/显式日期/空清单回退);README 同步。
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
# TamaBox 功能与修复变更记录
|
||||||
|
|
||||||
|
> 变更日期:2026-08-12 ~ 2026-08-13
|
||||||
|
> 说明:本文档汇总本阶段对 TamaBox(NekoBox fork)新增的功能、修复的问题与性能/安全优化,供部署、维护与后续开发参考。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 一、新增功能
|
||||||
|
|
||||||
|
| # | 功能 | 说明 |
|
||||||
|
|---|------|------|
|
||||||
|
| 1 | **问题置顶 / 精选回答** | 提问箱主人在管理页可置顶/取消置顶提问,公开主页置顶优先展示(`is_pinned` 字段 + `PinFirst` 排序) |
|
||||||
|
| 2 | **单题分享图** | 单个问题(提问+回答)生成分享卡片图,仅公开且已回答可生成;复用主页分享图的绘制/缓存/字体模块 |
|
||||||
|
| 3 | **回答后追问** | 提问者凭 token/登录身份对已回答的问题最多追问 3 次,主人可回复;事务+行锁保证并发上限;追问框仅在主人回复上一轮后显示,等待期间提示提问者 |
|
||||||
|
| 4 | **回答 Markdown 渲染** | 回答与追问回答支持 Markdown 排版,服务端渲染 + HTML 白名单过滤(防存储型 XSS),带 XSS 单测 |
|
||||||
|
| 5 | **深色模式** | 全站一键切换深/浅色(cookie 持久化 365 天);桌面端顶栏图标、移动端底部固定操作栏,双入口 |
|
||||||
|
| 6 | **同 IP 重复内容拦截** | 同一 IP 在 5 分钟内提交相同内容(提问/私聊首条)会被拒绝,防刷屏 |
|
||||||
|
| 7 | **匿名 / 登录分级限流** | 登录用户享有 3 倍请求额度,匿名与登录独立限流器统计(滑动窗口) |
|
||||||
|
| 8 | **封禁用户连带清理** | 新增 CLI 命令 `TamaBox ban --email/--domain`:事务级联删除该用户提问、追问、私聊、消息、图片关联并物理删除账号(含二次确认) |
|
||||||
|
| 9 | **提问箱统计看板** | 管理页顶部 6 张统计卡:总提问 / 已回答 / 未回答 / 私密 / 置顶 / 私聊会话 |
|
||||||
|
| 10 | **热门标签榜** | 探索页展示高频用户标签(点击即搜索),热门问题区块按需移除 |
|
||||||
|
| 11 | **全文搜索提问箱** | 管理页可按关键词搜索自己收到的提问与回答(LIKE 模糊匹配,通配符转义,含私密提问) |
|
||||||
|
| 12 | **JSON 全量导出** | `/user/profile/export-json` 导出用户信息 + 提问/回答/追问/图片 + 私聊全部消息,满足数据可携带权;与既有 Excel 导出并存 |
|
||||||
|
| 13 | **多语言(i18n)** | 简体中文 / 繁體中文 / English / 日本語;按 语言 cookie > 登录用户配置 > 提问箱主人配置 > 站点默认 解析;**注册页可直接选择界面语言**(登录后即刻生效),注册成功提示跟随所选语言 |
|
||||||
|
| 14 | **私聊**(已有功能完善) | 登录用户可向开启私聊的提问箱发起会话,支持图片、拉黑、每日条数上限、会话关闭;管理页批量获取首条消息避免 N+1 |
|
||||||
|
| 15 | **页面密码 / 提问密码** | 提问箱页面可设置访问密码、提问可设置密码(bcrypt 存储) |
|
||||||
|
|
||||||
|
## 二、问题修复
|
||||||
|
|
||||||
|
### 编译阻断(在 Linux 上也会编译失败,已全部修复)
|
||||||
|
- `QuestionsStore` 接口缺失 `SetPinned` 方法 → **置顶功能无法编译**,已补接口声明
|
||||||
|
- `internal/route` 限流、IP 黑名单中间件 `ctx.Request()` 类型错误(应为 `ctx.Request().Request`)→ 修复
|
||||||
|
|
||||||
|
### 运行时 500 / 功能异常
|
||||||
|
- `templates/embed.go` 遗漏 `about-me.html` → `/about-me` 页面 500,已补嵌入
|
||||||
|
- **`/user/questions` 500**:`question-list.html` 在 `{{range}}` 内 6 处误用 `.LangCode`(应为 `$.LangCode`),渲染到私密/未回答/私聊条目即报错;已全部修正并新增渲染回归测试
|
||||||
|
- "等待主人回复"提示误显示给提问箱主人 → 增加提问者身份判断
|
||||||
|
- 邮箱 / 域名无唯一索引(并发注册可重复)→ 改为唯一索引
|
||||||
|
- 验证码 remoteIP 未统一解析(反代部署失效)→ 统一走 `shared.ResolveClientIP`
|
||||||
|
|
||||||
|
### 安全 / 稳定性
|
||||||
|
- 图片代理无响应体大小限制(DoS)→ 10MB 上限
|
||||||
|
- 图片代理缺少 302 重定向 SSRF 防护 → 域名白名单 + 内网 IP 拦截 + 逐跳重定向校验
|
||||||
|
- 限流器每个实例泄漏常驻 goroutine → 包级注册表 + 单一清理循环
|
||||||
|
- `censor.RemoveTrustedURL` 白名单删除机制保留(建议定期审查 TrustedHosts)
|
||||||
|
|
||||||
|
### UI / 交互
|
||||||
|
- 提问成功页复制按钮与链接栏大小不协调、两个操作按钮样式不统一 → 统一 flex 布局与按钮样式
|
||||||
|
- 顶栏多语言文字(英文/日文)溢出:最终方案为**恢复 UIkit 居中三列布局**,桌面端原样;手机端(≤640px)改流式单行 + 横向滚动兜底,用户名限宽省略号截断
|
||||||
|
- 管理页置顶按钮与"未回答"等标签不对齐 → 标签组改 flex 容器统一对齐;置顶按钮改用 `uk-label` 标签样式,完全继承 UIkit 尺寸(定制版 `.uk-label` 字号为 0.875rem,不再硬编码)
|
||||||
|
- 语言切换 / 深色模式入口在移动端移入底部固定操作栏(毛玻璃样式)
|
||||||
|
|
||||||
|
## 三、性能与体积优化(分享图)
|
||||||
|
|
||||||
|
- **画布尺寸 1280×720 → 960×540**:绘制与编码工作量降至约 40%
|
||||||
|
- **输出格式 PNG → JPEG(质量 88)**:单张体积约减小 90%(从数百 KB~1MB 降至约 100KB 量级),编码更快
|
||||||
|
- **文字宽度测量改估算**(逐字符宽度累加,替代每次创建 freetype.Context + DrawString 测量)
|
||||||
|
- 分享图结果缓存 TTL 由 30 分钟延长至 1 小时,远程图片缓存 1 小时不变
|
||||||
|
- 名称文字增加柔和投影,增强复杂背景上的可读性
|
||||||
|
|
||||||
|
## 四、新增命令与配置
|
||||||
|
|
||||||
|
### CLI 命令
|
||||||
|
| 命令 | 用途 |
|
||||||
|
|------|------|
|
||||||
|
| `TamaBox web` | 启动 Web 服务 |
|
||||||
|
| `TamaBox censor` | 批量补审未审查的提问/回答(需配置文本审查服务) |
|
||||||
|
| `TamaBox uid` | 为历史用户补生成 UID |
|
||||||
|
| `TamaBox ban --email [email protected]`(或 `--domain`,可加 `--yes` 跳过确认) | 封禁用户并连带清理其全部数据(不可恢复) |
|
||||||
|
|
||||||
|
### 配置项(conf/app.ini)
|
||||||
|
| 配置 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| `[app] default_lang` | 站点默认语言(zh-CN / zh-TW / en / ja),留空默认简体中文 |
|
||||||
|
| `[security] ip_blacklist` / `ip_blacklist_redirect_url` | 逗号分隔 IP/CIDR 黑名单,命中跳转指定 URL |
|
||||||
|
| `[security] trust_proxy` | 反代部署且代理已覆盖 X-Real-IP/X-Forwarded-For 时设为 true,否则 false(防伪造 IP 绕过限流/黑名单) |
|
||||||
|
| `[recaptcha] captcha_type` | recaptcha / turnstile / math(本地算数验证码) |
|
||||||
|
| `[upload] image_*` / `aliyun_*` | 图片存储(R2/S3 或 OSS) |
|
||||||
|
| `[mail] skip_tls_verify` | 自签名 SMTP 证书时跳过校验 |
|
||||||
|
| `[service] tls_insecure_skip_verify` | 内网后端自签名证书时跳过校验 |
|
||||||
|
|
||||||
|
### 编译依赖提示
|
||||||
|
- `chai2010/webp` 需要 CGO 与系统 `libwebp`(Linux:`apt install libwebp-dev`),转换失败自动回退原始格式
|
||||||
|
- 动画 GIF 转 WebP 需要系统 `cwebp` 命令,未安装时回退原始 GIF
|
||||||
|
|
||||||
|
## 五、测试
|
||||||
|
|
||||||
|
- 非 DB 依赖测试全部通过:`templates`(模板解析 + 交叉引用 + 渲染回归)、`internal/i18n`、`internal/shared`、`internal/security/censor`、`internal/template`(含 Markdown XSS 用例)
|
||||||
|
- DB 层测试需要外部 MySQL/Postgres(`DB_TYPE` 环境变量),建议 CI 配置
|
||||||
|
- 注意:Windows 上因 webp 依赖无法完整编译,请在 Linux 环境 `go build ./...` 复核
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
FROM golang:1.20-alpine as builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
ENV CGO_ENABLED=0
|
||||||
|
|
||||||
|
ARG GITHUB_SHA=dev
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
RUN go mod tidy
|
||||||
|
RUN go build -v -ldflags "-w -s -extldflags '-static' -X 'github.com/NekoWheel/NekoBox/internal/conf.BuildCommit=$GITHUB_SHA'" -o NekoBox ./cmd/
|
||||||
|
|
||||||
|
FROM alpine:latest
|
||||||
|
|
||||||
|
RUN apk update && apk add tzdata && cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
|
||||||
|
&& echo "Asia/Shanghai" > /etc/timezone
|
||||||
|
|
||||||
|
WORKDIR /home/app
|
||||||
|
|
||||||
|
COPY --from=builder /app/NekoBox .
|
||||||
|
|
||||||
|
RUN chmod 777 /home/app/NekoBox
|
||||||
|
|
||||||
|
ENTRYPOINT ["./NekoBox", "web"]
|
||||||
|
EXPOSE 8080
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2022 E99p1ant
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
<h1 align="center">
|
||||||
|
<img src="https://nekobox-public.oss-cn-hangzhou.aliyuncs.com/images/Neko.png" width=100px/>
|
||||||
|
|
||||||
|
狼的提问箱
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
匿名提问箱 / Anonymous Question Box
|
||||||
|
|
||||||
|
基于原版NekoBox做了一些微小的修改。主要体现在:
|
||||||
|
- 率先引入二维码访问,同时增加更多自定义可行性,方便自行创作。
|
||||||
|
- 添加探索页面,允许用户自行选择添加标签并展示,为陌生人提问创造可能。
|
||||||
|
- 稍微调整了屏蔽词策略。
|
||||||
|
|
||||||
|
## 截图
|
||||||
|
|
||||||
|
### QRcode
|
||||||
|

|
||||||
|
<br>
|
||||||
|
### Commit with picture
|
||||||
|

|
||||||
|
<br>
|
||||||
|
### Explorer
|
||||||
|

|
||||||
|
<br>
|
||||||
|

|
||||||
|
|
||||||
|
## 安装
|
||||||
|
|
||||||
|
### 需求
|
||||||
|
|
||||||
|
* [Go](https://golang.org/dl/) (v1.19 或更高版本)
|
||||||
|
* [MySQL](https://www.mysql.com/downloads/) (v5.7 或更高版本)
|
||||||
|
* [Redis](https://redis.io/download/) (v6.0 或更高版本)
|
||||||
|
|
||||||
|
### 从源码编译
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/tamakyi/TamaBox.git
|
||||||
|
|
||||||
|
cd TamaBox
|
||||||
|
|
||||||
|
go build -o TamaBox
|
||||||
|
```
|
||||||
|
|
||||||
|
### 编辑配置文件
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp conf/app.sample.ini conf/app.ini
|
||||||
|
```
|
||||||
|
|
||||||
|
### 运行
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./TamaBox web
|
||||||
|
```
|
||||||
|
|
||||||
|
## 架构
|
||||||
|
|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
|
NekoBox 使用 GitHub Actions 进行持续集成和部署。
|
||||||
|
|
||||||
|
当用户访问 NekoBox 时,请求将会被发送至阿里云 CDN,CDN 的访问日志将会被实时推送到阿里云日志服务
|
||||||
|
(SLS)。日志数据将在 SLS 中存储 180 天,用于审计。
|
||||||
|
|
||||||
|
用户的信息、提问和回答将被存储在 MySQL 数据库中。
|
||||||
|
|
||||||
|
用户的会话、CSRF 令牌和电子邮件验证令牌将被暂时存储在 Redis 中。
|
||||||
|
|
||||||
|
用户的整个请求和响应链路将被上传到 Uptrace 用于调试。这些数据将被储存 30 天。管理员可以使用用户提供的 `TraceID`
|
||||||
|
来追踪查询指定的请求。
|
||||||
|
|
||||||
|
当用户提交提问时,问题的内容将被发送到七牛文本审查服务进行审查。如果提问内容存在问题,该内容将被发送到阿里云文本审查服务进行二次审查。
|
||||||
|
如果内容审查仍未通过,该提问将被拒绝发送。这是由于七牛文本审查服务不是很准确,一些非冒犯性的内容可能被七牛文本审查误报。
|
||||||
|
|
||||||
|
当用户收到新的提问时,阿里云邮件服务(DM)会向用户的邮箱发送一封邮件。
|
||||||
|
|
||||||
|
你可以在主页查看 NekoBox 的更新日志,也欢迎访问赞助页面来打钱支持 NekoBox。 更新日志和赞助商名单存储在独立部署的
|
||||||
|
Pocketbase 服务中。
|
||||||
|
|
||||||
|
## 开源协议
|
||||||
|
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
## 备注
|
||||||
|
|
||||||
|
* 基于原版[Nekobox](https://github.com/NekoWheel/NekoBox)修改,基本与原版无异,主要是添加了个人主页二维码和首页统计数,并修改了部分适合自己的参数。
|
||||||
+122
@@ -0,0 +1,122 @@
|
|||||||
|
<h1 align="center">
|
||||||
|
<img src="https://box-user-assets.n3ko.cc/public/Neko.png" width=100px/>
|
||||||
|
|
||||||
|
NekoBox
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
匿名提问箱 / Anonymous Question Box
|
||||||
|
</p>
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://goreportcard.com/badge/github.com/NekoWheel/NekoBox">
|
||||||
|
<img src="https://github.com/NekoWheel/NekoBox/workflows/Go/badge.svg" alt="Go Report Card">
|
||||||
|
</a>
|
||||||
|
<a href="https://sourcegraph.com/github.com/NekoWheel/NekoBox">
|
||||||
|
<img src="https://img.shields.io/badge/view%20on-Sourcegraph-brightgreen.svg?logo=sourcegraph" alt="Sourcegraph">
|
||||||
|
</a>
|
||||||
|
<a href="https://deepsource.io/gh/NekoWheel/NekoBox/?ref=repository-badge">
|
||||||
|
<img src="https://deepsource.io/gh/NekoWheel/NekoBox.svg/?label=active+issues&token=7nuU5C-4QG3CP_5g9qFf3Bl9" alt="DeepSource">
|
||||||
|
</a>
|
||||||
|
<a href="https://goreportcard.com/report/github.com/NekoWheel/NekoBox">
|
||||||
|
<img src="https://goreportcard.com/badge/github.com/NekoWheel/NekoBox" alt="Go Report Card">
|
||||||
|
<a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="/README.zh-CN.md">简体中文</a> | <a href="/README.md">English</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## 安装
|
||||||
|
|
||||||
|
### 需求
|
||||||
|
|
||||||
|
* [Go](https://golang.org/dl/) (v1.19 或更高版本,`go.mod` 声明 `go 1.25.0`)
|
||||||
|
* [MySQL](https://www.mysql.com/downloads/) (v5.7 或更高版本)
|
||||||
|
* [Redis](https://redis.io/download/) (v6.0 或更高版本)
|
||||||
|
|
||||||
|
> 编译依赖说明:`chai2010/webp` 需要 CGO 与系统 `libwebp`(Debian/Ubuntu:`apt install libwebp-dev`),
|
||||||
|
> 静态图片上传时会自动转换为 WebP。若安装失败,转换将自动回退为原始格式(不影响编译之外的功能)。
|
||||||
|
> 动画 GIF 转 WebP 需要系统安装 `cwebp` 命令行工具,未安装时回退为原始 GIF。
|
||||||
|
|
||||||
|
### 从源码编译
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/NekoWheel/NekoBox.git
|
||||||
|
|
||||||
|
cd NekoBox
|
||||||
|
|
||||||
|
go build -o NekoBox
|
||||||
|
```
|
||||||
|
|
||||||
|
### 编辑配置文件
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp conf/app.sample.ini conf/app.ini
|
||||||
|
```
|
||||||
|
|
||||||
|
### 运行
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./NekoBox web
|
||||||
|
```
|
||||||
|
|
||||||
|
### 常用命令
|
||||||
|
|
||||||
|
| 命令 | 用途 |
|
||||||
|
| ---- | ---- |
|
||||||
|
| `./NekoBox web` | 启动 Web 服务 |
|
||||||
|
| `./NekoBox censor` | 批量补审未审查的提问/回答(需配置文本审查服务) |
|
||||||
|
| `./NekoBox uid` | 为历史用户补生成 UID |
|
||||||
|
| `./NekoBox ban --email [email protected]` | 封禁用户并连带清理其提问、追问、私聊与消息(不可恢复,执行前二次确认) |
|
||||||
|
|
||||||
|
## 功能特性
|
||||||
|
|
||||||
|
- **匿名提问 / 私密提问**:支持匿名或登录后提问,可标记私密(仅通过 token 链接可见)
|
||||||
|
- **问题置顶 / 精选回答**:提问箱主人在管理页置顶提问,公开主页置顶优先展示
|
||||||
|
- **回答后追问**:提问者凭 token 可对已回答的问题最多追问 3 次,主人可回复
|
||||||
|
- **Markdown 回答**:回答支持 Markdown 排版(服务端渲染 + 白名单过滤防 XSS)
|
||||||
|
- **分享图**:提问箱主页分享图与单题分享图(含二维码,复用同一绘制模块)
|
||||||
|
- **页面密码 / 提问密码**:可选为提问箱页面设置访问密码、为提问设置密码
|
||||||
|
- **同 IP 重复内容拦截**:同一 IP 在 5 分钟内提交相同内容会被拒绝
|
||||||
|
- **匿名 / 登录分级限流**:登录用户享有更高请求额度(端点级滑动窗口限流)
|
||||||
|
- **IP 黑名单**:支持精确 IP 与 CIDR,命中后跳转到指定 URL
|
||||||
|
- **私聊**:登录用户可向开启私聊的提问箱发起会话,支持图片、拉黑、每日上限
|
||||||
|
- **提问箱统计看板**:管理页展示总提问 / 已回答 / 未回答 / 私密 / 置顶 / 私聊统计
|
||||||
|
- **全文搜索**:管理页可按关键词搜索自己提问箱的提问与回答
|
||||||
|
- **热门问题 / 标签榜**:探索页展示热门标签与最新活跃的公开提问
|
||||||
|
- **数据导出**:支持 Excel 导出与 JSON 全量导出(含追问与私聊,可迁移备份)
|
||||||
|
- **多语言**:简体中文 / 繁體中文 / English / 日本語,支持按 cookie、用户配置与提问箱配置切换
|
||||||
|
- **深色模式**:全站一键切换深/浅色(cookie 持久化)
|
||||||
|
- **内容审查**:七牛 + 阿里云文本审查(可配置),结果带 30 天缓存
|
||||||
|
|
||||||
|
|
||||||
|
## 架构
|
||||||
|
|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
|
NekoBox 使用 GitHub Actions 进行持续集成和部署。
|
||||||
|
|
||||||
|
当用户访问 NekoBox 时,请求将会被发送至阿里云 CDN,CDN 的访问日志将会被实时推送到阿里云日志服务
|
||||||
|
(SLS)。日志数据将在 SLS 中存储 180 天,用于审计。
|
||||||
|
|
||||||
|
用户的信息、提问和回答将被存储在 MySQL 数据库中。
|
||||||
|
|
||||||
|
用户的会话、CSRF 令牌和电子邮件验证令牌将被暂时存储在 Redis 中。
|
||||||
|
|
||||||
|
用户的整个请求和响应链路将被上传到 Uptrace 用于调试。这些数据将被储存 30 天。管理员可以使用用户提供的 `TraceID`
|
||||||
|
来追踪查询指定的请求。
|
||||||
|
|
||||||
|
当用户提交提问时,问题的内容将被发送到七牛文本审查服务进行审查。如果提问内容存在问题,该内容将被发送到阿里云文本审查服务进行二次审查。
|
||||||
|
如果内容审查仍未通过,该提问将被拒绝发送。这是由于七牛文本审查服务不是很准确,一些非冒犯性的内容可能被七牛文本审查误报。
|
||||||
|
|
||||||
|
当用户收到新的提问时,阿里云邮件服务(DM)会向用户的邮箱发送一封邮件。
|
||||||
|
|
||||||
|
你可以在主页查看 NekoBox 的更新日志,也欢迎访问赞助页面来打钱支持 NekoBox。 更新日志和赞助商名单存储在独立部署的
|
||||||
|
Pocketbase 服务中。
|
||||||
|
|
||||||
|
## 开源协议
|
||||||
|
|
||||||
|
MIT License
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
// 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 main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
|
"github.com/urfave/cli/v2"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/cmd"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
app := cli.NewApp()
|
||||||
|
app.Name = "TamaBox"
|
||||||
|
app.Description = "Anonymous question box"
|
||||||
|
|
||||||
|
app.Commands = []*cli.Command{
|
||||||
|
cmd.Web,
|
||||||
|
cmd.Censor,
|
||||||
|
cmd.Uid,
|
||||||
|
}
|
||||||
|
if err := app.Run(os.Args); err != nil {
|
||||||
|
logrus.WithError(err).Fatal("Failed to start application")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
[app]
|
||||||
|
production = true
|
||||||
|
external_url = "https://box.shiroko.one" ; 【必填】站点对外访问地址。用于生成 og:url 与邮件中的全部链接
|
||||||
|
; (找回密码、私信通知等),必须以 http(s):// 开头、结尾不带斜杠
|
||||||
|
; (程序会自动 TrimRight "/")。域名迁移时只改这一处即可全局生效。
|
||||||
|
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:<port>,
|
||||||
|
; 使源站端口仅对本地 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
|
||||||
Binary file not shown.
@@ -0,0 +1,191 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# Insert form-validation i18n keys (form.*) into all four dictionaries.
|
||||||
|
import io, os
|
||||||
|
|
||||||
|
base = os.path.join(os.path.dirname(__file__), "..", "internal", "i18n")
|
||||||
|
|
||||||
|
# key -> {lang: text}
|
||||||
|
keys = {
|
||||||
|
"form.register.email": {
|
||||||
|
"zh_cn": "请填写有效的电子邮箱地址(不超过 100 个字符)",
|
||||||
|
"zh_tw": "請填寫有效的電子郵件地址(不超過 100 個字元)",
|
||||||
|
"en": "Please enter a valid email address (max 100 characters)",
|
||||||
|
"ja": "有効なメールアドレスを入力してください(100文字以内)",
|
||||||
|
},
|
||||||
|
"form.register.domain": {
|
||||||
|
"zh_cn": "个性域名只能包含字母、数字和下划线,长度为 3 至 20 位",
|
||||||
|
"zh_tw": "個性網域只能包含字母、數字與底線,長度為 3 至 20 位",
|
||||||
|
"en": "The custom domain may only contain letters, digits and underscores, and must be 3–20 characters long",
|
||||||
|
"ja": "カスタムドメインは半角英数字とアンダースコアのみ使用でき、3〜20文字である必要があります",
|
||||||
|
},
|
||||||
|
"form.register.name": {
|
||||||
|
"zh_cn": "昵称不能为空,且不超过 20 个字符",
|
||||||
|
"zh_tw": "暱稱不能為空,且不超過 20 個字元",
|
||||||
|
"en": "Nickname is required and must be at most 20 characters",
|
||||||
|
"ja": "ニックネームは必須で、20文字以内である必要があります",
|
||||||
|
},
|
||||||
|
"form.register.password": {
|
||||||
|
"zh_cn": "请设置 8 至 30 位的密码",
|
||||||
|
"zh_tw": "請設定 8 至 30 位的密碼",
|
||||||
|
"en": "Please set a password of 8–30 characters",
|
||||||
|
"ja": "8〜30文字のパスワードを設定してください",
|
||||||
|
},
|
||||||
|
"form.register.repeatPassword": {
|
||||||
|
"zh_cn": "两次输入的密码不一致",
|
||||||
|
"zh_tw": "兩次輸入的密碼不一致",
|
||||||
|
"en": "The two passwords do not match",
|
||||||
|
"ja": "入力した2つのパスワードが一致しません",
|
||||||
|
},
|
||||||
|
"form.register.recaptcha": {
|
||||||
|
"zh_cn": "无法加载人机验证,请刷新页面或切换网络后重试",
|
||||||
|
"zh_tw": "無法人機驗證,請重新整理頁面或更換網路後重試",
|
||||||
|
"en": "Unable to load the CAPTCHA. Please refresh the page or switch your network and try again",
|
||||||
|
"ja": "CAPTCHAを読み込めません。ページを再読み込みするか、ネットワークを変更してお試しください",
|
||||||
|
},
|
||||||
|
"form.email.required": {
|
||||||
|
"zh_cn": "请填写有效的电子邮箱地址",
|
||||||
|
"zh_tw": "請填寫有效的電子郵件地址",
|
||||||
|
"en": "Please enter a valid email address",
|
||||||
|
"ja": "有効なメールアドレスを入力してください",
|
||||||
|
},
|
||||||
|
"form.login.password": {
|
||||||
|
"zh_cn": "请输入密码",
|
||||||
|
"zh_tw": "請輸入密碼",
|
||||||
|
"en": "Please enter your password",
|
||||||
|
"ja": "パスワードを入力してください",
|
||||||
|
},
|
||||||
|
"form.recaptcha": {
|
||||||
|
"zh_cn": "请完成人机验证",
|
||||||
|
"zh_tw": "請完成人機驗證",
|
||||||
|
"en": "Please complete the CAPTCHA verification",
|
||||||
|
"ja": "CAPTCHA認証を完了してください",
|
||||||
|
},
|
||||||
|
"form.recover.newPassword": {
|
||||||
|
"zh_cn": "请设置 8 至 30 位的新密码",
|
||||||
|
"zh_tw": "請設定 8 至 30 位的新密碼",
|
||||||
|
"en": "Please set a new password of 8–30 characters",
|
||||||
|
"ja": "8〜30文字の新しいパスワードを設定してください",
|
||||||
|
},
|
||||||
|
"form.recover.repeatPassword": {
|
||||||
|
"zh_cn": "两次输入的新密码不一致",
|
||||||
|
"zh_tw": "兩次輸入的新密碼不一致",
|
||||||
|
"en": "The two new passwords do not match",
|
||||||
|
"ja": "入力した2つの新しいパスワードが一致しません",
|
||||||
|
},
|
||||||
|
"form.question.content": {
|
||||||
|
"zh_cn": "问题内容不能为空,且不超过 2000 个字符",
|
||||||
|
"zh_tw": "問題內容不能為空,且不超過 2000 個字元",
|
||||||
|
"en": "Question content is required and must be at most 2000 characters",
|
||||||
|
"ja": "質問内容は必須で、2000文字以内である必要があります",
|
||||||
|
},
|
||||||
|
"form.question.receiveReplyEmail": {
|
||||||
|
"zh_cn": "请填写有效的电子邮箱地址以接收回复",
|
||||||
|
"zh_tw": "請填寫有效的電子郵件地址以接收回覆",
|
||||||
|
"en": "Please enter a valid email address to receive replies",
|
||||||
|
"ja": "返信を受け取るための有効なメールアドレスを入力してください",
|
||||||
|
},
|
||||||
|
"form.answer.content": {
|
||||||
|
"zh_cn": "回答内容不能为空,且不超过 2000 个字符",
|
||||||
|
"zh_tw": "回答內容不能為空,且不超過 2000 個字元",
|
||||||
|
"en": "Answer content is required and must be at most 2000 characters",
|
||||||
|
"ja": "回答内容は必須で、2000文字以内である必要があります",
|
||||||
|
},
|
||||||
|
"form.followup.content": {
|
||||||
|
"zh_cn": "追问内容不能为空,且不超过 2000 个字符",
|
||||||
|
"zh_tw": "追問內容不能為空,且不超過 2000 個字元",
|
||||||
|
"en": "Follow-up content is required and must be at most 2000 characters",
|
||||||
|
"ja": "フォローアップ内容は必須で、2000文字以内である必要があります",
|
||||||
|
},
|
||||||
|
"form.followup.answer": {
|
||||||
|
"zh_cn": "追问回答不能为空,且不超过 2000 个字符",
|
||||||
|
"zh_tw": "追問回答不能為空,且不超過 2000 個字元",
|
||||||
|
"en": "Follow-up answer is required and must be at most 2000 characters",
|
||||||
|
"ja": "フォローアップの回答は必須で、2000文字以内である必要があります",
|
||||||
|
},
|
||||||
|
"form.profile.name": {
|
||||||
|
"zh_cn": "昵称不能为空,且不超过 20 个字符",
|
||||||
|
"zh_tw": "暱稱不能為空,且不超過 20 個字元",
|
||||||
|
"en": "Nickname is required and must be at most 20 characters",
|
||||||
|
"ja": "ニックネームは必須で、20文字以内である必要があります",
|
||||||
|
},
|
||||||
|
"form.profile.newPassword": {
|
||||||
|
"zh_cn": "新密码长度不能超过 30 个字符",
|
||||||
|
"zh_tw": "新密碼長度不能超過 30 個字元",
|
||||||
|
"en": "New password must be at most 30 characters",
|
||||||
|
"ja": "新しいパスワードは30文字以内である必要があります",
|
||||||
|
},
|
||||||
|
"form.profile.intro": {
|
||||||
|
"zh_cn": "个人介绍不能为空,且不超过 100 个字符",
|
||||||
|
"zh_tw": "個人介紹不能為空,且不超過 100 個字元",
|
||||||
|
"en": "Bio is required and must be at most 100 characters",
|
||||||
|
"ja": "自己紹介は必須で、100文字以内である必要があります",
|
||||||
|
},
|
||||||
|
"form.profile.colorHex": {
|
||||||
|
"zh_cn": "请填写 7 位十六进制颜色代码(含 #)",
|
||||||
|
"zh_tw": "請填寫 7 位十六進制顏色代碼(含 #)",
|
||||||
|
"en": "Please enter a 7-character hex color code (including #)",
|
||||||
|
"ja": "7文字の16進数カラーコード(#を含む)を入力してください",
|
||||||
|
},
|
||||||
|
"form.profile.dotscale": {
|
||||||
|
"zh_cn": "请填写二维码点大小",
|
||||||
|
"zh_tw": "請填寫 QR Code 點大小",
|
||||||
|
"en": "Please enter the QR code dot size",
|
||||||
|
"ja": "QRコードの点の大きさを入力してください",
|
||||||
|
},
|
||||||
|
"form.profile.backgroundimagealpha": {
|
||||||
|
"zh_cn": "请填写二维码背景透明度",
|
||||||
|
"zh_tw": "請填寫 QR Code 背景透明度",
|
||||||
|
"en": "Please enter the QR code background opacity",
|
||||||
|
"ja": "QRコードの背景の不透明度を入力してください",
|
||||||
|
},
|
||||||
|
"form.profile.linkMax": {
|
||||||
|
"zh_cn": "主页链接长度不能超过 30 个字符",
|
||||||
|
"zh_tw": "主頁連結長度不能超過 30 個字元",
|
||||||
|
"en": "Profile link must be at most 30 characters",
|
||||||
|
"ja": "プロフィールリンクは30文字以内である必要があります",
|
||||||
|
},
|
||||||
|
"form.profile.passwordMax": {
|
||||||
|
"zh_cn": "密码长度不能超过 30 个字符",
|
||||||
|
"zh_tw": "密碼長度不能超過 30 個字元",
|
||||||
|
"en": "Password must be at most 30 characters",
|
||||||
|
"ja": "パスワードは30文字以内である必要があります",
|
||||||
|
},
|
||||||
|
"form.profile.chatMaxMessages": {
|
||||||
|
"zh_cn": "私聊消息上限需为 1 至 50 之间的整数",
|
||||||
|
"zh_tw": "私聊訊息上限需為 1 至 50 之間的整數",
|
||||||
|
"en": "The chat message limit must be an integer between 1 and 50",
|
||||||
|
"ja": "チャットメッセージ上限は1〜50の整数である必要があります",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
files = {
|
||||||
|
"zh_cn": "dict_zh_cn.go",
|
||||||
|
"zh_tw": "dict_zh_tw.go",
|
||||||
|
"en": "dict_en.go",
|
||||||
|
"ja": "dict_ja.go",
|
||||||
|
}
|
||||||
|
|
||||||
|
# Build inserted block (sorted by key for determinism).
|
||||||
|
ordered = sorted(keys.keys())
|
||||||
|
block_lines = ["\n\t// 表单校验", " // 表单校验 (form validation)"]
|
||||||
|
# dedupe comment for non-en langs not needed; use single comment line per lang appropriately.
|
||||||
|
for lang, fname in files.items():
|
||||||
|
path = os.path.join(base, fname)
|
||||||
|
with io.open(path, "r", encoding="utf-8") as fh:
|
||||||
|
text = fh.read()
|
||||||
|
# Insert before the final standalone "}" that closes the map.
|
||||||
|
idx = text.rfind("\n}")
|
||||||
|
if idx == -1:
|
||||||
|
raise SystemExit("cannot find closing brace in " + fname)
|
||||||
|
# Build entries.
|
||||||
|
lines = ["\n\t// 表单校验"]
|
||||||
|
for k in ordered:
|
||||||
|
v = keys[k][lang]
|
||||||
|
# Escape double quotes (none expected, but be safe).
|
||||||
|
v = v.replace('"', '\\"')
|
||||||
|
lines.append('\t"%s":\t"%s",' % (k, v))
|
||||||
|
insertion = "\n".join(lines) + "\n"
|
||||||
|
new_text = text[:idx] + insertion + text[idx:]
|
||||||
|
with io.open(path, "w", encoding="utf-8") as fh:
|
||||||
|
fh.write(new_text)
|
||||||
|
print("updated", fname, "with", len(ordered), "keys")
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# ============================================================================
|
||||||
|
# bench-cdn.sh — UIkit CDN 测速脚本(国内 / 海外双视角)
|
||||||
|
#
|
||||||
|
# 用途:对比"自建 R2 自托管 uikit"与"公共 CDN (cdnjs.snrat.com)"的加载速度,
|
||||||
|
# 用于验证/复测 2026-09-05 的 CDN 迁移是否持续生效。
|
||||||
|
#
|
||||||
|
# 用法:
|
||||||
|
# bash dev/bench-cdn.sh cn # 国内本机:每资源 5 次全量下载取中位
|
||||||
|
# bash dev/bench-cdn.sh global # 海外:check-host.net 多区域节点 (p50/p90)
|
||||||
|
#
|
||||||
|
# 数据结论参考(2026-09-05 基线,国内中位):
|
||||||
|
# css R2 0.864s -> snrat 0.200s (4.3x)
|
||||||
|
# js R2 0.796s -> snrat 0.163s (4.9x)
|
||||||
|
# icons R2 0.824s -> snrat 0.177s (4.7x)
|
||||||
|
# 海外(check-host p50):css 打平;js R2 372ms vs snrat 647ms (R2 略快)
|
||||||
|
# 结论:站点访客以国内为主 -> snrat 净收益大;海外属轻微下降可接受。
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
OLD_CSS="https://r2.337845818.best/tamabox/cdn/expire-1-y/uikit/3.3.3/css/modify-black-font/uikit.min.css"
|
||||||
|
NEW_CSS="https://cdnjs.snrat.com/ajax/libs/uikit/3.3.3/css/uikit.min.css"
|
||||||
|
OLD_JS="https://r2.337845818.best/tamabox/cdn/lib/uikit/3.3.3/js/uikit.min.js"
|
||||||
|
NEW_JS="https://cdnjs.snrat.com/ajax/libs/uikit/3.3.3/js/uikit.min.js"
|
||||||
|
OLD_ICONS="https://r2.337845818.best/tamabox/cdn/lib/uikit/3.3.3/js/uikit-icons.min.js"
|
||||||
|
NEW_ICONS="https://cdnjs.snrat.com/ajax/libs/uikit/3.3.3/js/uikit-icons.min.js"
|
||||||
|
|
||||||
|
# ---------- 国内:全量下载计时 ----------
|
||||||
|
bench_cn() {
|
||||||
|
echo "== 国内本机:每资源 5 次全量下载(秒),取中位 =="
|
||||||
|
local pairs=(
|
||||||
|
"OLD-css (R2 modify):$OLD_CSS"
|
||||||
|
"NEW-css (snrat) :$NEW_CSS"
|
||||||
|
"OLD-js (R2) :$OLD_JS"
|
||||||
|
"NEW-js (snrat) :$NEW_JS"
|
||||||
|
"OLD-icons (R2) :$OLD_ICONS"
|
||||||
|
"NEW-icons (snrat) :$NEW_ICONS"
|
||||||
|
)
|
||||||
|
for entry in "${pairs[@]}"; do
|
||||||
|
local name="${entry%%:*}"; local url="${entry#*:}"
|
||||||
|
local vals=()
|
||||||
|
for i in 1 2 3 4 5; do
|
||||||
|
vals+=("$(curl -sS -o /dev/null -w '%{time_total}' --max-time 20 "$url" 2>/dev/null)")
|
||||||
|
done
|
||||||
|
local sorted=($(printf '%s\n' "${vals[@]}" | sort -n))
|
||||||
|
local med="${sorted[2]}"
|
||||||
|
printf '%-20s : [%s] 中位=%ss\n' "$name" "${vals[*]}" "$med"
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---------- 海外:check-host.net 多区域节点 ----------
|
||||||
|
probe_global() {
|
||||||
|
local name="$1" url="$2"
|
||||||
|
local enc
|
||||||
|
enc=$(python3 -c "import urllib.parse,sys;print(urllib.parse.quote(sys.argv[1],safe=''))" "$url")
|
||||||
|
local rid
|
||||||
|
rid=$(curl -sS -H "Accept: application/json" \
|
||||||
|
"https://check-host.net/check-http?host=$enc&max_nodes=12" 2>/dev/null \
|
||||||
|
| python3 -c "import sys,json;print(json.load(sys.stdin).get('request_id',''))")
|
||||||
|
[ -z "$rid" ] && { echo "$name: 请求失败"; return; }
|
||||||
|
sleep 8
|
||||||
|
curl -sS -H "Accept: application/json" "https://check-host.net/check-result/$rid" 2>/dev/null \
|
||||||
|
| python3 -c "
|
||||||
|
import sys,json,statistics
|
||||||
|
d=json.load(sys.stdin)
|
||||||
|
ms=[]
|
||||||
|
for node,arr in (d or {}).items():
|
||||||
|
if not arr or not arr[0]: continue
|
||||||
|
r=arr[0]
|
||||||
|
if len(r)>3 and str(r[3]).startswith('2') and isinstance(r[1],(int,float)):
|
||||||
|
ms.append(r[1]*1000)
|
||||||
|
if ms:
|
||||||
|
ms.sort()
|
||||||
|
print(f'$name | n={len(ms)} | min={ms[0]:.0f} | p50={statistics.median(ms):.0f} | p90={ms[int(len(ms)*0.9)-1]:.0f} | max={ms[-1]:.0f} ms')
|
||||||
|
else:
|
||||||
|
print(f'$name | 无有效节点')
|
||||||
|
"
|
||||||
|
}
|
||||||
|
|
||||||
|
bench_global() {
|
||||||
|
echo "== 海外:check-host.net 多区域节点探测(HTTP 200 的耗时统计)=="
|
||||||
|
probe_global "OLD css (R2 modify)" "$OLD_CSS"
|
||||||
|
probe_global "NEW css (snrat)" "$NEW_CSS"
|
||||||
|
probe_global "OLD js (R2)" "$OLD_JS"
|
||||||
|
probe_global "NEW js (snrat)" "$NEW_JS"
|
||||||
|
}
|
||||||
|
|
||||||
|
case "$1" in
|
||||||
|
cn) bench_cn ;;
|
||||||
|
global) bench_global ;;
|
||||||
|
*)
|
||||||
|
echo "用法: bash dev/bench-cdn.sh {cn|global}"
|
||||||
|
echo " cn = 国内本机全量下载测速"
|
||||||
|
echo " global = 海外 check-host.net 多区域探测"
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 297 KiB |
@@ -0,0 +1,11 @@
|
|||||||
|
## 2024-03-04 21:45:55
|
||||||
|
新增:用户私信功能上线,可在「我的」页查看匿名来信。
|
||||||
|
修复:移动端问题列表间距过窄的问题。
|
||||||
|
优化:首页加载速度提升约 30%。
|
||||||
|
|
||||||
|
## 2024-02-29 00:00:55
|
||||||
|
修复:部分旧浏览器下时间显示异常。
|
||||||
|
新增:修改记录页(本页),将完整更新历史从首页挪出,保持首页简洁。
|
||||||
|
|
||||||
|
## 2023-06-03 13:11:55
|
||||||
|
项目初始化:匿名提问 / 回答的基础流程跑通。
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
texttmpl "text/template"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/template"
|
||||||
|
"github.com/tamakyi/TamaBox/templates"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mergedFuncMap 将项目实际使用的模板函数(含 t 等 i18n 函数)合并为 text/template.FuncMap。
|
||||||
|
// 不使用 FuncMap 直接解析会因 "t" 等函数未定义而误报模板错误。
|
||||||
|
func mergedFuncMap() texttmpl.FuncMap {
|
||||||
|
fm := texttmpl.FuncMap{}
|
||||||
|
for _, m := range template.FuncMap() {
|
||||||
|
for k, v := range m {
|
||||||
|
fm[k] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fm
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
hasErr := false
|
||||||
|
_ = fs.WalkDir(templates.FS, ".", func(path string, d fs.DirEntry, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if d.IsDir() || !strings.HasSuffix(path, ".html") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if _, err := texttmpl.New(path).Funcs(mergedFuncMap()).ParseFS(templates.FS, path); err != nil {
|
||||||
|
fmt.Println("TEMPLATE ERROR:", path, "->", err)
|
||||||
|
hasErr = true
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if hasErr {
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fmt.Println("all templates syntax OK")
|
||||||
|
}
|
||||||
Vendored
+21
File diff suppressed because one or more lines are too long
@@ -0,0 +1,219 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.2",
|
||||||
|
"tcp_ms": 176.9,
|
||||||
|
"handshake_ms": 599.1,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.4",
|
||||||
|
"tcp_ms": 609.9,
|
||||||
|
"handshake_ms": 794.4,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.9",
|
||||||
|
"tcp_ms": 791.7,
|
||||||
|
"handshake_ms": 973.8,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.10",
|
||||||
|
"tcp_ms": 973.8,
|
||||||
|
"handshake_ms": 1153.9,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.7",
|
||||||
|
"tcp_ms": 1156.6,
|
||||||
|
"handshake_ms": 1914.6,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.21",
|
||||||
|
"tcp_ms": 1906.3,
|
||||||
|
"handshake_ms": 2689.0,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.1",
|
||||||
|
"tcp_ms": 2703.3,
|
||||||
|
"handshake_ms": 3606.3,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.11",
|
||||||
|
"tcp_ms": 3600.5,
|
||||||
|
"handshake_ms": 3795.7,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.5",
|
||||||
|
"tcp_ms": 3800.5,
|
||||||
|
"handshake_ms": 3996.5,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.6",
|
||||||
|
"tcp_ms": 3996.7,
|
||||||
|
"handshake_ms": 4194.4,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.8",
|
||||||
|
"tcp_ms": 4194.1,
|
||||||
|
"handshake_ms": 5120.6,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.18",
|
||||||
|
"tcp_ms": 5114.5,
|
||||||
|
"handshake_ms": 5299.6,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.20",
|
||||||
|
"tcp_ms": 5298.5,
|
||||||
|
"handshake_ms": 6025.5,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.12",
|
||||||
|
"tcp_ms": 6031.7,
|
||||||
|
"handshake_ms": 6218.7,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.3",
|
||||||
|
"tcp_ms": 6225.4,
|
||||||
|
"handshake_ms": 7469.9,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.23",
|
||||||
|
"tcp_ms": 7457.2,
|
||||||
|
"handshake_ms": 7648.1,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.29",
|
||||||
|
"tcp_ms": 7644.9,
|
||||||
|
"handshake_ms": 7827.4,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.26",
|
||||||
|
"tcp_ms": 7829.8,
|
||||||
|
"handshake_ms": 8188.7,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.15",
|
||||||
|
"tcp_ms": 8197.2,
|
||||||
|
"handshake_ms": 8388.9,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.16",
|
||||||
|
"tcp_ms": 8388.6,
|
||||||
|
"handshake_ms": 8585.0,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.32",
|
||||||
|
"tcp_ms": 8574.8,
|
||||||
|
"handshake_ms": 9287.3,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.19",
|
||||||
|
"tcp_ms": 9297.3,
|
||||||
|
"handshake_ms": 9490.1,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.13",
|
||||||
|
"tcp_ms": 9494.5,
|
||||||
|
"handshake_ms": 9692.0,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.22",
|
||||||
|
"tcp_ms": 9686.6,
|
||||||
|
"handshake_ms": 10704.7,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.24",
|
||||||
|
"tcp_ms": 10704.7,
|
||||||
|
"handshake_ms": 11717.3,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.25",
|
||||||
|
"tcp_ms": 11717.6,
|
||||||
|
"handshake_ms": 12484.2,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.34",
|
||||||
|
"tcp_ms": 12479.1,
|
||||||
|
"handshake_ms": 12667.2,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.14",
|
||||||
|
"tcp_ms": 12681.3,
|
||||||
|
"handshake_ms": 13862.1,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.42",
|
||||||
|
"tcp_ms": 13843.7,
|
||||||
|
"handshake_ms": 14038.8,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.37",
|
||||||
|
"tcp_ms": 14043.4,
|
||||||
|
"handshake_ms": 14412.6,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.150.35",
|
||||||
|
"tcp_ms": 14414.9,
|
||||||
|
"handshake_ms": 15780.7,
|
||||||
|
"tls": "TLSv1.3",
|
||||||
|
"alpn": "http/1.1"
|
||||||
|
}
|
||||||
|
]
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"ip": "43.175.107.217",
|
||||||
|
"http": "400",
|
||||||
|
"total_s": 1.010907,
|
||||||
|
"elapsed_ms": 3525.3,
|
||||||
|
"note": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.175.118.111",
|
||||||
|
"http": "400",
|
||||||
|
"total_s": 1.113784,
|
||||||
|
"elapsed_ms": 2782.9,
|
||||||
|
"note": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.175.18.50",
|
||||||
|
"http": "200",
|
||||||
|
"total_s": 1.504578,
|
||||||
|
"elapsed_ms": 1629.3,
|
||||||
|
"note": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.175.17.109",
|
||||||
|
"http": "200",
|
||||||
|
"total_s": 1.675108,
|
||||||
|
"elapsed_ms": 2895.5,
|
||||||
|
"note": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.175.113.139",
|
||||||
|
"http": "200",
|
||||||
|
"total_s": 1.79808,
|
||||||
|
"elapsed_ms": 3461.2,
|
||||||
|
"note": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.175.119.214",
|
||||||
|
"http": "200",
|
||||||
|
"total_s": 1.836886,
|
||||||
|
"elapsed_ms": 4706.9,
|
||||||
|
"note": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.175.115.202",
|
||||||
|
"http": "200",
|
||||||
|
"total_s": 1.977182,
|
||||||
|
"elapsed_ms": 3401.5,
|
||||||
|
"note": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.175.115.123",
|
||||||
|
"http": "200",
|
||||||
|
"total_s": 1.987886,
|
||||||
|
"elapsed_ms": 3563.1,
|
||||||
|
"note": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.175.115.149",
|
||||||
|
"http": "200",
|
||||||
|
"total_s": 2.029702,
|
||||||
|
"elapsed_ms": 3139.6,
|
||||||
|
"note": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.175.119.174",
|
||||||
|
"http": "200",
|
||||||
|
"total_s": 2.116343,
|
||||||
|
"elapsed_ms": 3937.1,
|
||||||
|
"note": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.175.119.230",
|
||||||
|
"http": "200",
|
||||||
|
"total_s": 2.65339,
|
||||||
|
"elapsed_ms": 4696.5,
|
||||||
|
"note": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.126.220",
|
||||||
|
"http": "200",
|
||||||
|
"total_s": 3.056871,
|
||||||
|
"elapsed_ms": 4404.8,
|
||||||
|
"note": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.175.115.41",
|
||||||
|
"http": "200",
|
||||||
|
"total_s": 3.309262,
|
||||||
|
"elapsed_ms": 4261.4,
|
||||||
|
"note": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.174.126.152",
|
||||||
|
"http": "200",
|
||||||
|
"total_s": 3.333779,
|
||||||
|
"elapsed_ms": 4557.8,
|
||||||
|
"note": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.175.17.185",
|
||||||
|
"http": "200",
|
||||||
|
"total_s": 3.525846,
|
||||||
|
"elapsed_ms": 5194.5,
|
||||||
|
"note": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ip": "43.175.16.233",
|
||||||
|
"http": "200",
|
||||||
|
"total_s": 4.754878,
|
||||||
|
"elapsed_ms": 6255.5,
|
||||||
|
"note": ""
|
||||||
|
}
|
||||||
|
]
|
||||||
+3579
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,114 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
EO 优选 IP 免费探测脚本 (方案 B 免费替代 wetest.vip)
|
||||||
|
原理: EdgeOne 边缘节点(腾讯云香港 43.174.x/43.175.x 段)对任意 EO 接入域名做 SNI 路由。
|
||||||
|
若某 IP:443 能对 box.shiroko.one 完成 TLS 握手, 则该 IP 可作为境内 A 记录直连目标。
|
||||||
|
用法:
|
||||||
|
python eo-probe-ips.py # 扫默认段列表(已知优选 IP 所在 /24)
|
||||||
|
python eo-probe-ips.py --host box.shiroko.one --out eo-hits.json
|
||||||
|
判定: TCP 连通 + TLS 握手成功(SNI=目标host) -> hit; 记录握手 RTT。
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import socket
|
||||||
|
import ssl
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
# 已知/疑似 EO 香港优质 IP 所在段(来自社区 itdog 截图统计 + 教程)
|
||||||
|
DEFAULT_CIDRS = [
|
||||||
|
"43.174.150.0/24", "43.174.78.0/24", "43.174.79.0/24", "43.174.57.0/24",
|
||||||
|
"43.175.130.0/24", "43.175.132.0/24", "43.175.151.0/24", "43.175.165.0/24",
|
||||||
|
"43.175.185.0/24", "43.175.150.0/24", "43.174.152.0/24", "43.174.153.0/24",
|
||||||
|
"43.175.131.0/24", "43.175.133.0/24",
|
||||||
|
]
|
||||||
|
|
||||||
|
def cidr_hosts(cidr: str):
|
||||||
|
net, bits = cidr.split("/")
|
||||||
|
bits = int(bits)
|
||||||
|
a, b, c, d = map(int, net.split("."))
|
||||||
|
base = (a << 24) + (b << 16) + (c << 8) + d
|
||||||
|
count = 1 << (32 - bits)
|
||||||
|
for i in range(1, count - 1): # skip network & broadcast
|
||||||
|
v = base + i
|
||||||
|
yield f"{(v >> 24) & 255}.{(v >> 16) & 255}.{(v >> 8) & 255}.{v & 255}"
|
||||||
|
|
||||||
|
async def probe(ip: str, host: str, timeout: float, sem: asyncio.Semaphore):
|
||||||
|
"""TCP connect + TLS handshake (SNI=host). Return dict or None."""
|
||||||
|
async with sem:
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
t0 = time.perf_counter()
|
||||||
|
try:
|
||||||
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
sock.settimeout(timeout)
|
||||||
|
# async connect
|
||||||
|
await loop.sock_connect(sock, (ip, 443))
|
||||||
|
tcp_ms = (time.perf_counter() - t0) * 1000
|
||||||
|
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||||
|
ctx.check_hostname = False
|
||||||
|
ctx.verify_mode = ssl.CERT_NONE
|
||||||
|
ctx.set_alpn_protocols(["http/1.1"])
|
||||||
|
tls_sock = ctx.wrap_socket(sock, server_hostname=host)
|
||||||
|
tls_sock.settimeout(timeout)
|
||||||
|
tls_ms = (time.perf_counter() - t0) * 1000
|
||||||
|
ver = tls_sock.version()
|
||||||
|
alpn = tls_sock.selected_alpn_protocol()
|
||||||
|
tls_sock.close()
|
||||||
|
sock.close()
|
||||||
|
return {"ip": ip, "tcp_ms": round(tcp_ms, 1),
|
||||||
|
"handshake_ms": round(tls_ms, 1), "tls": ver, "alpn": alpn}
|
||||||
|
except Exception as e:
|
||||||
|
try:
|
||||||
|
sock.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("--host", default="box.shiroko.one")
|
||||||
|
ap.add_argument("--cidrs", nargs="*", default=None)
|
||||||
|
ap.add_argument("--concurrency", type=int, default=256)
|
||||||
|
ap.add_argument("--timeout", type=float, default=2.5)
|
||||||
|
ap.add_argument("--out", default="eo-hits.json")
|
||||||
|
args = ap.parse_args()
|
||||||
|
|
||||||
|
cidrs = args.cidrs or DEFAULT_CIDRS
|
||||||
|
ips = []
|
||||||
|
for c in cidrs:
|
||||||
|
ips.extend(cidr_hosts(c))
|
||||||
|
print(f"[*] 目标 host: {args.host} 段数: {len(cidrs)} 待测 IP: {len(ips)} 并发: {args.concurrency}")
|
||||||
|
|
||||||
|
sem = asyncio.Semaphore(args.concurrency)
|
||||||
|
hits = []
|
||||||
|
done = 0
|
||||||
|
t_start = time.perf_counter()
|
||||||
|
|
||||||
|
# chunk to avoid building all tasks at once
|
||||||
|
CH = args.concurrency * 4
|
||||||
|
for i in range(0, len(ips), CH):
|
||||||
|
chunk = ips[i:i + CH]
|
||||||
|
tasks = [asyncio.create_task(probe(ip, args.host, args.timeout, sem)) for ip in chunk]
|
||||||
|
results = await asyncio.gather(*tasks)
|
||||||
|
for r in results:
|
||||||
|
if r:
|
||||||
|
hits.append(r)
|
||||||
|
done += len(chunk)
|
||||||
|
if done % (len(ips) // 10 or 1) == 0 or done == len(ips):
|
||||||
|
el = time.perf_counter() - t_start
|
||||||
|
print(f" [{done}/{len(ips)}] hits={len(hits)} elapsed={el:.1f}s")
|
||||||
|
|
||||||
|
hits.sort(key=lambda x: x["handshake_ms"])
|
||||||
|
print(f"\n[*] 完成: {done} IP 用时 {time.perf_counter()-t_start:.1f}s, 命中 {len(hits)}")
|
||||||
|
for h in hits[:40]:
|
||||||
|
print(f" {h['ip']:16s} tcp={h['tcp_ms']:6.1f}ms hs={h['handshake_ms']:6.1f}ms tls={h['tls']} alpn={h['alpn']}")
|
||||||
|
|
||||||
|
if hits and args.out:
|
||||||
|
with open(args.out, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(hits, f, ensure_ascii=False, indent=2)
|
||||||
|
print(f"[*] 结果已存: {args.out}")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
EO 优选 IP 扫描 v2 (schannel 证书校验版)
|
||||||
|
判据更严格: 用 curl (Windows schannel, 系统证书链) + --resolve 强制 SNI,
|
||||||
|
只有当 TLS 证书链校验通过(浏览器视角可访问)且返回 HTTP 响应才算 hit。
|
||||||
|
这能区分 "CDN 通用池 IP (证书 *.cdn.myqcloud.com 不匹配)" 与 "真正承载目标站点的 EO 边缘"。
|
||||||
|
用法: python eo-probe-v2.py --cidrs 43.174.246.0/24 43.174.247.0/24 ...
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import concurrent.futures
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
|
||||||
|
DEFAULT_CIDRS = [
|
||||||
|
"43.174.150.0/24", "43.174.151.0/24", "43.174.152.0/24", "43.174.153.0/24",
|
||||||
|
"43.174.78.0/24", "43.174.79.0/24", "43.174.57.0/24",
|
||||||
|
"43.175.130.0/24", "43.175.131.0/24", "43.175.132.0/24", "43.175.133.0/24",
|
||||||
|
"43.175.150.0/24", "43.175.151.0/24", "43.175.152.0/24",
|
||||||
|
"43.175.165.0/24", "43.175.166.0/24",
|
||||||
|
"43.175.185.0/24", "43.175.186.0/24",
|
||||||
|
"43.174.246.0/24", "43.174.247.0/24", # EO 官方当前分配段(新加坡)
|
||||||
|
]
|
||||||
|
|
||||||
|
def cidr_hosts(cidr):
|
||||||
|
net, bits = cidr.split("/")
|
||||||
|
bits = int(bits)
|
||||||
|
a, b, c, d = map(int, net.split("."))
|
||||||
|
base = (a << 24) + (b << 16) + (c << 8) + d
|
||||||
|
count = 1 << (32 - bits)
|
||||||
|
for i in range(1, count - 1):
|
||||||
|
v = base + i
|
||||||
|
yield f"{(v >> 24) & 255}.{(v >> 16) & 255}.{(v >> 8) & 255}.{v & 255}"
|
||||||
|
|
||||||
|
def probe(ip, host, timeout):
|
||||||
|
t0 = time.perf_counter()
|
||||||
|
# schannel on Windows: 默认走系统 CA, 证书不匹配会直接失败 => http_code 000 + 错误
|
||||||
|
cmd = ["curl", "-sS", "--resolve", f"{host}:443:{ip}",
|
||||||
|
"--connect-timeout", str(timeout), "--max-time", str(timeout * 2),
|
||||||
|
"-o", "NUL", "-w", "%{http_code}|%{time_total}|%{time_starttransfer}",
|
||||||
|
f"https://{host}/"]
|
||||||
|
try:
|
||||||
|
r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout * 3,
|
||||||
|
errors="replace")
|
||||||
|
out = r.stdout.strip()
|
||||||
|
parts = out.split("|")
|
||||||
|
code = parts[0] if parts else "000"
|
||||||
|
el = (time.perf_counter() - t0) * 1000
|
||||||
|
err = r.stderr.strip() if r.stderr else ""
|
||||||
|
if code not in ("000",):
|
||||||
|
return {"ip": ip, "http": code, "total_s": float(parts[1]) if len(parts) > 1 else None,
|
||||||
|
"elapsed_ms": round(el, 1), "note": err.splitlines()[-1] if err else ""}
|
||||||
|
# 000: 看看是不是证书错误
|
||||||
|
note = ""
|
||||||
|
if "SEC_E_WRONG_PRINCIPAL" in err or "certificate" in err.lower():
|
||||||
|
note = "cert-mismatch"
|
||||||
|
elif err:
|
||||||
|
note = err.splitlines()[-1][:80]
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("--host", default="box.shiroko.one")
|
||||||
|
ap.add_argument("--cidrs", nargs="*", default=None)
|
||||||
|
ap.add_argument("--workers", type=int, default=64)
|
||||||
|
ap.add_argument("--timeout", type=float, default=3)
|
||||||
|
ap.add_argument("--out", default="eo-hits-v2.json")
|
||||||
|
args = ap.parse_args()
|
||||||
|
|
||||||
|
cidrs = args.cidrs or DEFAULT_CIDRS
|
||||||
|
ips = []
|
||||||
|
for c in cidrs:
|
||||||
|
ips.extend(cidr_hosts(c))
|
||||||
|
print(f"[*] host={args.host} 段={len(cidrs)} IP={len(ips)} workers={args.workers}")
|
||||||
|
|
||||||
|
hits = []
|
||||||
|
t_start = time.perf_counter()
|
||||||
|
with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) as ex:
|
||||||
|
futs = {ex.submit(probe, ip, args.host, args.timeout): ip for ip in ips}
|
||||||
|
done = 0
|
||||||
|
for fut in concurrent.futures.as_completed(futs):
|
||||||
|
done += 1
|
||||||
|
r = fut.result()
|
||||||
|
if r:
|
||||||
|
hits.append(r)
|
||||||
|
print(f" HIT {r['ip']:16s} http={r['http']} total={r['total_s']}s {r['note']}")
|
||||||
|
if done % 500 == 0:
|
||||||
|
print(f" [{done}/{len(ips)}] hits={len(hits)} elapsed={time.perf_counter()-t_start:.0f}s")
|
||||||
|
|
||||||
|
print(f"\n[*] done in {time.perf_counter()-t_start:.0f}s, hits={len(hits)}")
|
||||||
|
if hits:
|
||||||
|
hits.sort(key=lambda x: x["total_s"] or 99)
|
||||||
|
with open(args.out, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(hits, f, ensure_ascii=False, indent=2)
|
||||||
|
print(f"[*] saved: {args.out}")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
EO 全段扫描 v3 (方案 B: 找所有能服务 box.shiroko.one 的 EO 边缘 IP)
|
||||||
|
两段式: 1) asyncio TCP:443 预筛全段 2) openssl 对 TCP 通的 IP 做 SNI 证书核验 (CN 含 host)
|
||||||
|
输出: eo-all-hits.json [{ip, cn, tcp_ms}]
|
||||||
|
用法: python eo-scan-all.py --host box.shiroko.one --nets 43.174.0.0/16 43.175.0.0/16 --workers 400
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import socket
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
|
||||||
|
def iter_hosts(net: str):
|
||||||
|
net, bits = net.split("/")
|
||||||
|
bits = int(bits)
|
||||||
|
a, b, c, d = map(int, net.split("."))
|
||||||
|
base = (a << 24) + (b << 16) + (c << 8) + d
|
||||||
|
count = 1 << (32 - bits)
|
||||||
|
for i in range(1, count - 1):
|
||||||
|
v = base + i
|
||||||
|
yield f"{(v >> 24) & 255}.{(v >> 16) & 255}.{(v >> 8) & 255}.{v & 255}"
|
||||||
|
|
||||||
|
async def tcp_probe(ip: str, port: int, timeout: float, sem: asyncio.Semaphore):
|
||||||
|
async with sem:
|
||||||
|
t0 = time.perf_counter()
|
||||||
|
try:
|
||||||
|
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
s.setblocking(False)
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
await asyncio.wait_for(loop.sock_connect(s, (ip, port)), timeout)
|
||||||
|
ms = (time.perf_counter() - t0) * 1000
|
||||||
|
s.close()
|
||||||
|
return ip, ms
|
||||||
|
except Exception:
|
||||||
|
try:
|
||||||
|
s.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return None
|
||||||
|
|
||||||
|
def tls_cn(ip: str, host: str, timeout: float):
|
||||||
|
try:
|
||||||
|
r = subprocess.run(
|
||||||
|
["openssl", "s_client", "-connect", f"{ip}:443", "-servername", host,
|
||||||
|
"-tlsextdebug", "-no_ign_eof"],
|
||||||
|
capture_output=True, text=True, timeout=timeout, errors="replace",
|
||||||
|
input="Q")
|
||||||
|
out = r.stdout + r.stderr
|
||||||
|
cn = ""
|
||||||
|
for line in out.splitlines():
|
||||||
|
ls = line.strip()
|
||||||
|
if ls.startswith("subject="):
|
||||||
|
cn = ls
|
||||||
|
break
|
||||||
|
return {"ip": ip, "cn": cn or "(no-subject)", "ok": host in cn}
|
||||||
|
except Exception as e:
|
||||||
|
return {"ip": ip, "cn": f"ERR:{type(e).__name__}", "ok": False}
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("--host", default="box.shiroko.one")
|
||||||
|
ap.add_argument("--nets", nargs="*",
|
||||||
|
default=["43.174.0.0/16", "43.175.0.0/16"])
|
||||||
|
ap.add_argument("--workers", type=int, default=300)
|
||||||
|
ap.add_argument("--timeout", type=float, default=2.0)
|
||||||
|
ap.add_argument("--out", default="eo-all-hits.json")
|
||||||
|
args = ap.parse_args()
|
||||||
|
|
||||||
|
all_ips = []
|
||||||
|
for n in args.nets:
|
||||||
|
all_ips.extend(iter_hosts(n))
|
||||||
|
print(f"[*] host={args.host} 网段={args.nets} 总IP={len(all_ips)}")
|
||||||
|
|
||||||
|
# Stage 1: TCP 预筛
|
||||||
|
sem = asyncio.Semaphore(args.workers)
|
||||||
|
open_ips = []
|
||||||
|
|
||||||
|
async def run_tcp():
|
||||||
|
CH = args.workers * 6
|
||||||
|
for i in range(0, len(all_ips), CH):
|
||||||
|
chunk = all_ips[i:i + CH]
|
||||||
|
tasks = [asyncio.create_task(tcp_probe(ip, 443, args.timeout, sem)) for ip in chunk]
|
||||||
|
res = await asyncio.gather(*tasks)
|
||||||
|
for r in res:
|
||||||
|
if r:
|
||||||
|
open_ips.append(r)
|
||||||
|
if (i + CH) % 20000 < CH or i + CH >= len(all_ips):
|
||||||
|
print(f" tcp预筛 [{i+CH}/{len(all_ips)}] open={len(open_ips)}", flush=True)
|
||||||
|
t0 = time.perf_counter()
|
||||||
|
asyncio.run(run_tcp())
|
||||||
|
print(f"[*] TCP 预筛完成: {len(all_ips)} -> {len(open_ips)} open, {time.perf_counter()-t0:.0f}s")
|
||||||
|
|
||||||
|
if not open_ips:
|
||||||
|
print("[!] 无开放 IP")
|
||||||
|
return
|
||||||
|
|
||||||
|
# Stage 2: openssl 证书核验
|
||||||
|
hits = []
|
||||||
|
with ThreadPoolExecutor(max_workers=64) as ex:
|
||||||
|
futs = [ex.submit(tls_cn, ip, args.host, args.timeout * 2) for ip, _ in open_ips]
|
||||||
|
done = 0
|
||||||
|
for fut in futures_as_completed(futs):
|
||||||
|
done += 1
|
||||||
|
r = fut.result()
|
||||||
|
if r and r["ok"]:
|
||||||
|
hits.append(r)
|
||||||
|
print(f" HIT {r['ip']:16s} {r['cn']}", flush=True)
|
||||||
|
if done % 200 == 0:
|
||||||
|
print(f" 证书核验 [{done}/{len(open_ips)}] hits={len(hits)}", flush=True)
|
||||||
|
|
||||||
|
print(f"\n[*] 全部完成: hits={len(hits)}")
|
||||||
|
if hits:
|
||||||
|
with open(args.out, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(hits, f, ensure_ascii=False, indent=2)
|
||||||
|
print(f"[*] saved: {args.out}")
|
||||||
|
|
||||||
|
def futures_as_completed(futs):
|
||||||
|
import concurrent.futures
|
||||||
|
for fut in concurrent.futures.as_completed(futs):
|
||||||
|
yield fut
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
gen_changelog.py — 生成 PocketBase 风格的 changelogs JSON(无需 PocketBase 服务)
|
||||||
|
|
||||||
|
用途:
|
||||||
|
你在本地维护一个 Markdown 源文件(按 `## <时间戳>` 分段写 changelog),
|
||||||
|
本脚本把它导出成前端 change-logs.html 所 fetch 的 tamabox.changelogs.json。
|
||||||
|
输出格式完全兼容 PocketBase list API 的返回结构,但无需部署任何后端服务,
|
||||||
|
因此不会在你的 1C1G 服务器上多占哪怕 1 MB 常驻内存。
|
||||||
|
|
||||||
|
输出位置:static/tamabox.changelogs.json —— 该文件被 static 包以 //go:embed 打入
|
||||||
|
二进制,由 flamego.Static 在 /static 路径同源提供,前端直接 fetch 同源路径,
|
||||||
|
不再依赖任何外部域名(去掉 api-direct.337845818.best 等外链,降低可用性/安全风险)。
|
||||||
|
|
||||||
|
源文件格式(dev/changelog-source.md 示例):
|
||||||
|
## 2024-03-04 21:45:55
|
||||||
|
新增:用户私信功能上线。
|
||||||
|
修复:移动端问题列表间距过窄。
|
||||||
|
|
||||||
|
## 2024-02-29 00:00:55
|
||||||
|
优化:首页加载速度提升约 30%。
|
||||||
|
|
||||||
|
注意:
|
||||||
|
- 时间戳支持 `YYYY-MM-DD HH:MM:SS` / `YYYY-MM-DD` / 带毫秒的 `...fffZ` / ISO 格式,
|
||||||
|
脚本会统一归一化为 PocketBase 风格的 `YYYY-MM-DD HH:MM:SS.fffZ`(UTC)。
|
||||||
|
- 正文里的换行默认会被转成 `<br>`,因为前端用 x-html 渲染;传 --no-br 可关闭。
|
||||||
|
- 导出时按时间倒序排列,最新一条排在最前(前端读 items[0] 即取最新)。
|
||||||
|
|
||||||
|
用法:
|
||||||
|
python dev/gen_changelog.py
|
||||||
|
python dev/gen_changelog.py 源文件.md 输出.json
|
||||||
|
python dev/gen_changelog.py 源文件.md 输出.json --no-br
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
COLLECTION_ID = "tamabox"
|
||||||
|
COLLECTION_NAME = "tamabox-changelogs"
|
||||||
|
DEFAULT_SRC = "dev/changelog-source.md"
|
||||||
|
DEFAULT_OUT = "static/tamabox.changelogs.json"
|
||||||
|
|
||||||
|
TS_LINE = re.compile(r"^##\s+(.+?)\s*$")
|
||||||
|
FULL_TS = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}Z$")
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_ts(raw: str) -> str:
|
||||||
|
"""把用户输入的时间归一化为 PocketBase 风格时间戳:YYYY-MM-DD HH:MM:SS.fffZ(UTC)。"""
|
||||||
|
raw = raw.strip()
|
||||||
|
if FULL_TS.match(raw):
|
||||||
|
return raw
|
||||||
|
for fmt in ("%Y-%m-%d %H:%M:%S.%fZ", "%Y-%m-%d %H:%M:%S",
|
||||||
|
"%Y-%m-%d %H:%M", "%Y-%m-%d"):
|
||||||
|
try:
|
||||||
|
dt = datetime.strptime(raw, fmt)
|
||||||
|
return dt.strftime("%Y-%m-%d %H:%M:%S") + ".000Z"
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
dt = datetime.fromisoformat(raw.replace("Z", "+00:00"))
|
||||||
|
return dt.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S") + ".000Z"
|
||||||
|
except ValueError:
|
||||||
|
sys.exit(f"[错误] 无法解析时间戳: {raw!r}")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_source(text: str):
|
||||||
|
"""按 `## <时间戳>` 分段,返回 [(ts, content), ...],顺序与源文件一致。"""
|
||||||
|
entries, cur_ts, buf = [], None, []
|
||||||
|
for line in text.splitlines():
|
||||||
|
m = TS_LINE.match(line)
|
||||||
|
if m:
|
||||||
|
if cur_ts is not None:
|
||||||
|
entries.append((cur_ts, "\n".join(buf).strip()))
|
||||||
|
cur_ts, buf = m.group(1).strip(), []
|
||||||
|
elif cur_ts is not None:
|
||||||
|
buf.append(line)
|
||||||
|
if cur_ts is not None:
|
||||||
|
entries.append((cur_ts, "\n".join(buf).strip()))
|
||||||
|
if not entries:
|
||||||
|
sys.exit("[错误] 源文件未找到任何 '## <时间戳>' 分段")
|
||||||
|
return entries
|
||||||
|
|
||||||
|
|
||||||
|
def build(entries, br=True):
|
||||||
|
"""把条目导出为 PocketBase list API 风格 JSON(最新在前)。"""
|
||||||
|
parsed = [(normalize_ts(ts), c) for ts, c in entries]
|
||||||
|
parsed.sort(key=lambda x: x[0], reverse=True) # 倒序:最新 published_at 在前
|
||||||
|
items = []
|
||||||
|
for ts, content in parsed:
|
||||||
|
items.append({
|
||||||
|
"collectionId": COLLECTION_ID,
|
||||||
|
"collectionName": COLLECTION_NAME,
|
||||||
|
"content": content.replace("\n", "<br>\n") if br else content,
|
||||||
|
"created": ts,
|
||||||
|
"id": "none",
|
||||||
|
"published_at": ts,
|
||||||
|
"updated": ts,
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
"page": 1,
|
||||||
|
"perPage": len(items) or 1,
|
||||||
|
"totalItems": len(items),
|
||||||
|
"totalPages": 1,
|
||||||
|
"items": items,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args = sys.argv[1:]
|
||||||
|
br = "--no-br" not in args
|
||||||
|
paths = [a for a in args if not a.startswith("--")]
|
||||||
|
src = paths[0] if len(paths) > 0 else DEFAULT_SRC
|
||||||
|
out = paths[1] if len(paths) > 1 else DEFAULT_OUT
|
||||||
|
try:
|
||||||
|
with open(src, encoding="utf-8") as f:
|
||||||
|
text = f.read()
|
||||||
|
except FileNotFoundError:
|
||||||
|
sys.exit(f"[错误] 找不到源文件: {src}")
|
||||||
|
data = build(parse_source(text), br=br)
|
||||||
|
with open(out, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||||
|
latest = data["items"][0]["published_at"] if data["items"] else "N/A"
|
||||||
|
print(f"[完成] 已生成 {out}({data['totalItems']} 条记录,最新发布于 {latest})")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
|||||||
|
{"Replace": {"C:/Users/Tamakyi Gekka/Downloads/TamaBox-v4-time/internal/storage/s3.go": "C:/Users/TAMAKY~1/AppData/Local/Temp/s3_stub.go"}}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# TamaBox Cloudflare Tunnel 部署安全自检脚本
|
||||||
|
#
|
||||||
|
# 架构前提:
|
||||||
|
# 访客 → Cloudflare 边缘(a.b.com 自定义主机名证书 / a.a.com 主域)
|
||||||
|
# → cloudflared Tunnel(源站仅出站连接)→ 127.0.0.1:5877 (TamaBox)
|
||||||
|
#
|
||||||
|
# 用法:
|
||||||
|
# 第一部分(在源站服务器上执行): ./security-selfcheck.sh local
|
||||||
|
# 第二部分(在你自己的电脑上执行):SERVER_IP=源站公网IP CF_DOMAIN=a.a.com CUSTOM_DOMAIN=a.b.com ./security-selfcheck.sh remote
|
||||||
|
# 两部分都跑: ./security-selfcheck.sh all
|
||||||
|
#
|
||||||
|
set -u
|
||||||
|
|
||||||
|
MODE="${1:-all}"
|
||||||
|
SERVER_IP="${SERVER_IP:-}"
|
||||||
|
CF_DOMAIN="${CF_DOMAIN:-a.a.com}"
|
||||||
|
CUSTOM_DOMAIN="${CUSTOM_DOMAIN:-a.b.com}"
|
||||||
|
APP_PORT="${APP_PORT:-5877}"
|
||||||
|
|
||||||
|
section() { printf "\n========== %s ==========\n" "$1"; }
|
||||||
|
ok() { echo "[✓] $1"; }
|
||||||
|
warn() { echo "[!] $1"; }
|
||||||
|
bad() { echo "[✗] $1"; }
|
||||||
|
|
||||||
|
# 用 bash /dev/tcp 探测 TCP 端口是否可达(3 秒超时)
|
||||||
|
port_open() {
|
||||||
|
(timeout 3 bash -c "echo > /dev/tcp/$1/$2") 2>/dev/null
|
||||||
|
}
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------
|
||||||
|
# 第一部分:源站本地检查
|
||||||
|
# ----------------------------------------------------------------
|
||||||
|
local_checks() {
|
||||||
|
section "1. 应用与数据库端口绑定检查(核心)"
|
||||||
|
|
||||||
|
BIND=$(ss -tlnp 2>/dev/null | grep ":${APP_PORT} " || true)
|
||||||
|
echo "$BIND"
|
||||||
|
if echo "$BIND" | grep -qE "127\.0\.0\.1:${APP_PORT}|\[::1\]:${APP_PORT}"; then
|
||||||
|
ok "TamaBox 只绑定在 127.0.0.1:${APP_PORT},外部无法直连(正确)"
|
||||||
|
elif [ -z "$BIND" ]; then
|
||||||
|
warn "端口 ${APP_PORT} 未监听——确认 TamaBox 是否在运行"
|
||||||
|
else
|
||||||
|
bad "TamaBox 绑定在 0.0.0.0/*:${APP_PORT}(监听所有网卡)!"
|
||||||
|
echo " 修复:conf/app.ini [server] 段设置 listen = 127.0.0.1:${APP_PORT} 并重启"
|
||||||
|
fi
|
||||||
|
|
||||||
|
section "2. PostgreSQL / Redis 是否暴露公网"
|
||||||
|
for p in 5432 6379; do
|
||||||
|
BIND=$(ss -tlnp 2>/dev/null | grep ":${p} " || true)
|
||||||
|
if echo "$BIND" | grep -qE "0\.0\.0\.0:${p}|\*:${p}"; then
|
||||||
|
bad "端口 ${p} 绑定在所有网卡!必须改为 127.0.0.1 或加防火墙(云数据库直接暴露=高危)"
|
||||||
|
else
|
||||||
|
ok "端口 ${p} 未对外监听(${BIND:-未运行})"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
section "3. cloudflared 状态与 ingress 配置"
|
||||||
|
if systemctl is-active --quiet cloudflared 2>/dev/null || pgrep -x cloudflared >/dev/null 2>&1; then
|
||||||
|
ok "cloudflared 正在运行"
|
||||||
|
else
|
||||||
|
bad "cloudflared 未运行——Tunnel 断开,所有域名不可达"
|
||||||
|
fi
|
||||||
|
CFG=""
|
||||||
|
for f in /etc/cloudflared/config.yml /root/.cloudflared/config.yml /home/*/.cloudflared/config.yml; do
|
||||||
|
[ -f "$f" ] && CFG="$f" && break
|
||||||
|
done
|
||||||
|
if [ -n "$CFG" ]; then
|
||||||
|
echo "配置文件:$CFG"
|
||||||
|
grep -nE "hostname|service|originRequest" "$CFG" || true
|
||||||
|
if grep -qE "service:\s*http://127\.0\.0\.1:${APP_PORT}|localhost:${APP_PORT}" "$CFG"; then
|
||||||
|
ok "ingress service 指向 127.0.0.1:${APP_PORT}(正确)"
|
||||||
|
else
|
||||||
|
warn "未在 config.yml 中找到指向 127.0.0.1:${APP_PORT} 的 service,请人工核对 ingress 规则"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
warn "未找到 config.yml(若用 token 模式 + 远端 ingress,请到 Cloudflare 面板核对 Public Hostname 的 service 地址)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
section "4. 本地请求验证(模拟 cloudflared 的视角)"
|
||||||
|
RESP=$(curl -s -m 5 -o /dev/null -w "%{http_code}" "http://127.0.0.1:${APP_PORT}/" || true)
|
||||||
|
if [ "$RESP" = "200" ] || [ "$RESP" = "302" ] || [ "$RESP" = "303" ]; then
|
||||||
|
ok "本地 HTTP 请求返回 $RESP,应用正常"
|
||||||
|
else
|
||||||
|
warn "本地请求返回 ${RESP:-无响应},请人工确认"
|
||||||
|
fi
|
||||||
|
|
||||||
|
section "5. 防火墙状态(仅供参考)"
|
||||||
|
if command -v ufw >/dev/null 2>&1; then
|
||||||
|
ufw status verbose 2>/dev/null | head -15 || true
|
||||||
|
elif command -v firewall-cmd >/dev/null 2>&1; then
|
||||||
|
firewall-cmd --list-all 2>/dev/null || true
|
||||||
|
else
|
||||||
|
iptables -L INPUT -n --line-numbers 2>/dev/null | head -15 || true
|
||||||
|
fi
|
||||||
|
warn "请人工确认:除 SSH(22) 外,80/443/5877 等端口不应有公网入站放行规则"
|
||||||
|
}
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------
|
||||||
|
# 第二部分:外部探测(在自己的电脑上执行)
|
||||||
|
# ----------------------------------------------------------------
|
||||||
|
remote_checks() {
|
||||||
|
if [ -z "$SERVER_IP" ]; then
|
||||||
|
bad "未设置 SERVER_IP 环境变量,跳过直连探测(用法见文件头注释)"
|
||||||
|
else
|
||||||
|
section "6. 直连源站 IP 探测(核心:防 IP+端口直连)"
|
||||||
|
for p in "$APP_PORT" 80 443 5432 6379; do
|
||||||
|
if port_open "$SERVER_IP" "$p"; then
|
||||||
|
case "$p" in
|
||||||
|
22) warn "端口 22 开放(SSH,正常,但建议改密钥登录/限来源 IP)" ;;
|
||||||
|
*) bad "端口 ${p} 从公网可达!存在被直连/攻击面,去服务器防火墙封掉它" ;;
|
||||||
|
esac
|
||||||
|
else
|
||||||
|
ok "端口 ${p} 从公网不可达"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
section "7. 经域名的正常访问验证"
|
||||||
|
for d in "$CF_DOMAIN" "$CUSTOM_DOMAIN"; do
|
||||||
|
CODE=$(curl -s -m 10 -o /dev/null -w "%{http_code}" "https://${d}/" || true)
|
||||||
|
RAY=$(curl -sI -m 10 "https://${d}/" | grep -i "^cf-ray:" || true)
|
||||||
|
if [ -n "$RAY" ]; then
|
||||||
|
ok "https://${d}/ 返回 ${CODE:-?},且带 ${RAY%%$'\r'} → 确认流量经过 Cloudflare 边缘"
|
||||||
|
elif [ "$CODE" = "200" ] || [ "$CODE" = "302" ] || [ "$CODE" = "303" ]; then
|
||||||
|
warn "https://${d}/ 返回 ${CODE} 但没有 cf-ray 头 → 流量可能没走 Cloudflare(自定义主机名未生效?)"
|
||||||
|
else
|
||||||
|
bad "https://${d}/ 不可达(${CODE:-无响应})"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
section "8. 伪造头穿透测试(验证 Cloudflare 会重写伪造头)"
|
||||||
|
# 若伪造头被 CF 覆盖,应用侧记录的仍是真实 IP;此测试主要用于演示,无法从响应直接观察,
|
||||||
|
# 需配合 TamaBox 侧日志/封禁记录核对(见第 9 项说明)。
|
||||||
|
curl -s -m 10 -o /dev/null \
|
||||||
|
-H "CF-Connecting-IP: 203.0.113.66" \
|
||||||
|
-H "X-Forwarded-For: 203.0.113.66" \
|
||||||
|
"https://${CUSTOM_DOMAIN}/" || true
|
||||||
|
ok "已发送带伪造 CF-Connecting-IP 的请求(CF 边缘会将其重写为你的真实 IP)"
|
||||||
|
|
||||||
|
section "9. HTTP 明文与 HSTS 检查"
|
||||||
|
LOC=$(curl -sI -m 10 "http://${CUSTOM_DOMAIN}/" | grep -iE "^(HTTP|location):" | tr -d '\r')
|
||||||
|
echo "$LOC"
|
||||||
|
HSTS=$(curl -sI -m 10 "https://${CUSTOM_DOMAIN}/" | grep -i "strict-transport-security" | tr -d '\r')
|
||||||
|
if [ -n "$HSTS" ]; then ok "$HSTS"; else warn "未返回 HSTS 头(若浏览器直访 http 可能被中间人,建议确认 securityHeaders 已生效)"; fi
|
||||||
|
}
|
||||||
|
|
||||||
|
case "$MODE" in
|
||||||
|
local) local_checks ;;
|
||||||
|
remote) remote_checks ;;
|
||||||
|
all) local_checks; remote_checks ;;
|
||||||
|
*) echo "用法: $0 {local|remote|all}"; exit 1 ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
section "自检完成"
|
||||||
|
echo "逐项核对上面的 [✓]/[!]/[✗],所有 [✗] 都需要修复后再跑一遍。"
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
function secondToDate(second) {
|
||||||
|
if (!second) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
var time = new Array(0, 0, 0, 0, 0);
|
||||||
|
if (second >= 365 * 24 * 3600) {
|
||||||
|
time[0] = parseInt(second / (365 * 24 * 3600));
|
||||||
|
second %= 365 * 24 * 3600;
|
||||||
|
}
|
||||||
|
if (second >= 24 * 3600) {
|
||||||
|
time[1] = parseInt(second / (24 * 3600));
|
||||||
|
second %= 24 * 3600;
|
||||||
|
}
|
||||||
|
if (second >= 3600) {
|
||||||
|
time[2] = parseInt(second / 3600);
|
||||||
|
second %= 3600;
|
||||||
|
}
|
||||||
|
if (second >= 60) {
|
||||||
|
time[3] = parseInt(second / 60);
|
||||||
|
second %= 60;
|
||||||
|
}
|
||||||
|
if (second > 0) {
|
||||||
|
time[4] = second;
|
||||||
|
}
|
||||||
|
return time;
|
||||||
|
}
|
||||||
|
function setTime() {
|
||||||
|
var create_time = Math.round(new Date(Date.UTC(2023, 06, 01, 18, 15, 43)).getTime() / 1000);
|
||||||
|
var timestamp = Math.round((new Date().getTime() + 8 * 60 * 60 * 1000) / 1000);
|
||||||
|
currentTime = secondToDate((timestamp - create_time));
|
||||||
|
currentTimeHtml = currentTime[0] + '年 ' + currentTime[1] + '天 ' + currentTime[2] + '时 ' + currentTime[3] + '分 ' + currentTime[4] + '秒 ';
|
||||||
|
document.getElementById("box_runtime").innerHTML = currentTimeHtml;
|
||||||
|
var boxRuntime = document.getElementById("box_runtime");
|
||||||
|
if (boxRuntime) {
|
||||||
|
boxRuntime.innerHTML = currentTimeHtml;
|
||||||
|
} else {
|
||||||
|
console.error("Element with id 'box_runtime' not found!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 确保 DOM 加载完成后执行
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
setInterval(setTime, 1000);
|
||||||
|
});
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
// webpstub(package webp)是 chai2010/webp 的本地编译桩:仅用于在缺少 libwebp 的
|
||||||
|
// Windows 沙箱中通过 `go build -overlay` 对依赖 internal/storage 的包做完整
|
||||||
|
// 类型检查。API 只覆盖项目实际用到的 Encode/Options。
|
||||||
|
package webp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"image"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Options 与 github.com/chai2010/webp 的 Options 字段保持兼容(项目仅用 Quality)。
|
||||||
|
type Options struct {
|
||||||
|
Lossless bool
|
||||||
|
Quality float32
|
||||||
|
}
|
||||||
|
|
||||||
|
// Encode 是 webp.Encode 的签名兼容桩(类型检查期间不会被真正调用)。
|
||||||
|
func Encode(w io.Writer, m image.Image, o *Options) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
module github.com/tamakyi/TamaBox
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
replace golang.org/x/image => golang.org/x/image v0.13.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/aliyun/alibaba-cloud-sdk-go v1.62.26
|
||||||
|
github.com/aliyun/aliyun-oss-go-sdk v2.2.4+incompatible
|
||||||
|
github.com/aws/aws-sdk-go-v2 v1.24.0
|
||||||
|
github.com/aws/aws-sdk-go-v2/config v1.26.1
|
||||||
|
github.com/aws/aws-sdk-go-v2/credentials v1.16.12
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/s3 v1.47.5
|
||||||
|
github.com/chai2010/webp v1.4.0
|
||||||
|
github.com/disintegration/imaging v1.6.2
|
||||||
|
github.com/flamego/cache v1.1.0
|
||||||
|
github.com/flamego/csrf v1.3.0
|
||||||
|
github.com/flamego/flamego v1.9.4
|
||||||
|
github.com/flamego/recaptcha v1.2.0
|
||||||
|
github.com/flamego/session v1.6.5
|
||||||
|
github.com/flamego/template v1.2.2
|
||||||
|
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0
|
||||||
|
github.com/pkg/errors v0.9.1
|
||||||
|
github.com/qiniu/go-sdk/v7 v7.13.0
|
||||||
|
github.com/rs/xid v1.2.1
|
||||||
|
github.com/russross/blackfriday/v2 v2.1.0
|
||||||
|
github.com/samber/lo v1.34.0
|
||||||
|
github.com/sirupsen/logrus v1.9.3
|
||||||
|
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
||||||
|
github.com/stretchr/testify v1.9.0
|
||||||
|
github.com/tdewolff/minify/v2 v2.12.4
|
||||||
|
github.com/thanhpk/randstr v1.0.4
|
||||||
|
github.com/unknwon/com v1.0.1
|
||||||
|
github.com/uptrace/opentelemetry-go-extra/otelgorm v0.1.16
|
||||||
|
github.com/uptrace/opentelemetry-go-extra/otellogrus v0.1.16
|
||||||
|
github.com/uptrace/uptrace-go v1.9.0
|
||||||
|
github.com/urfave/cli/v2 v2.26.0
|
||||||
|
github.com/wuhan005/gadget v0.0.0-20221206194113-7619e407f1a0
|
||||||
|
github.com/wuhan005/govalid v0.0.0-20230216091828-820aa255fd21
|
||||||
|
github.com/xuri/excelize/v2 v2.6.0
|
||||||
|
go.opentelemetry.io/otel v1.10.0
|
||||||
|
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.9.0
|
||||||
|
go.opentelemetry.io/otel/sdk v1.9.0
|
||||||
|
go.opentelemetry.io/otel/trace v1.10.0
|
||||||
|
golang.org/x/crypto v0.54.0
|
||||||
|
golang.org/x/net v0.56.0
|
||||||
|
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
|
||||||
|
gopkg.in/ini.v1 v1.66.2
|
||||||
|
gorm.io/datatypes v1.0.7
|
||||||
|
gorm.io/driver/mysql v1.3.6
|
||||||
|
gorm.io/driver/postgres v1.4.5
|
||||||
|
gorm.io/gorm v1.24.1-0.20221019064659-5dd2bb482755
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
filippo.io/edwards25519 v1.1.0 // indirect
|
||||||
|
github.com/alecthomas/participle/v2 v2.0.0 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.5.4 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.14.10 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/configsources v1.2.9 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.5.9 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/ini v1.7.2 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/v4a v1.2.9 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.10.4 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.2.9 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.10.9 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.16.9 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sso v1.18.5 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.21.5 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sts v1.26.5 // indirect
|
||||||
|
github.com/aws/smithy-go v1.19.0 // indirect
|
||||||
|
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
|
||||||
|
github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f // indirect
|
||||||
|
github.com/cenkalti/backoff/v4 v4.1.3 // indirect
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||||
|
github.com/charmbracelet/lipgloss v0.7.1 // indirect
|
||||||
|
github.com/charmbracelet/log v0.2.3 // indirect
|
||||||
|
github.com/cpuguy83/go-md2man/v2 v2.0.3 // indirect
|
||||||
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||||
|
github.com/go-logfmt/logfmt v0.6.0 // indirect
|
||||||
|
github.com/go-logr/logr v1.3.0 // indirect
|
||||||
|
github.com/go-logr/stdr v1.2.2 // indirect
|
||||||
|
github.com/go-redis/redis/v8 v8.11.5 // indirect
|
||||||
|
github.com/go-sql-driver/mysql v1.8.1 // indirect
|
||||||
|
github.com/golang/protobuf v1.5.3 // indirect
|
||||||
|
github.com/google/go-cmp v0.6.0 // indirect
|
||||||
|
github.com/gopherjs/gopherjs v0.0.0-20190430165422-3e4dfb77656c // indirect
|
||||||
|
github.com/grpc-ecosystem/grpc-gateway/v2 v2.11.3 // indirect
|
||||||
|
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
|
||||||
|
github.com/jackc/pgconn v1.13.0 // indirect
|
||||||
|
github.com/jackc/pgio v1.0.0 // indirect
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
|
github.com/jackc/pgproto3/v2 v2.3.1 // indirect
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||||
|
github.com/jackc/pgtype v1.12.0 // indirect
|
||||||
|
github.com/jackc/pgx/v4 v4.17.2 // indirect
|
||||||
|
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||||
|
github.com/jinzhu/now v1.1.5 // indirect
|
||||||
|
github.com/jmespath/go-jmespath v0.4.0 // indirect
|
||||||
|
github.com/json-iterator/go v1.1.8 // indirect
|
||||||
|
github.com/kr/pretty v0.3.1 // indirect
|
||||||
|
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.18 // indirect
|
||||||
|
github.com/mattn/go-runewidth v0.0.14 // indirect
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||||
|
github.com/modern-go/reflect2 v1.0.1 // indirect
|
||||||
|
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
|
||||||
|
github.com/muesli/reflow v0.3.0 // indirect
|
||||||
|
github.com/muesli/termenv v0.15.2 // indirect
|
||||||
|
github.com/onsi/gomega v1.29.0 // indirect
|
||||||
|
github.com/opentracing/opentracing-go v1.2.1-0.20220228012449-10b1cf09e00b // indirect
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
|
github.com/redis/go-redis/v9 v9.5.1 // indirect
|
||||||
|
github.com/richardlehane/mscfb v1.0.4 // indirect
|
||||||
|
github.com/richardlehane/msoleps v1.0.1 // indirect
|
||||||
|
github.com/rivo/uniseg v0.2.0 // indirect
|
||||||
|
github.com/smartystreets/assertions v1.0.1 // indirect
|
||||||
|
github.com/tdewolff/parse/v2 v2.6.4 // indirect
|
||||||
|
github.com/uptrace/opentelemetry-go-extra/otelsql v0.1.16 // indirect
|
||||||
|
github.com/uptrace/opentelemetry-go-extra/otelutil v0.1.16 // indirect
|
||||||
|
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
|
||||||
|
github.com/xuri/efp v0.0.0-20220407160117-ad0f7a785be8 // indirect
|
||||||
|
github.com/xuri/nfp v0.0.0-20220409054826-5e722a1d9e22 // indirect
|
||||||
|
go.opentelemetry.io/contrib/instrumentation/runtime v0.34.0 // indirect
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.9.0 // indirect
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlpmetric v0.31.0 // indirect
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v0.31.0 // indirect
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.9.0 // indirect
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.9.0 // indirect
|
||||||
|
go.opentelemetry.io/otel/metric v0.32.1 // indirect
|
||||||
|
go.opentelemetry.io/otel/sdk/metric v0.31.0 // indirect
|
||||||
|
go.opentelemetry.io/proto/otlp v0.19.0 // indirect
|
||||||
|
golang.org/x/exp v0.0.0-20231206192017-f3f8817b8deb // indirect
|
||||||
|
golang.org/x/image v0.13.0 // indirect
|
||||||
|
golang.org/x/sys v0.47.0 // indirect
|
||||||
|
golang.org/x/text v0.40.0 // indirect
|
||||||
|
golang.org/x/time v0.0.0-20191024005414-555d28b269f0 // indirect
|
||||||
|
google.golang.org/genproto v0.0.0-20231120223509-83a465c0220f // indirect
|
||||||
|
google.golang.org/genproto/googleapis/api v0.0.0-20231127180814-3a041ad873d4 // indirect
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20231127180814-3a041ad873d4 // indirect
|
||||||
|
google.golang.org/grpc v1.59.0 // indirect
|
||||||
|
google.golang.org/protobuf v1.33.0 // indirect
|
||||||
|
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
|
)
|
||||||
Vendored
+87
@@ -0,0 +1,87 @@
|
|||||||
|
// 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 cache 提供进程内、并发安全的短 TTL 缓存。
|
||||||
|
//
|
||||||
|
// 适用场景:结果聚合统计等"非强一致"数据,用短 TTL 换取数据库实时重算压力的显著降低
|
||||||
|
// (投票结果页、探索页热门投票等)。需注意:进程内存缓存在多实例横向扩容时不会共享,
|
||||||
|
// 因此仅用于可接受短暂陈旧的数据;强一致数据请勿使用本缓存。
|
||||||
|
package cache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ttlEntry struct {
|
||||||
|
value interface{}
|
||||||
|
expiresAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// TTLCache 并发安全的带 TTL 进程内缓存。
|
||||||
|
type TTLCache struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
items map[string]ttlEntry
|
||||||
|
maxItems int
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewTTLCache 创建缓存实例。maxItems<=0 时使用默认容量 256;达到容量上限时,
|
||||||
|
// 先淘汰过期项,若仍满则整表清空(避免内存无限增长,短 TTL 下过期项通常已占多数)。
|
||||||
|
func NewTTLCache(maxItems int) *TTLCache {
|
||||||
|
if maxItems <= 0 {
|
||||||
|
maxItems = 256
|
||||||
|
}
|
||||||
|
return &TTLCache{
|
||||||
|
items: make(map[string]ttlEntry, maxItems),
|
||||||
|
maxItems: maxItems,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get 读取缓存;命中且未过期返回值,否则返回 (nil, false)。
|
||||||
|
func (c *TTLCache) Get(key string) (interface{}, bool) {
|
||||||
|
c.mu.RLock()
|
||||||
|
e, ok := c.items[key]
|
||||||
|
c.mu.RUnlock()
|
||||||
|
if !ok {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
if time.Now().After(e.expiresAt) {
|
||||||
|
c.mu.Lock()
|
||||||
|
// 双重检查,避免并发重复删除(无影响,仅兜底)
|
||||||
|
if cur, still := c.items[key]; still && time.Now().After(cur.expiresAt) {
|
||||||
|
delete(c.items, key)
|
||||||
|
}
|
||||||
|
c.mu.Unlock()
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
return e.value, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set 写入缓存并设定过期时间。
|
||||||
|
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, v := range c.items {
|
||||||
|
if now.After(v.expiresAt) {
|
||||||
|
delete(c.items, k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 仍满(多为短 TTL 下瞬时高频写入):整表重建,保证写入成功且不 OOM
|
||||||
|
if len(c.items) >= c.maxItems {
|
||||||
|
c.items = make(map[string]ttlEntry, c.maxItems)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.items[key] = ttlEntry{value: value, expiresAt: time.Now().Add(ttl)}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete 删除指定键的缓存项;键不存在时静默返回。
|
||||||
|
// 用于写穿式失效:数据变更(如新增投票提交)后立即清除对应缓存,避免结果页短暂陈旧。
|
||||||
|
func (c *TTLCache) Delete(key string) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
delete(c.items, key)
|
||||||
|
}
|
||||||
Vendored
+61
@@ -0,0 +1,61 @@
|
|||||||
|
// 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 cache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTTLCacheBasic(t *testing.T) {
|
||||||
|
c := NewTTLCache(8)
|
||||||
|
if _, ok := c.Get("missing"); ok {
|
||||||
|
t.Fatal("expected miss for empty cache")
|
||||||
|
}
|
||||||
|
c.Set("k", "v", time.Minute)
|
||||||
|
v, ok := c.Get("k")
|
||||||
|
if !ok || v.(string) != "v" {
|
||||||
|
t.Fatalf("expected hit with v, got %v %v", v, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTTLCacheExpiry(t *testing.T) {
|
||||||
|
c := NewTTLCache(8)
|
||||||
|
c.Set("k", "v", time.Nanosecond)
|
||||||
|
time.Sleep(2 * time.Millisecond)
|
||||||
|
if _, ok := c.Get("k"); ok {
|
||||||
|
t.Fatal("expected expired entry to miss")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTTLCacheCapacityEviction(t *testing.T) {
|
||||||
|
c := NewTTLCache(4)
|
||||||
|
for i := 0; i < 100; i++ {
|
||||||
|
c.Set(string(rune('a'+i%26))+string(rune('0'+i%10)), i, time.Minute)
|
||||||
|
}
|
||||||
|
// 不 panic 且仍可读
|
||||||
|
if _, ok := c.Get("a0"); ok {
|
||||||
|
// 命中与否均可,关键是内存不失控且无 panic
|
||||||
|
_ = ok
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTTLCacheConcurrent(t *testing.T) {
|
||||||
|
c := NewTTLCache(16)
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
for g := 0; g < 20; g++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go func(n int) {
|
||||||
|
defer wg.Done()
|
||||||
|
for i := 0; i < 200; i++ {
|
||||||
|
key := string(rune('a' + (n+i)%26))
|
||||||
|
c.Set(key, n, time.Minute)
|
||||||
|
c.Get(key)
|
||||||
|
}
|
||||||
|
}(g)
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
}
|
||||||
@@ -0,0 +1,273 @@
|
|||||||
|
// Copyright 2024 TamaBox. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package captcha
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/subtle"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"math/big"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/flamego/flamego"
|
||||||
|
"github.com/flamego/recaptcha"
|
||||||
|
"github.com/flamego/session"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/conf"
|
||||||
|
"github.com/tamakyi/TamaBox/internal/i18n"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// Session key prefix for storing math captcha answers
|
||||||
|
sessionKeyPrefix = "math_captcha_"
|
||||||
|
// TTL for each captcha in session
|
||||||
|
captchaTTL = 5 * time.Minute
|
||||||
|
// maxCaptchaAttempts 同一条验证码被尝试(含模态框预校验)的最大次数,
|
||||||
|
// 超过即销毁该验证码,迫使刷新,防止对答案做无限轮询爆破。
|
||||||
|
maxCaptchaAttempts = 5
|
||||||
|
)
|
||||||
|
|
||||||
|
// MathProblem represents an arithmetic captcha problem.
|
||||||
|
type MathProblem struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Question string `json:"question"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// storedAnswer holds the expected answer and creation time.
|
||||||
|
type StoredAnswer struct {
|
||||||
|
Answer int
|
||||||
|
CreatedAt time.Time
|
||||||
|
// Attempts 累计校验尝试次数(含模态框预校验),用于达到上限后销毁验证码。
|
||||||
|
Attempts int
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateMath creates a new arithmetic captcha problem and stores the answer in session.
|
||||||
|
func GenerateMath(s session.Session) (*MathProblem, error) {
|
||||||
|
// Generate random operands
|
||||||
|
op1, err := rand.Int(rand.Reader, big.NewInt(90))
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "generate operand 1")
|
||||||
|
}
|
||||||
|
op2, err := rand.Int(rand.Reader, big.NewInt(90))
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "generate operand 2")
|
||||||
|
}
|
||||||
|
a := int(op1.Int64()) + 1 // 1-90
|
||||||
|
b := int(op2.Int64()) + 1 // 1-90
|
||||||
|
|
||||||
|
// Pick a random operator (+, -, *)
|
||||||
|
opIdx, err := rand.Int(rand.Reader, big.NewInt(3))
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "generate operator")
|
||||||
|
}
|
||||||
|
var operator string
|
||||||
|
var answer int
|
||||||
|
switch opIdx.Int64() {
|
||||||
|
case 0:
|
||||||
|
operator = "+"
|
||||||
|
answer = a + b
|
||||||
|
case 1:
|
||||||
|
operator = "-"
|
||||||
|
// Ensure non-negative result
|
||||||
|
if a < b {
|
||||||
|
a, b = b, a
|
||||||
|
}
|
||||||
|
answer = a - b
|
||||||
|
default:
|
||||||
|
operator = "×"
|
||||||
|
// Keep numbers small for multiplication
|
||||||
|
a = a%10 + 1
|
||||||
|
b = b%10 + 1
|
||||||
|
answer = a * b
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成唯一 ID
|
||||||
|
idBytes := make([]byte, 8)
|
||||||
|
if _, err := rand.Read(idBytes); err != nil {
|
||||||
|
return nil, errors.Wrap(err, "generate captcha id")
|
||||||
|
}
|
||||||
|
id := hex.EncodeToString(idBytes)
|
||||||
|
|
||||||
|
// 清理策略说明:flamego session 接口不支持遍历,无法主动清理过期条目。
|
||||||
|
// 泄漏可控:验证码一次性消费(VerifyMath 校验后立即删除),
|
||||||
|
// 且每个用户同一时刻只生成 1 个新 key;session 本身过期后存储层整体清理。
|
||||||
|
|
||||||
|
// Store answer in session
|
||||||
|
key := sessionKeyPrefix + id
|
||||||
|
s.Set(key, StoredAnswer{
|
||||||
|
Answer: answer,
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
})
|
||||||
|
|
||||||
|
question := fmt.Sprintf("%d %s %d =", a, operator, b)
|
||||||
|
return &MathProblem{
|
||||||
|
ID: id,
|
||||||
|
Question: question,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// VerifyMath checks if the given answer matches the stored captcha.
|
||||||
|
// Returns (true, nil) if correct, (false, nil) if incorrect, (false, error) on error.
|
||||||
|
func VerifyMath(s session.Session, token string, lang string) (bool, error) {
|
||||||
|
if token == "" {
|
||||||
|
return false, errors.New(i18n.T(lang, "captcha.errEmpty"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Token format: "captcha_id:answer"
|
||||||
|
parts := strings.SplitN(token, ":", 2)
|
||||||
|
if len(parts) != 2 {
|
||||||
|
return false, errors.New(i18n.T(lang, "captcha.errFormat"))
|
||||||
|
}
|
||||||
|
|
||||||
|
id := parts[0]
|
||||||
|
answerStr := parts[1]
|
||||||
|
|
||||||
|
answer, err := strconv.Atoi(strings.TrimSpace(answerStr))
|
||||||
|
if err != nil {
|
||||||
|
return false, errors.New(i18n.T(lang, "captcha.errAnswerFormat"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retrieve stored answer
|
||||||
|
key := sessionKeyPrefix + id
|
||||||
|
stored, ok := s.Get(key).(StoredAnswer)
|
||||||
|
if !ok {
|
||||||
|
return false, errors.New(i18n.T(lang, "captcha.errExpired"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check expiry
|
||||||
|
if time.Since(stored.CreatedAt) > captchaTTL {
|
||||||
|
s.Delete(key)
|
||||||
|
return false, errors.New(i18n.T(lang, "captcha.errExpired"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete after verification attempt (one-time use)
|
||||||
|
s.Delete(key)
|
||||||
|
|
||||||
|
// 常量时间比较,避免答案比对产生可观测的时序侧信道。
|
||||||
|
if subtle.ConstantTimeCompare([]byte(strconv.Itoa(answer)), []byte(strconv.Itoa(stored.Answer))) != 1 {
|
||||||
|
return false, errors.New(i18n.T(lang, "captcha.errAnswerWrong"))
|
||||||
|
}
|
||||||
|
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// VerifyOnly checks if the answer is correct WITHOUT consuming the captcha.
|
||||||
|
// This is used by the modal to validate before actually submitting the form.
|
||||||
|
// 同一验证码的答案预校验次数计入 Attempts,达到上限即销毁,防止脚本无限轮询爆破。
|
||||||
|
func VerifyOnly(s session.Session, id string, answer int) bool {
|
||||||
|
key := sessionKeyPrefix + id
|
||||||
|
stored, ok := s.Get(key).(StoredAnswer)
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if time.Since(stored.CreatedAt) > captchaTTL {
|
||||||
|
s.Delete(key)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// 尝试次数限制:超过上限即销毁,迫使刷新。
|
||||||
|
stored.Attempts++
|
||||||
|
if stored.Attempts > maxCaptchaAttempts {
|
||||||
|
s.Delete(key)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
s.Set(key, stored)
|
||||||
|
|
||||||
|
// 常量时间比较,避免答案比对产生可观测的时序侧信道。
|
||||||
|
return subtle.ConstantTimeCompare([]byte(strconv.Itoa(answer)), []byte(strconv.Itoa(stored.Answer))) == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// sessionLang 从会话读取匿名用户显式选择的语言(与 Contexter 一致,语言偏好现托管于
|
||||||
|
// session 而非独立 lang cookie,避免被 session 中间件的 Set-Cookie 覆盖);未设置时回退默认。
|
||||||
|
func sessionLang(s session.Session) string {
|
||||||
|
if v := s.Get("lang"); v != nil {
|
||||||
|
if str, ok := v.(string); ok && str != "" {
|
||||||
|
return i18n.Resolve(str)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return i18n.Default
|
||||||
|
}
|
||||||
|
|
||||||
|
// VerifyHandler is an HTTP handler that checks a captcha answer without consuming it.
|
||||||
|
// Used by the modal to validate before form submission.
|
||||||
|
func VerifyHandler(ctx flamego.Context, s session.Session) {
|
||||||
|
lang := sessionLang(s)
|
||||||
|
var req struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Answer int `json:"answer"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(ctx.Request().Request.Body).Decode(&req); err != nil {
|
||||||
|
ctx.ResponseWriter().WriteHeader(http.StatusBadRequest)
|
||||||
|
_ = json.NewEncoder(ctx.ResponseWriter()).Encode(map[string]interface{}{
|
||||||
|
"code": 40000,
|
||||||
|
"message": i18n.T(lang, "captcha.json.badRequest"),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.ID == "" {
|
||||||
|
ctx.ResponseWriter().WriteHeader(http.StatusBadRequest)
|
||||||
|
_ = json.NewEncoder(ctx.ResponseWriter()).Encode(map[string]interface{}{
|
||||||
|
"code": 40000,
|
||||||
|
"message": i18n.T(lang, "captcha.json.idRequired"),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
correct := VerifyOnly(s, req.ID, req.Answer)
|
||||||
|
|
||||||
|
ctx.ResponseWriter().Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(ctx.ResponseWriter()).Encode(map[string]interface{}{
|
||||||
|
"code": 0,
|
||||||
|
"correct": correct,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateHandler is an HTTP handler that generates a math captcha and returns it as JSON.
|
||||||
|
func GenerateHandler(ctx flamego.Context, s session.Session) {
|
||||||
|
lang := sessionLang(s)
|
||||||
|
problem, err := GenerateMath(s)
|
||||||
|
if err != nil {
|
||||||
|
ctx.ResponseWriter().WriteHeader(http.StatusInternalServerError)
|
||||||
|
_ = json.NewEncoder(ctx.ResponseWriter()).Encode(map[string]interface{}{
|
||||||
|
"code": 50000,
|
||||||
|
"message": i18n.T(lang, "captcha.json.genFailed"),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.ResponseWriter().Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(ctx.ResponseWriter()).Encode(map[string]interface{}{
|
||||||
|
"code": 0,
|
||||||
|
"data": problem,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify is a unified captcha verification function.
|
||||||
|
// It automatically chooses between recaptcha/turnstile and math captcha based on config.
|
||||||
|
// Returns (true, nil) if verification passes, (false, nil) if it fails, (false, error) on error.
|
||||||
|
func Verify(token string, remoteIP string, s session.Session, r recaptcha.RecaptchaV3, lang string) (bool, error) {
|
||||||
|
if conf.Recaptcha.CaptchaType == "math" {
|
||||||
|
return VerifyMath(s, token, lang)
|
||||||
|
}
|
||||||
|
|
||||||
|
// reCAPTCHA / Turnstile
|
||||||
|
resp, err := r.Verify(token, remoteIP)
|
||||||
|
if err != nil {
|
||||||
|
logrus.WithError(err).Error("Failed to verify recaptcha/turnstile")
|
||||||
|
return false, errors.New(i18n.T(lang, "captcha.errService"))
|
||||||
|
}
|
||||||
|
if !resp.Success {
|
||||||
|
return false, errors.New(i18n.T(lang, "captcha.error"))
|
||||||
|
}
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
// 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 cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
|
"github.com/urfave/cli/v2"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/conf"
|
||||||
|
"github.com/tamakyi/TamaBox/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Ban 封禁用户并连带清理其全部数据。
|
||||||
|
// 用法:TamaBox ban --email [email protected] 或 TamaBox ban --domain someone
|
||||||
|
var Ban = &cli.Command{
|
||||||
|
Name: "ban",
|
||||||
|
Usage: "Ban a user and clean up all their questions, follow-ups and chats",
|
||||||
|
Action: runBan,
|
||||||
|
Flags: []cli.Flag{
|
||||||
|
&cli.StringFlag{
|
||||||
|
Name: "email",
|
||||||
|
Usage: "Email of the user to ban",
|
||||||
|
},
|
||||||
|
&cli.StringFlag{
|
||||||
|
Name: "domain",
|
||||||
|
Usage: "Custom domain of the user to ban",
|
||||||
|
},
|
||||||
|
&cli.BoolFlag{
|
||||||
|
Name: "yes",
|
||||||
|
Usage: "Skip confirmation",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
func runBan(ctx *cli.Context) error {
|
||||||
|
if err := conf.Init(); err != nil {
|
||||||
|
return errors.Wrap(err, "load configuration")
|
||||||
|
}
|
||||||
|
|
||||||
|
dbType := conf.Database.Type
|
||||||
|
if dbType == "postgres" {
|
||||||
|
conf.Database.DSN = conf.PostgresDsn()
|
||||||
|
} else {
|
||||||
|
conf.Database.DSN = conf.MySQLDsn()
|
||||||
|
}
|
||||||
|
|
||||||
|
database, err := db.Init(dbType, conf.Database.DSN)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "connect to database")
|
||||||
|
}
|
||||||
|
|
||||||
|
email := ctx.String("email")
|
||||||
|
domain := ctx.String("domain")
|
||||||
|
if email == "" && domain == "" {
|
||||||
|
return errors.New("must provide --email or --domain")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 用 Unscoped 查找,支持封禁已软删除(自助停用)的账号
|
||||||
|
var user db.User
|
||||||
|
query := database.WithContext(ctx.Context).Unscoped()
|
||||||
|
if email != "" {
|
||||||
|
query = query.Where("email = ?", email)
|
||||||
|
} else {
|
||||||
|
query = query.Where("domain = ?", domain)
|
||||||
|
}
|
||||||
|
if err := query.First(&user).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "find user to ban")
|
||||||
|
}
|
||||||
|
|
||||||
|
logrus.WithFields(logrus.Fields{
|
||||||
|
"id": user.ID,
|
||||||
|
"name": user.Name,
|
||||||
|
"email": user.Email,
|
||||||
|
"domain": user.Domain,
|
||||||
|
}).Warn("准备封禁以下账号,其提问/追问/私聊将一并删除,此操作不可恢复!")
|
||||||
|
|
||||||
|
if !ctx.Bool("yes") {
|
||||||
|
logrus.Warn("输入大写 YES 确认执行封禁:")
|
||||||
|
var answer string
|
||||||
|
if _, err := fmtScan(&answer); err != nil {
|
||||||
|
return errors.Wrap(err, "read confirmation")
|
||||||
|
}
|
||||||
|
if answer != "YES" {
|
||||||
|
return errors.New("已取消")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.Users.BanUserAndCleanup(ctx.Context, user.ID); err != nil {
|
||||||
|
return errors.Wrap(err, "ban user and cleanup")
|
||||||
|
}
|
||||||
|
|
||||||
|
logrus.WithField("user_id", user.ID).Info("用户已封禁,关联数据已清理")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// fmtScan 从标准输入读取一行,便于交互确认(隔离以便测试)。
|
||||||
|
var fmtScan = func(dst *string) (int, error) {
|
||||||
|
return fmt.Fscan(os.Stdin, dst)
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
// 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 cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
|
"github.com/urfave/cli/v2"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/conf"
|
||||||
|
"github.com/tamakyi/TamaBox/internal/db"
|
||||||
|
"github.com/tamakyi/TamaBox/internal/security/censor"
|
||||||
|
)
|
||||||
|
|
||||||
|
var Censor = &cli.Command{
|
||||||
|
Name: "censor",
|
||||||
|
Usage: "Censor the questions",
|
||||||
|
Action: runCensor,
|
||||||
|
}
|
||||||
|
|
||||||
|
func runCensor(ctx *cli.Context) error {
|
||||||
|
if err := conf.Init(); err != nil {
|
||||||
|
return errors.Wrap(err, "load configuration")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !conf.Security.EnableTextCensor {
|
||||||
|
return errors.New("text censor is disabled")
|
||||||
|
}
|
||||||
|
|
||||||
|
dbType := conf.Database.Type
|
||||||
|
if dbType == "postgres" {
|
||||||
|
conf.Database.DSN = conf.PostgresDsn()
|
||||||
|
} else {
|
||||||
|
conf.Database.DSN = conf.MySQLDsn()
|
||||||
|
}
|
||||||
|
|
||||||
|
database, err := db.Init(dbType, conf.Database.DSN)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "connect to database")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check all the unprocessed questions.
|
||||||
|
var questions []db.Question
|
||||||
|
if err := database.Raw(`SELECT * FROM questions WHERE content_censor_metadata IS NULL`).Find(&questions).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "query questions")
|
||||||
|
}
|
||||||
|
|
||||||
|
logrus.WithContext(ctx.Context).WithField("count", len(questions)).Info("Found un-censor questions")
|
||||||
|
|
||||||
|
for i, question := range questions {
|
||||||
|
question := question
|
||||||
|
|
||||||
|
content := question.Content
|
||||||
|
answer := question.Answer
|
||||||
|
contentCensorResponse, err := censor.Text(ctx.Context, content)
|
||||||
|
if err != nil {
|
||||||
|
logrus.WithContext(ctx.Context).WithField("question_id", question.ID).WithError(err).Error("Failed to censor content")
|
||||||
|
} else {
|
||||||
|
// We don't want to update the `updated_at` field, so just execute the raw SQL.
|
||||||
|
if err := database.Debug().Exec(`UPDATE questions SET content_censor_metadata = ? WHERE id = ?`, contentCensorResponse.ToJSON(), question.ID).Error; err != nil {
|
||||||
|
logrus.WithContext(ctx.Context).WithField("question_id", question.ID).WithError(err).Error("Failed to update content censor metadata")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if answer != "" && question.AnswerCensorMetadata == nil {
|
||||||
|
answerCensorResponse, err := censor.Text(ctx.Context, answer)
|
||||||
|
if err != nil {
|
||||||
|
logrus.WithContext(ctx.Context).WithField("question_id", question.ID).WithError(err).Error("Failed to censor answer")
|
||||||
|
} else {
|
||||||
|
// We don't want to update the `updated_at` field, so just execute the raw SQL.
|
||||||
|
if err := database.Exec(`UPDATE questions SET answer_censor_metadata = ? WHERE id = ?`, answerCensorResponse.ToJSON(), question.ID).Error; err != nil {
|
||||||
|
logrus.WithContext(ctx.Context).WithField("question_id", question.ID).WithError(err).Error("Failed to update answer censor metadata")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if i%1000 == 0 {
|
||||||
|
logrus.WithContext(ctx.Context).WithField("count", i).Trace("Processed questions")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logrus.WithContext(ctx.Context).WithField("count", len(questions)).Info("Processed all questions")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/rs/xid"
|
||||||
|
"github.com/urfave/cli/v2"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/conf"
|
||||||
|
"github.com/tamakyi/TamaBox/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
var Uid = &cli.Command{
|
||||||
|
Name: "uid",
|
||||||
|
Usage: "Create uid for user",
|
||||||
|
Action: runUid,
|
||||||
|
}
|
||||||
|
|
||||||
|
func runUid(ctx *cli.Context) error {
|
||||||
|
if err := conf.Init(); err != nil {
|
||||||
|
return errors.Wrap(err, "load configuration")
|
||||||
|
}
|
||||||
|
|
||||||
|
dbType := conf.Database.Type
|
||||||
|
if dbType == "postgres" {
|
||||||
|
conf.Database.DSN = conf.PostgresDsn()
|
||||||
|
} else {
|
||||||
|
conf.Database.DSN = conf.MySQLDsn()
|
||||||
|
}
|
||||||
|
|
||||||
|
database, err := db.Init(dbType, conf.Database.DSN)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "connect to database")
|
||||||
|
}
|
||||||
|
|
||||||
|
var users []*db.User
|
||||||
|
if err := database.WithContext(ctx.Context).Unscoped().Find(&users).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "query users")
|
||||||
|
}
|
||||||
|
|
||||||
|
for idx, user := range users {
|
||||||
|
user := user
|
||||||
|
if user.UID != "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if idx%1000 == 0 {
|
||||||
|
fmt.Printf("Processing user %d/%d\n", idx, len(users))
|
||||||
|
}
|
||||||
|
|
||||||
|
uid := xid.NewWithTime(user.CreatedAt).String()
|
||||||
|
if err := database.WithContext(ctx.Context).Unscoped().
|
||||||
|
Model(&db.User{}).
|
||||||
|
Omit("updated_at").
|
||||||
|
Where("id = ?", user.ID).UpdateColumn("uid", uid).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "update uid")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
// 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 cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
|
"github.com/uptrace/opentelemetry-go-extra/otellogrus"
|
||||||
|
"github.com/uptrace/uptrace-go/uptrace"
|
||||||
|
"github.com/urfave/cli/v2"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/conf"
|
||||||
|
"github.com/tamakyi/TamaBox/internal/db"
|
||||||
|
"github.com/tamakyi/TamaBox/internal/route"
|
||||||
|
"github.com/tamakyi/TamaBox/internal/shared"
|
||||||
|
"github.com/tamakyi/TamaBox/internal/tracing"
|
||||||
|
)
|
||||||
|
|
||||||
|
var Web = &cli.Command{
|
||||||
|
Name: "web",
|
||||||
|
Usage: "Start web server",
|
||||||
|
Action: runWeb,
|
||||||
|
}
|
||||||
|
|
||||||
|
func runWeb(ctx *cli.Context) error {
|
||||||
|
if err := conf.Init(); err != nil {
|
||||||
|
return errors.Wrap(err, "load configuration")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解析可信代理网段(用于客户端 IP 解析,避免维护 Cloudflare 庞大 CIDR 清单)。
|
||||||
|
if err := shared.InitTrustedProxies(); err != nil {
|
||||||
|
return errors.Wrap(err, "init trusted proxies")
|
||||||
|
}
|
||||||
|
|
||||||
|
if conf.App.UptraceDSN != "" {
|
||||||
|
uptrace.ConfigureOpentelemetry(
|
||||||
|
uptrace.WithDSN(conf.App.UptraceDSN),
|
||||||
|
uptrace.WithServiceName("tamabox"),
|
||||||
|
uptrace.WithServiceVersion(conf.BuildCommit),
|
||||||
|
)
|
||||||
|
logrus.WithContext(ctx.Context).Debug("Tracing enabled.")
|
||||||
|
}
|
||||||
|
|
||||||
|
logrus.AddHook(otellogrus.NewHook(otellogrus.WithLevels(
|
||||||
|
logrus.PanicLevel,
|
||||||
|
logrus.FatalLevel,
|
||||||
|
logrus.ErrorLevel,
|
||||||
|
logrus.WarnLevel,
|
||||||
|
)))
|
||||||
|
|
||||||
|
dbType := conf.Database.Type
|
||||||
|
|
||||||
|
var dsn string
|
||||||
|
switch dbType {
|
||||||
|
case "mysql", "":
|
||||||
|
dsn = conf.MySQLDsn()
|
||||||
|
case "postgres":
|
||||||
|
dsn = conf.PostgresDsn()
|
||||||
|
default:
|
||||||
|
return errors.Errorf("unknown database type: %q", dbType)
|
||||||
|
}
|
||||||
|
conf.Database.DSN = dsn
|
||||||
|
|
||||||
|
_, err := db.Init(dbType, dsn)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "connect to database")
|
||||||
|
}
|
||||||
|
|
||||||
|
logrus.WithContext(ctx.Context).WithField("external_url", conf.App.ExternalURL).Info("Starting web server")
|
||||||
|
|
||||||
|
// 站点默认语言初始化(default_lang 配置,未配置时回退 zh-CN)
|
||||||
|
shared.App.SetLang(conf.App.DefaultLang)
|
||||||
|
|
||||||
|
r := route.New()
|
||||||
|
r.Use(tracing.Middleware("TamaBox"))
|
||||||
|
|
||||||
|
// 最外层挂载 gzip 压缩,并在 http.Server 上配置超时:
|
||||||
|
// - ReadHeaderTimeout 防止慢速客户端占用连接
|
||||||
|
// - ReadTimeout / WriteTimeout 防止读写挂死
|
||||||
|
// - IdleTimeout 复用 keep-alive 连接
|
||||||
|
// listen 留空时回退到 ":port"(监听所有网卡);Cloudflare Tunnel 部署建议设为
|
||||||
|
// "127.0.0.1:<port>",使源站端口仅对本地 cloudflared 可见,即使防火墙误配也无法被外部直连。
|
||||||
|
addr := conf.Server.Listen
|
||||||
|
if addr == "" {
|
||||||
|
addr = fmt.Sprintf(":%d", conf.Server.Port)
|
||||||
|
}
|
||||||
|
server := &http.Server{
|
||||||
|
Addr: addr,
|
||||||
|
Handler: route.GzipHandler(r),
|
||||||
|
ReadHeaderTimeout: 10 * time.Second,
|
||||||
|
ReadTimeout: 30 * time.Second,
|
||||||
|
WriteTimeout: 60 * time.Second,
|
||||||
|
IdleTimeout: 120 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
logrus.WithContext(ctx.Context).WithField("port", conf.Server.Port).Info("Listening on")
|
||||||
|
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||||
|
return errors.Wrap(err, "start http server")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
// 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
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"gopkg.in/ini.v1"
|
||||||
|
)
|
||||||
|
|
||||||
|
// File is the configuration object.
|
||||||
|
var File *ini.File
|
||||||
|
|
||||||
|
func Init() error {
|
||||||
|
configFile := os.Getenv("NEKOBOX_CONFIG_PATH")
|
||||||
|
if configFile == "" {
|
||||||
|
configFile = "conf/app.ini"
|
||||||
|
}
|
||||||
|
|
||||||
|
var err error
|
||||||
|
File, err = ini.LoadSources(ini.LoadOptions{
|
||||||
|
IgnoreInlineComment: true,
|
||||||
|
}, configFile)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "parse %q", configFile)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := File.Section("app").MapTo(&App); err != nil {
|
||||||
|
return errors.Wrap(err, "map 'server'")
|
||||||
|
}
|
||||||
|
|
||||||
|
if App.ExternalURL == "" {
|
||||||
|
return errors.New("app.external_url is required")
|
||||||
|
}
|
||||||
|
App.ExternalURL = strings.TrimRight(App.ExternalURL, "/")
|
||||||
|
|
||||||
|
if err := File.Section("security").MapTo(&Security); err != nil {
|
||||||
|
return errors.Wrap(err, "map 'security'")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := File.Section("server").MapTo(&Server); err != nil {
|
||||||
|
return errors.Wrap(err, "map 'server'")
|
||||||
|
}
|
||||||
|
|
||||||
|
// XSRFKey 为空会导致 CSRF token 以空密钥生成、可被预测,
|
||||||
|
// 使删题/置顶/拉黑/改密等所有 POST 操作的 CSRF 防护形同虚设。启动时强制校验。
|
||||||
|
if Server.XSRFKey == "" {
|
||||||
|
return errors.New("server.xsrf_key is required (used to generate CSRF tokens, must not be empty)")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Salt 为空会让密码哈希以空盐计算(HmacSha1(password, "")),
|
||||||
|
// 相同密码产生相同哈希且可被离线字典/彩虹表攻击。启动时强制校验。
|
||||||
|
if Server.Salt == "" {
|
||||||
|
return errors.New("server.salt is required (used to hash user passwords, must not be empty)")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := File.Section("database").MapTo(&Database); err != nil {
|
||||||
|
return errors.Wrap(err, "map 'database'")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := File.Section("redis").MapTo(&Redis); err != nil {
|
||||||
|
return errors.Wrap(err, "map 'redis'")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := File.Section("recaptcha").MapTo(&Recaptcha); err != nil {
|
||||||
|
return errors.Wrap(err, "map 'recaptcha'")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := File.Section("pixel").MapTo(&Pixel); err != nil {
|
||||||
|
return errors.Wrap(err, "map 'pixel'")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := File.Section("upload").MapTo(&Upload); err != nil {
|
||||||
|
return errors.Wrap(err, "map 'upload'")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := File.Section("limits").MapTo(&Limits); err != nil {
|
||||||
|
return errors.Wrap(err, "map 'limits'")
|
||||||
|
}
|
||||||
|
// ini 键留空会被 int 解析为 0;<1 的值一律回退内置默认,防止上限被静默置零。
|
||||||
|
sanitizeLimits(&Limits)
|
||||||
|
|
||||||
|
if err := File.Section("mail").MapTo(&Mail); err != nil {
|
||||||
|
return errors.Wrap(err, "map 'mail'")
|
||||||
|
}
|
||||||
|
|
||||||
|
serviceSections := File.Section("service").ChildSections()
|
||||||
|
for _, serviceSection := range serviceSections {
|
||||||
|
serviceSection := serviceSection
|
||||||
|
var backend struct {
|
||||||
|
Prefix string `ini:"prefix"`
|
||||||
|
ForwardURL string `ini:"forward_url"`
|
||||||
|
}
|
||||||
|
if err := serviceSection.MapTo(&backend); err != nil {
|
||||||
|
return errors.Wrapf(err, "map 'service.%s'", serviceSection.Name())
|
||||||
|
}
|
||||||
|
Service.Backends = append(Service.Backends, backend)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package conf
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
func MySQLDsn() string {
|
||||||
|
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
|
||||||
|
Database.User,
|
||||||
|
Database.Password,
|
||||||
|
Database.Host,
|
||||||
|
Database.Port,
|
||||||
|
Database.Name,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func PostgresDsn() string {
|
||||||
|
dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable TimeZone=Asia/Shanghai",
|
||||||
|
Database.Host,
|
||||||
|
Database.Port,
|
||||||
|
Database.User,
|
||||||
|
Database.Password,
|
||||||
|
Database.Name,
|
||||||
|
)
|
||||||
|
if Database.Schema != "" {
|
||||||
|
dsn += fmt.Sprintf(" search_path=%s", Database.Schema)
|
||||||
|
}
|
||||||
|
return dsn
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
// 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 conf
|
||||||
|
|
||||||
|
// 各项上限的内置默认值(与旧版硬编码一致)。既是未配置 [limits] 段时的兜底,
|
||||||
|
// 也是 conf.Init 后归一化(sanitizeLimits)的回退基准。
|
||||||
|
const (
|
||||||
|
defaultMaxTags = 5
|
||||||
|
defaultMaxTagLen = 5
|
||||||
|
defaultMaxBlockWords = 10
|
||||||
|
defaultMaxBlockWordLen = 10
|
||||||
|
defaultCustomAnswerLen = 200
|
||||||
|
defaultVoteOptionLen = 300
|
||||||
|
defaultQuestionContentLen = 1000
|
||||||
|
defaultAnswerContentLen = 2000
|
||||||
|
defaultFollowUpContentLen = 2000
|
||||||
|
defaultChatMessageLen = 2000
|
||||||
|
defaultChatMaxMessages = 200
|
||||||
|
defaultDailyMessageLimitMax = 999
|
||||||
|
)
|
||||||
|
|
||||||
|
// LimitsConfig 全站内容 / 数量上限([limits] 配置段)的字段集合。
|
||||||
|
//
|
||||||
|
// 过去这些上限以常量形式散落在 internal/db(MaxTags / MaxCustomTextLen 等)与
|
||||||
|
// 路由层硬编码(私聊单条 2000 字、会话条数 clamp 5~200 等)中,调整需改代码重编译,
|
||||||
|
// 且前后端、i18n 文案各自携带一份数值容易漂移。统一收口到 [limits] 段后:
|
||||||
|
// - 后端校验、模板注入、前端提示全部引用 conf.Limits 的同一份值;
|
||||||
|
// - 调整仅需修改 conf/app.ini 并重启进程,无需改代码;
|
||||||
|
// - 长度类上限统一按字符(rune / Unicode 码点)计数。
|
||||||
|
type LimitsConfig struct {
|
||||||
|
// ── 标签与屏蔽词(账号设置页)──
|
||||||
|
|
||||||
|
// 标签个数上限
|
||||||
|
MaxTags int `ini:"max_tags"`
|
||||||
|
// 单个标签最大字符数
|
||||||
|
MaxTagLen int `ini:"max_tag_len"`
|
||||||
|
// 屏蔽词个数上限
|
||||||
|
MaxBlockWords int `ini:"max_block_words"`
|
||||||
|
// 单个屏蔽词最大字符数
|
||||||
|
MaxBlockWordLen int `ini:"max_block_word_len"`
|
||||||
|
|
||||||
|
// ── 投票 ──
|
||||||
|
|
||||||
|
// 参与者填写的「自定义补充选项」文本最大字符数。
|
||||||
|
// 覆盖两类入口:单选/多选/排序的全局补充选项,以及表单收集字段的
|
||||||
|
// 「其他/自定义选项」(field_{id}_custom)。
|
||||||
|
CustomAnswerLen int `ini:"custom_answer_len"`
|
||||||
|
// 站长创建投票时单个「选项」文本的最大字符数。
|
||||||
|
// 覆盖单选/多选/排序的预设选项,以及表单收集字段(select/radio/checkbox/rank)
|
||||||
|
// 的预置选项。与 CustomAnswerLen 是两条独立规则(站长侧预设刻意放宽),可各自调参。
|
||||||
|
VoteOptionLen int `ini:"vote_option_len"`
|
||||||
|
|
||||||
|
// ── 提问 / 回答 / 追问 ──
|
||||||
|
|
||||||
|
// 提问正文最大字符数(访客向提问箱提交的问题内容)。
|
||||||
|
// 旧实现依赖 govalid 的 maxlen 标签(编译期写死 2000),无法随配置调整,
|
||||||
|
// 且与前端 maxlength=1000 不一致,现已移到路由层按本值做 rune 校验。
|
||||||
|
QuestionContentLen int `ini:"question_content_len"`
|
||||||
|
// 回答正文最大字符数:箱主对提问的正式回答,以及箱主对追问的回复(共用)。
|
||||||
|
AnswerContentLen int `ini:"answer_content_len"`
|
||||||
|
// 追问正文最大字符数(提问者在问题被回答后继续追问的内容)。
|
||||||
|
FollowUpContentLen int `ini:"followup_content_len"`
|
||||||
|
|
||||||
|
// ── 私聊 ──
|
||||||
|
|
||||||
|
// 单条消息(发送 / 回复共用)最大字符数
|
||||||
|
ChatMessageLen int `ini:"chat_message_len"`
|
||||||
|
// 每个私聊会话的消息条数上限(系统硬顶)。用户只能在 1..该值 之间设置自己的
|
||||||
|
// chat_max_messages;新注册用户的默认值即该硬顶(而非固定 20)。
|
||||||
|
ChatMaxMessages int `ini:"chat_max_messages"`
|
||||||
|
// 单用户每日私信条数上限(用户可设范围 0..该值;0 表示不限制每日条数)。
|
||||||
|
// 该值只是「用户可设置的上限」,不是站点强制的每日配额。
|
||||||
|
DailyMessageLimitMax int `ini:"daily_message_limit_max"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Limits 保存运行时的全部上限配置。conf.Init 中会先 MapTo [limits] 段覆盖显式键,
|
||||||
|
// 再调用 sanitizeLimits 把 <1 的值回退到内置默认,因此:
|
||||||
|
// - 缺失 [limits] 段或个别键 → 使用内置默认;
|
||||||
|
// - ini 键留空(int 解析为 0)或误填 0/负数 → 自动回退默认,不会把上限静默置零。
|
||||||
|
var Limits = LimitsConfig{
|
||||||
|
MaxTags: defaultMaxTags,
|
||||||
|
MaxTagLen: defaultMaxTagLen,
|
||||||
|
MaxBlockWords: defaultMaxBlockWords,
|
||||||
|
MaxBlockWordLen: defaultMaxBlockWordLen,
|
||||||
|
CustomAnswerLen: defaultCustomAnswerLen,
|
||||||
|
VoteOptionLen: defaultVoteOptionLen,
|
||||||
|
QuestionContentLen: defaultQuestionContentLen,
|
||||||
|
AnswerContentLen: defaultAnswerContentLen,
|
||||||
|
FollowUpContentLen: defaultFollowUpContentLen,
|
||||||
|
ChatMessageLen: defaultChatMessageLen,
|
||||||
|
ChatMaxMessages: defaultChatMaxMessages,
|
||||||
|
DailyMessageLimitMax: defaultDailyMessageLimitMax,
|
||||||
|
}
|
||||||
|
|
||||||
|
// sanitizeLimits 归一化 [limits] 配置:所有上限最小为 1(0 / 负数说明未配置或手滑,
|
||||||
|
// 一律回退内置默认,避免「留空=0」把标签全拒、消息全超长等隐性灾难)。
|
||||||
|
// 注意 DailyMessageLimitMax 同样要求 >=1:0 会让用户侧永远只能设为 0(=不限制),
|
||||||
|
// 语义上等于关闭每日配额功能,需显式使用该字段其余语义时请另行设计。
|
||||||
|
func sanitizeLimits(l *LimitsConfig) {
|
||||||
|
clamp1 := func(p *int, def int) {
|
||||||
|
if *p < 1 {
|
||||||
|
*p = def
|
||||||
|
}
|
||||||
|
}
|
||||||
|
clamp1(&l.MaxTags, defaultMaxTags)
|
||||||
|
clamp1(&l.MaxTagLen, defaultMaxTagLen)
|
||||||
|
clamp1(&l.MaxBlockWords, defaultMaxBlockWords)
|
||||||
|
clamp1(&l.MaxBlockWordLen, defaultMaxBlockWordLen)
|
||||||
|
clamp1(&l.CustomAnswerLen, defaultCustomAnswerLen)
|
||||||
|
clamp1(&l.VoteOptionLen, defaultVoteOptionLen)
|
||||||
|
clamp1(&l.QuestionContentLen, defaultQuestionContentLen)
|
||||||
|
clamp1(&l.AnswerContentLen, defaultAnswerContentLen)
|
||||||
|
clamp1(&l.FollowUpContentLen, defaultFollowUpContentLen)
|
||||||
|
clamp1(&l.ChatMessageLen, defaultChatMessageLen)
|
||||||
|
clamp1(&l.ChatMaxMessages, defaultChatMaxMessages)
|
||||||
|
clamp1(&l.DailyMessageLimitMax, defaultDailyMessageLimitMax)
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
// 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 conf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gopkg.in/ini.v1"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestLimitsDefaults 保证内置默认值与旧版硬编码一致:未配置 [limits] 段(或 conf.Init
|
||||||
|
// 尚未调用)时,程序按这些默认值运行。
|
||||||
|
func TestLimitsDefaults(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
got int
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{"MaxTags", Limits.MaxTags, 5},
|
||||||
|
{"MaxTagLen", Limits.MaxTagLen, 5},
|
||||||
|
{"MaxBlockWords", Limits.MaxBlockWords, 10},
|
||||||
|
{"MaxBlockWordLen", Limits.MaxBlockWordLen, 10},
|
||||||
|
{"CustomAnswerLen", Limits.CustomAnswerLen, 200},
|
||||||
|
{"VoteOptionLen", Limits.VoteOptionLen, 300},
|
||||||
|
{"QuestionContentLen", Limits.QuestionContentLen, 1000},
|
||||||
|
{"AnswerContentLen", Limits.AnswerContentLen, 2000},
|
||||||
|
{"FollowUpContentLen", Limits.FollowUpContentLen, 2000},
|
||||||
|
{"ChatMessageLen", Limits.ChatMessageLen, 2000},
|
||||||
|
{"ChatMaxMessages", Limits.ChatMaxMessages, 200},
|
||||||
|
{"DailyMessageLimitMax", Limits.DailyMessageLimitMax, 999},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
if c.got != c.want {
|
||||||
|
t.Errorf("%s = %d, want %d", c.name, c.got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLimitsMapTo 模拟 conf.Init 的映射行为:显式键被覆盖,缺失键保留默认。
|
||||||
|
// 启动逻辑是 File.Section("limits").MapTo(&Limits),与这里同一路径。
|
||||||
|
func TestLimitsMapTo(t *testing.T) {
|
||||||
|
src := `
|
||||||
|
[limits]
|
||||||
|
max_tags = 7
|
||||||
|
chat_message_len = 500
|
||||||
|
answer_content_len = 300
|
||||||
|
daily_message_limit_max = 0
|
||||||
|
`
|
||||||
|
f, err := ini.LoadSources(ini.LoadOptions{IgnoreInlineComment: true}, []byte(src))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parse ini: %v", err)
|
||||||
|
}
|
||||||
|
l := Limits // 拷贝默认值,等价于启动前状态
|
||||||
|
if err := f.Section("limits").MapTo(&l); err != nil {
|
||||||
|
t.Fatalf("map [limits]: %v", err)
|
||||||
|
}
|
||||||
|
if l.MaxTags != 7 {
|
||||||
|
t.Errorf("MaxTags = %d, want 7 (ini 覆盖失败)", l.MaxTags)
|
||||||
|
}
|
||||||
|
if l.ChatMessageLen != 500 {
|
||||||
|
t.Errorf("ChatMessageLen = %d, want 500", l.ChatMessageLen)
|
||||||
|
}
|
||||||
|
if l.AnswerContentLen != 300 {
|
||||||
|
t.Errorf("AnswerContentLen = %d, want 300(ini 覆盖失败)", l.AnswerContentLen)
|
||||||
|
}
|
||||||
|
if l.DailyMessageLimitMax != 0 {
|
||||||
|
t.Errorf("DailyMessageLimitMax = %d, want 0(配置为 0 应生效)", l.DailyMessageLimitMax)
|
||||||
|
}
|
||||||
|
// 未显式出现的键保留内置默认
|
||||||
|
if l.MaxTagLen != 5 {
|
||||||
|
t.Errorf("MaxTagLen = %d, want 5(缺失键应保留默认)", l.MaxTagLen)
|
||||||
|
}
|
||||||
|
if l.VoteOptionLen != 300 {
|
||||||
|
t.Errorf("VoteOptionLen = %d, want 300", l.VoteOptionLen)
|
||||||
|
}
|
||||||
|
if l.QuestionContentLen != 1000 || l.FollowUpContentLen != 2000 {
|
||||||
|
t.Errorf("QuestionContentLen/FollowUpContentLen = %d/%d, want 1000/2000(缺失键应保留默认)",
|
||||||
|
l.QuestionContentLen, l.FollowUpContentLen)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLimitsEmptyValueSanitized 验证「键留空」的防护:ini 会把空 int 解析为 0,
|
||||||
|
// sanitizeLimits 随后将其回退到内置默认 —— 防止留空把上限静默置零(标签全拒等)。
|
||||||
|
func TestLimitsEmptyValueSanitized(t *testing.T) {
|
||||||
|
src := `
|
||||||
|
[limits]
|
||||||
|
max_tags =
|
||||||
|
chat_message_len = 0
|
||||||
|
followup_content_len = -1
|
||||||
|
daily_message_limit_max = -3
|
||||||
|
`
|
||||||
|
f, err := ini.LoadSources(ini.LoadOptions{IgnoreInlineComment: true}, []byte(src))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parse ini: %v", err)
|
||||||
|
}
|
||||||
|
l := Limits
|
||||||
|
if err := f.Section("limits").MapTo(&l); err != nil {
|
||||||
|
t.Fatalf("map [limits]: %v", err)
|
||||||
|
}
|
||||||
|
// 前提确认:空串对 int 是「保留原值」而非 0(gopkg.in/ini 行为);
|
||||||
|
// 显式 0 / 负数则照常映射。真正的 0 陷阱来自显式填 0 / 负数,由 sanitize 兜底。
|
||||||
|
if l.MaxTags != defaultMaxTags {
|
||||||
|
t.Fatalf("precondition broken: 空值 max_tags 应保留默认, got %d", l.MaxTags)
|
||||||
|
}
|
||||||
|
if l.ChatMessageLen != 0 || l.DailyMessageLimitMax != -3 {
|
||||||
|
t.Fatalf("precondition broken: got %d/%d, want 0/-3",
|
||||||
|
l.ChatMessageLen, l.DailyMessageLimitMax)
|
||||||
|
}
|
||||||
|
sanitizeLimits(&l)
|
||||||
|
if l.MaxTags != defaultMaxTags {
|
||||||
|
t.Errorf("MaxTags = %d, want 默认 %d", l.MaxTags, defaultMaxTags)
|
||||||
|
}
|
||||||
|
if l.ChatMessageLen != defaultChatMessageLen {
|
||||||
|
t.Errorf("ChatMessageLen = %d, want 默认 %d(0 应回退默认)", l.ChatMessageLen, defaultChatMessageLen)
|
||||||
|
}
|
||||||
|
if l.FollowUpContentLen != defaultFollowUpContentLen {
|
||||||
|
t.Errorf("FollowUpContentLen = %d, want 默认 %d(负数应回退默认)", l.FollowUpContentLen, defaultFollowUpContentLen)
|
||||||
|
}
|
||||||
|
if l.DailyMessageLimitMax != defaultDailyMessageLimitMax {
|
||||||
|
t.Errorf("DailyMessageLimitMax = %d, want 默认 %d(负数应回退默认)", l.DailyMessageLimitMax, defaultDailyMessageLimitMax)
|
||||||
|
}
|
||||||
|
if l.ChatMaxMessages != defaultChatMaxMessages {
|
||||||
|
t.Errorf("ChatMaxMessages = %d, want 默认 %d(缺失键不受影响)", l.ChatMaxMessages, defaultChatMaxMessages)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
// 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"`
|
||||||
|
// BanTrackNotFound 是否把「未注册路径的 404」计入封禁统计。默认 false:正常业务
|
||||||
|
// (域名/题目不存在等均走 302 业务跳转,不产生计数)一律放行,仅命中后台扫描特征
|
||||||
|
// 路径(KindSensitive)才参与统计封禁。避免共享出口(CDN 边缘 / CGNAT NAT444)下
|
||||||
|
// 正常用户被 404 探测流量连坐误伤。如需恢复对纯 404 字典扫描的封禁再置 true。
|
||||||
|
BanTrackNotFound bool `ini:"ban_track_notfound"`
|
||||||
|
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"`
|
||||||
|
}
|
||||||
|
)
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
// 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 context
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/flamego/flamego"
|
||||||
|
"github.com/flamego/session"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/db"
|
||||||
|
"github.com/tamakyi/TamaBox/internal/i18n"
|
||||||
|
)
|
||||||
|
|
||||||
|
// authenticatedUser returns the user object of the authenticated user.
|
||||||
|
func authenticatedUser(ctx flamego.Context, sess session.Session) *db.User {
|
||||||
|
uid, ok := sess.Get("uid").(uint)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
user, err := db.Users.GetByID(ctx.Request().Context(), uid)
|
||||||
|
if err != nil || user == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 密码变更后,旧会话保存的版本号不匹配,强制重新登录。
|
||||||
|
ver, _ := sess.Get("pwd_ver").(uint)
|
||||||
|
if user.PasswordVersion != ver {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return user
|
||||||
|
}
|
||||||
|
|
||||||
|
type ToggleOptions struct {
|
||||||
|
UserSignInRequired bool
|
||||||
|
UserSignOutRequired bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func Toggle(options *ToggleOptions) flamego.Handler {
|
||||||
|
return func(ctx Context, endpoint EndpointType) error {
|
||||||
|
if options.UserSignOutRequired && ctx.IsLogged {
|
||||||
|
ctx.Redirect("/")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if options.UserSignInRequired && !ctx.IsLogged {
|
||||||
|
if endpoint.IsAPI() {
|
||||||
|
return ctx.JSONError(40100, i18n.T(ctx.Lang(), "auth.errLoginRequired"))
|
||||||
|
}
|
||||||
|
ctx.SetErrorFlash(i18n.T(ctx.Lang(), "auth.errLoginRequired"))
|
||||||
|
ctx.Redirect("/login")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,327 @@
|
|||||||
|
// 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 context
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/flamego/csrf"
|
||||||
|
"github.com/flamego/flamego"
|
||||||
|
"github.com/flamego/session"
|
||||||
|
"github.com/flamego/template"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/unknwon/com"
|
||||||
|
"github.com/wuhan005/govalid"
|
||||||
|
"go.opentelemetry.io/otel/attribute"
|
||||||
|
"go.opentelemetry.io/otel/trace"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/conf"
|
||||||
|
"github.com/tamakyi/TamaBox/internal/db"
|
||||||
|
"github.com/tamakyi/TamaBox/internal/i18n"
|
||||||
|
"github.com/tamakyi/TamaBox/internal/shared"
|
||||||
|
templatepkg "github.com/tamakyi/TamaBox/internal/template"
|
||||||
|
)
|
||||||
|
|
||||||
|
type EndpointType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
EndpointAPI EndpointType = "api"
|
||||||
|
EndpointWeb EndpointType = "web"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (e EndpointType) IsAPI() bool {
|
||||||
|
return e == EndpointAPI
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e EndpointType) IsWeb() bool {
|
||||||
|
return e == EndpointWeb
|
||||||
|
}
|
||||||
|
|
||||||
|
func APIEndpoint(ctx Context) {
|
||||||
|
ctx.Map(EndpointAPI)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Context represents context of a request.
|
||||||
|
type Context struct {
|
||||||
|
flamego.Context
|
||||||
|
|
||||||
|
Data template.Data
|
||||||
|
Session session.Session
|
||||||
|
Template template.Template
|
||||||
|
|
||||||
|
User *db.User
|
||||||
|
IsLogged bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// HasError returns true if error occurs in form validation.
|
||||||
|
func (c *Context) HasError() bool {
|
||||||
|
hasErr, ok := c.Data["HasError"]
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return hasErr.(bool)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Context) SetError(err error, f ...interface{}) {
|
||||||
|
// 防御性兜底:调用方可能传入 nil error(如从某个可能返回 nil 的函数直接透传),
|
||||||
|
// 此时下方 err.Error() 会触发 nil 指针 panic。统一兜底为「未知错误」,避免整页崩溃。
|
||||||
|
if err == nil {
|
||||||
|
err = errors.New("发生未知错误")
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Data["HasError"] = true
|
||||||
|
|
||||||
|
// 表单校验(govalid)错误:其 Error() 在字段带 msg 标签时为 i18n 键,
|
||||||
|
// 在此按当前界面语言翻译;其余业务错误(errors.New(i18n.T(...)) 等)原样保留。
|
||||||
|
if ge, ok := err.(*govalid.ErrContext); ok {
|
||||||
|
c.Data["Error"] = i18n.T(c.Lang(), ge.Error())
|
||||||
|
} else {
|
||||||
|
c.Data["Error"] = err.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set back the form data.
|
||||||
|
if len(f) > 0 {
|
||||||
|
form := f[0]
|
||||||
|
typ := reflect.TypeOf(form)
|
||||||
|
val := reflect.ValueOf(form)
|
||||||
|
|
||||||
|
if typ.Kind() == reflect.Ptr {
|
||||||
|
typ = typ.Elem()
|
||||||
|
val = val.Elem()
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < typ.NumField(); i++ {
|
||||||
|
field := typ.Field(i)
|
||||||
|
fieldName := com.ToSnakeCase(field.Name)
|
||||||
|
|
||||||
|
c.Data[fieldName] = val.Field(i).Interface()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
span := trace.SpanFromContext(c.Request().Context())
|
||||||
|
if span.IsRecording() {
|
||||||
|
span.SetAttributes(
|
||||||
|
attribute.String("tamabox.error", err.Error()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Context) SetInternalError(f ...interface{}) {
|
||||||
|
span := trace.SpanFromContext(c.Request().Context())
|
||||||
|
traceID := span.SpanContext().TraceID()
|
||||||
|
|
||||||
|
c.Data["FlashTip"] = fmt.Sprintf("若问题一直出现,请带上该段字符 %s 提交反馈。", traceID.String())
|
||||||
|
c.SetError(errors.New(i18n.T(c.Lang(), "internal.errFlash")), f...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Success renders HTML template with given name with 200 OK status code.
|
||||||
|
func (c *Context) Success(templateName string) {
|
||||||
|
c.Template.HTML(http.StatusOK, templateName)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Context) SetTitle(title string) {
|
||||||
|
c.Data["Title"] = title
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Context) Refresh() {
|
||||||
|
c.Redirect(c.Request().URL.Path)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Context) JSON(data interface{}) error {
|
||||||
|
resp := map[string]interface{}{
|
||||||
|
"code": 0,
|
||||||
|
"data": data,
|
||||||
|
"message": "success",
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.NewEncoder(c.ResponseWriter()).Encode(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Context) ServerError() error {
|
||||||
|
return c.JSONError(50000, i18n.T(c.Lang(), "internal.errServer"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Context) JSONError(errorCode int, message string) error {
|
||||||
|
span := trace.SpanFromContext(c.Request().Context())
|
||||||
|
|
||||||
|
resp := map[string]interface{}{
|
||||||
|
"code": errorCode,
|
||||||
|
"message": message,
|
||||||
|
"trace_id": span.SpanContext().TraceID().String(),
|
||||||
|
}
|
||||||
|
|
||||||
|
statusCode := errorCode / 100
|
||||||
|
if statusCode < 100 || statusCode > 999 {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
}
|
||||||
|
c.ResponseWriter().WriteHeader(statusCode)
|
||||||
|
|
||||||
|
return json.NewEncoder(c.ResponseWriter()).Encode(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Contexter initializes a classic context for a request.
|
||||||
|
func Contexter() flamego.Handler {
|
||||||
|
return func(ctx flamego.Context, data template.Data, session session.Session, x csrf.CSRF, t template.Template, flash session.Flash) {
|
||||||
|
c := Context{
|
||||||
|
Context: ctx,
|
||||||
|
Data: data,
|
||||||
|
Session: session,
|
||||||
|
Template: t,
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST 类请求统一校验 CSRF(像素追踪代理已改为 GET 且仅转发只读请求,
|
||||||
|
// 不再需要 CSRF 豁免,故此处不再对 /api/v1/pixel/ 做例外)。
|
||||||
|
if ctx.Request().Method == http.MethodPost {
|
||||||
|
x.Validate(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get user from session or header when possible
|
||||||
|
c.User = authenticatedUser(c.Context, c.Session)
|
||||||
|
|
||||||
|
var userID uint
|
||||||
|
if c.User != nil {
|
||||||
|
c.IsLogged = true
|
||||||
|
c.Data["IsLogged"] = c.IsLogged
|
||||||
|
c.Data["LoggedUser"] = c.User
|
||||||
|
c.Data["LoggedUserID"] = c.User.ID
|
||||||
|
c.Data["LoggedUserName"] = c.User.Name
|
||||||
|
|
||||||
|
userID = c.User.ID
|
||||||
|
} else {
|
||||||
|
c.Data["LoggedUserID"] = 0
|
||||||
|
c.Data["LoggedUserName"] = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Data["IsPixel"] = ctx.Request().URL.Path == "/pixel"
|
||||||
|
|
||||||
|
span := trace.SpanFromContext(ctx.Request().Context())
|
||||||
|
if span.IsRecording() {
|
||||||
|
span.SetAttributes(
|
||||||
|
attribute.Bool("tamabox.user.is-login", c.IsLogged),
|
||||||
|
attribute.Int("tamabox.user.id", int(userID)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
c.ResponseWriter().Header().Set("Trace-ID", span.SpanContext().TraceID().String())
|
||||||
|
|
||||||
|
if flash != nil {
|
||||||
|
flash, ok := flash.(Flash)
|
||||||
|
if ok {
|
||||||
|
switch flash.Type {
|
||||||
|
case "success":
|
||||||
|
c.Data["Success"] = flash.Message
|
||||||
|
case "error":
|
||||||
|
c.Data["HasError"] = true
|
||||||
|
c.Data["Error"] = flash.Message
|
||||||
|
case "info":
|
||||||
|
c.Data["Info"] = flash.Message
|
||||||
|
case "warning":
|
||||||
|
c.Data["Warning"] = flash.Message
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Data["FlashTip"] = flash.FlashTip
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- i18n 语言注入 ----
|
||||||
|
// 解析优先级(按页面类型):
|
||||||
|
// - 个人页(/user 后台、/_/{domain} 提问箱):永远跟随主人 profile 语言,忽略访客 cookie。
|
||||||
|
// /user 后台即登录用户本人的配置,直接采用 c.User.Language;
|
||||||
|
// /_/{domain} 提问箱页由 question.Pager 中间件按 pageUser.Language 覆盖(见 route/question/page.go)。
|
||||||
|
// - 公开页(首页/探索/登录等):访客 lang cookie 优先;未设置 cookie 时登录用户资料语言次之;
|
||||||
|
// 再回退站点默认语言(shared.App)> i18n.Default。
|
||||||
|
path := ctx.Request().URL.Path
|
||||||
|
isUserPage := strings.HasPrefix(path, "/user") || strings.HasPrefix(path, "/_/")
|
||||||
|
c.Data["IsUserPage"] = isUserPage
|
||||||
|
|
||||||
|
// SEO:仅公开页(首页/注册/登录/explore)允许被搜索引擎收录;
|
||||||
|
// 提问内容(提问箱页、单题页)、密码页、私信、用户后台等隐私页一律 noindex。
|
||||||
|
isPublicPage := path == "/" || path == "/register" || path == "/login" || strings.HasPrefix(path, "/explore")
|
||||||
|
if !isPublicPage {
|
||||||
|
c.Data["NoIndex"] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
lang := ""
|
||||||
|
if isUserPage {
|
||||||
|
// 个人页:永远跟随 profile,忽略 cookie(/user 直接采用本人配置;
|
||||||
|
// /_/{domain} 由 question.Pager 覆盖,此处留空交由其处理)。
|
||||||
|
if strings.HasPrefix(path, "/user") && c.IsLogged && c.User.Language != "" {
|
||||||
|
lang = i18n.Resolve(c.User.Language)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 公开页:会话内显式选择的语言优先,其次登录用户资料语言,最后回退站点默认。
|
||||||
|
// 语言偏好存于 session(由 session 中间件托管 cookie);此前独立 lang cookie 会被
|
||||||
|
// session 中间件的 Set-Cookie 整体覆盖而失效,故此处改读 session。
|
||||||
|
if v := c.Session.Get("lang"); v != nil {
|
||||||
|
if s, ok := v.(string); ok && s != "" {
|
||||||
|
lang = i18n.Resolve(s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if lang == "" && c.IsLogged && c.User.Language != "" {
|
||||||
|
lang = i18n.Resolve(c.User.Language)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if lang == "" {
|
||||||
|
lang = shared.App.Lang()
|
||||||
|
}
|
||||||
|
c.Data["Lang"] = lang
|
||||||
|
c.Data["LangCode"] = lang
|
||||||
|
c.Data["SupportedLangs"] = i18n.Supported()
|
||||||
|
|
||||||
|
c.SetTitle(i18n.T(lang, "site.title"))
|
||||||
|
c.Data["CSRFToken"] = x.Token()
|
||||||
|
c.Data["CSRFTokenHTML"] = templatepkg.Safe(`<input type="hidden" name="_csrf" value="` + x.Token() + `">`)
|
||||||
|
|
||||||
|
c.Data["RecaptchaDomain"] = conf.Recaptcha.Domain
|
||||||
|
c.Data["RecaptchaSiteKey"] = conf.Recaptcha.SiteKey
|
||||||
|
c.Data["RecaptchaTurnstileStyle"] = conf.Recaptcha.TurnstileStyle
|
||||||
|
c.Data["CaptchaType"] = conf.Recaptcha.CaptchaType
|
||||||
|
|
||||||
|
c.Data["CurrentURI"] = ctx.Request().Request.RequestURI
|
||||||
|
c.Data["ExternalURL"] = conf.App.ExternalURL
|
||||||
|
|
||||||
|
// 默认头像/背景图兜底:未设置自定义头像的箱主,其二维码 logo 应与页面头像一致回退到 default_avatar。
|
||||||
|
// 模板按原始 URL 直连(easy.qrcode 以 crossOrigin:'anonymous' 加载,配合对象存储桶 CORS
|
||||||
|
// 返回 Access-Control-Allow-Origin,保证 canvas 不被污染、可正常导出)。
|
||||||
|
c.Data["DefaultAvatar"] = conf.Upload.DefaultAvatarURL
|
||||||
|
c.Data["DefaultBackgroundImage"] = conf.Upload.DefaultBackgroundImageURL
|
||||||
|
|
||||||
|
// [limits] 段全站上限的模板同源入口:所有页面可直接引用
|
||||||
|
// {{.Limits.QuestionContentLen}} / {{.Limits.AnswerContentLen}} /
|
||||||
|
// {{.Limits.FollowUpContentLen}} / {{.Limits.ChatMessageLen}} 等,
|
||||||
|
// 作为输入框 maxlength 等与后端校验的同一数据源,避免各处写死数字漂移。
|
||||||
|
c.Data["Limits"] = conf.Limits
|
||||||
|
|
||||||
|
// ⚠️ VConsole can only be enabled for the first user for security reasons.
|
||||||
|
c.Data["VConsole"] = ctx.Query("debug") == "on" && c.IsLogged && c.User.ID == 1
|
||||||
|
|
||||||
|
// 🚨 SECURITY: Prevent MIME type sniffing in some browsers,
|
||||||
|
c.ResponseWriter().Header().Set("X-Content-Type-Options", "nosniff")
|
||||||
|
c.ResponseWriter().Header().Set("X-Frame-Options", "DENY")
|
||||||
|
|
||||||
|
ctx.Map(c)
|
||||||
|
ctx.Map(EndpointWeb)
|
||||||
|
|
||||||
|
if conf.App.MaintenanceMode {
|
||||||
|
c.ResponseWriter().Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
||||||
|
c.Success("maintenance-mode")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lang 返回当前请求解析出的界面语言代码(已规范化,必定是字典可查的规范代码)。
|
||||||
|
// 解析优先级见上方 Data["Lang"] 注入逻辑(个人页跟随箱主语言;公开页跟随 lang cookie /
|
||||||
|
// 登录用户资料语言 / 站点默认语言)。若中间件尚未注入(极少数非标准路径),回退 i18n.Default。
|
||||||
|
// 用于后端 flash / 错误信息按访客当前语言本地化,避免硬编码中文绕过 i18n。
|
||||||
|
func (c *Context) Lang() string {
|
||||||
|
if l, ok := c.Data["Lang"].(string); ok && l != "" {
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
return i18n.Default
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
// 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 context
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"go.opentelemetry.io/otel/trace"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/i18n"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FlashType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
Info = "info"
|
||||||
|
Success = "success"
|
||||||
|
Warning = "warning"
|
||||||
|
Error = "error"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Flash struct {
|
||||||
|
Type FlashType
|
||||||
|
Message string
|
||||||
|
FlashTip string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Context) SetInfoFlash(message string, tip ...string) {
|
||||||
|
c.Session.SetFlash(Flash{Type: Info, Message: message, FlashTip: strings.Join(tip, "")})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Context) SetSuccessFlash(message string, tip ...string) {
|
||||||
|
c.Session.SetFlash(Flash{Type: Success, Message: message, FlashTip: strings.Join(tip, "")})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Context) SetWarningFlash(message string, tip ...string) {
|
||||||
|
c.Session.SetFlash(Flash{Type: Warning, Message: message, FlashTip: strings.Join(tip, "")})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Context) SetErrorFlash(message string, tip ...string) {
|
||||||
|
c.Session.SetFlash(Flash{Type: Error, Message: message, FlashTip: strings.Join(tip, "")})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Context) SetInternalErrorFlash() {
|
||||||
|
span := trace.SpanFromContext(c.Request().Context())
|
||||||
|
traceID := span.SpanContext().TraceID()
|
||||||
|
|
||||||
|
c.Session.SetFlash(Flash{Type: Error, Message: i18n.T(c.Lang(), "internal.errFlash"), FlashTip: fmt.Sprintf("若问题一直出现,请带上该段字符 %s 提交反馈。", traceID.String())})
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
// 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 db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/wuhan005/gadget"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
var CensorLogs CensorLogsStore
|
||||||
|
|
||||||
|
type CensorLogsStore interface {
|
||||||
|
GetByText(ctx context.Context, sourceName, text string, noLongerThan ...time.Time) (*CensorLog, error)
|
||||||
|
Create(ctx context.Context, options CreateCensorLogOptions) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCensorLogsStore(db *gorm.DB) CensorLogsStore {
|
||||||
|
return &censorLogs{db}
|
||||||
|
}
|
||||||
|
|
||||||
|
type censorLogs struct {
|
||||||
|
*gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
type CensorLog struct {
|
||||||
|
gorm.Model
|
||||||
|
SourceName string
|
||||||
|
Input string
|
||||||
|
InputHash string `gorm:"index"`
|
||||||
|
Pass bool
|
||||||
|
RawResponse json.RawMessage
|
||||||
|
}
|
||||||
|
|
||||||
|
var ErrCensorLogsNotFound = errors.New("censor logs dose not exist")
|
||||||
|
|
||||||
|
func (db *censorLogs) GetByText(ctx context.Context, sourceName, text string, noLongerThan ...time.Time) (*CensorLog, error) {
|
||||||
|
hash := hashText(text)
|
||||||
|
|
||||||
|
var censorLog CensorLog
|
||||||
|
q := db.WithContext(ctx).Where("source_name = ? AND input_hash = ?", sourceName, hash)
|
||||||
|
if len(noLongerThan) > 0 && !noLongerThan[0].IsZero() {
|
||||||
|
q = q.Where("created_at > ?", noLongerThan[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := q.First(&censorLog).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, ErrCensorLogsNotFound
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &censorLog, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateCensorLogOptions struct {
|
||||||
|
SourceName string
|
||||||
|
Input string
|
||||||
|
Pass bool
|
||||||
|
RawResponse json.RawMessage
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *censorLogs) Create(ctx context.Context, options CreateCensorLogOptions) error {
|
||||||
|
censorLog := CensorLog{
|
||||||
|
SourceName: options.SourceName,
|
||||||
|
Input: options.Input,
|
||||||
|
InputHash: hashText(options.Input),
|
||||||
|
Pass: options.Pass,
|
||||||
|
RawResponse: options.RawResponse,
|
||||||
|
}
|
||||||
|
return db.WithContext(ctx).Create(&censorLog).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func hashText(text string) string {
|
||||||
|
return gadget.Md5(text)
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
// Copyright 2023 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 db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCensorLogs(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
db, cleanup := newTestDB(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
censorLogsStore := NewCensorLogsStore(db)
|
||||||
|
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
test func(t *testing.T, ctx context.Context, db *censorLogs)
|
||||||
|
}{
|
||||||
|
{"Create", testCensorLogsCreate},
|
||||||
|
{"GetByText", testCensorLogsGetByText},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
t.Cleanup(func() {
|
||||||
|
if err := cleanup("censor_logs"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
tc.test(t, ctx, censorLogsStore.(*censorLogs))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testCensorLogsCreate(t *testing.T, ctx context.Context, db *censorLogs) {
|
||||||
|
err := db.Create(ctx, CreateCensorLogOptions{
|
||||||
|
SourceName: "aliyun",
|
||||||
|
Input: "hello world",
|
||||||
|
Pass: true,
|
||||||
|
RawResponse: []byte(`{}`),
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testCensorLogsGetByText(t *testing.T, ctx context.Context, db *censorLogs) {
|
||||||
|
err := db.Create(ctx, CreateCensorLogOptions{
|
||||||
|
SourceName: "aliyun",
|
||||||
|
Input: "hello world",
|
||||||
|
Pass: true,
|
||||||
|
RawResponse: []byte(`{}`),
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
t.Run("normal by cache", func(t *testing.T) {
|
||||||
|
got, err := db.GetByText(ctx, "aliyun", "hello world")
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
got.CreatedAt = time.Time{}
|
||||||
|
got.UpdatedAt = time.Time{}
|
||||||
|
|
||||||
|
want := &CensorLog{
|
||||||
|
Model: gorm.Model{
|
||||||
|
ID: 1,
|
||||||
|
},
|
||||||
|
SourceName: "aliyun",
|
||||||
|
Input: "hello world",
|
||||||
|
InputHash: hashText("hello world"),
|
||||||
|
Pass: true,
|
||||||
|
RawResponse: []byte(`{}`),
|
||||||
|
}
|
||||||
|
require.Equal(t, want, got)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("no longer than", func(t *testing.T) {
|
||||||
|
_, err := db.GetByText(ctx, "aliyun", "hello world", time.Now())
|
||||||
|
require.Equal(t, ErrCensorLogsNotFound, err)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
// 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 db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
|
"github.com/thanhpk/randstr"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/dbutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
var Conversations ConversationStore
|
||||||
|
|
||||||
|
type ConversationStore interface {
|
||||||
|
Create(ctx context.Context, opts CreateConversationOptions) (*Conversation, error)
|
||||||
|
GetByID(ctx context.Context, id uint) (*Conversation, error)
|
||||||
|
GetByToken(ctx context.Context, token string) (*Conversation, error)
|
||||||
|
GetByIDAndOwner(ctx context.Context, id, ownerID uint) (*Conversation, error)
|
||||||
|
GetByIDAndAsker(ctx context.Context, id, askerID uint) (*Conversation, error)
|
||||||
|
IncrementMessageCount(ctx context.Context, id uint) error
|
||||||
|
IncrementMessageCountIfBelow(ctx context.Context, id uint, max int) (bool, error)
|
||||||
|
DecrementMessageCount(ctx context.Context, id uint) error
|
||||||
|
MaybeClose(ctx context.Context, id uint, max int) error
|
||||||
|
Close(ctx context.Context, id uint) error
|
||||||
|
// ListByOwner 返回某箱主拥有的会话。limit>0 时启用分页(取 limit 条、跳过 offset 条),
|
||||||
|
// 用于私聊列表分页;导出场景传 limit=0 取全量,行为与改造前一致。
|
||||||
|
ListByOwner(ctx context.Context, ownerID uint, limit, offset int) ([]*Conversation, error)
|
||||||
|
// CountByOwner 统计某箱主拥有的会话总数(分页看板与"加载更多"判定用)。
|
||||||
|
CountByOwner(ctx context.Context, ownerID uint) (int64, error)
|
||||||
|
// ListByAsker 返回某提问者发起的会话;分页语义同 ListByOwner。
|
||||||
|
ListByAsker(ctx context.Context, askerID uint, limit, offset int) ([]*Conversation, error)
|
||||||
|
// CountByAsker 统计某提问者发起的会话总数。
|
||||||
|
CountByAsker(ctx context.Context, askerID uint) (int64, error)
|
||||||
|
MarkDeletedByOwner(ctx context.Context, id uint) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewConversationStore(db *gorm.DB) ConversationStore {
|
||||||
|
return &conversations{db}
|
||||||
|
}
|
||||||
|
|
||||||
|
type conversations struct {
|
||||||
|
*gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
type Conversation struct {
|
||||||
|
dbutil.Model
|
||||||
|
OwnerID uint `gorm:"index:idx_conversation_owner" json:"owner_id"`
|
||||||
|
AskerID uint `gorm:"index:idx_conversation_asker" json:"asker_id"`
|
||||||
|
Token string `gorm:"size:6;uniqueIndex" json:"token"`
|
||||||
|
MaxMessages int `gorm:"default:20" json:"max_messages"`
|
||||||
|
MessageCount int `gorm:"default:0" json:"message_count"`
|
||||||
|
IsClosed bool `gorm:"default:false" json:"is_closed"`
|
||||||
|
IsDeletedByOwner bool `gorm:"default:false" json:"is_deleted_by_owner"` // 新增
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Conversation) BeforeCreate(tx *gorm.DB) error {
|
||||||
|
c.MessageCount = 0
|
||||||
|
c.Token = randstr.String(6)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateConversationOptions struct {
|
||||||
|
OwnerID uint
|
||||||
|
AskerID uint
|
||||||
|
MaxMessages int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *conversations) Create(ctx context.Context, opts CreateConversationOptions) (*Conversation, error) {
|
||||||
|
conversation := &Conversation{
|
||||||
|
OwnerID: opts.OwnerID,
|
||||||
|
AskerID: opts.AskerID,
|
||||||
|
MaxMessages: opts.MaxMessages,
|
||||||
|
}
|
||||||
|
if err := db.WithContext(ctx).Create(conversation).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "create conversation")
|
||||||
|
}
|
||||||
|
return conversation, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *conversations) GetByID(ctx context.Context, id uint) (*Conversation, error) {
|
||||||
|
var conv Conversation
|
||||||
|
if err := db.WithContext(ctx).First(&conv, id).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get conversation")
|
||||||
|
}
|
||||||
|
return &conv, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *conversations) GetByToken(ctx context.Context, token string) (*Conversation, error) {
|
||||||
|
var conv Conversation
|
||||||
|
if err := db.WithContext(ctx).Where("token = ?", token).First(&conv).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get conversation by token")
|
||||||
|
}
|
||||||
|
return &conv, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *conversations) GetByIDAndOwner(ctx context.Context, id, ownerID uint) (*Conversation, error) {
|
||||||
|
var conv Conversation
|
||||||
|
if err := db.WithContext(ctx).Where("id = ? AND owner_id = ?", id, ownerID).First(&conv).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get by owner")
|
||||||
|
}
|
||||||
|
return &conv, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *conversations) GetByIDAndAsker(ctx context.Context, id, askerID uint) (*Conversation, error) {
|
||||||
|
var conv Conversation
|
||||||
|
if err := db.WithContext(ctx).Where("id = ? AND asker_id = ?", id, askerID).First(&conv).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get by asker")
|
||||||
|
}
|
||||||
|
return &conv, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *conversations) IncrementMessageCount(ctx context.Context, id uint) error {
|
||||||
|
return db.WithContext(ctx).Model(&Conversation{}).Where("id = ?", id).UpdateColumn("message_count", gorm.Expr("message_count + 1")).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// IncrementMessageCountIfBelow 原子地检查并递增消息计数:
|
||||||
|
// 仅当 message_count < max 且未关闭时才 +1,返回 true。
|
||||||
|
// 并发场景下(同一对话两端同时发送)可防止消息数超出上限。
|
||||||
|
func (db *conversations) IncrementMessageCountIfBelow(ctx context.Context, id uint, max int) (bool, error) {
|
||||||
|
res := db.WithContext(ctx).Model(&Conversation{}).
|
||||||
|
Where("id = ? AND message_count < ? AND is_closed = ?", id, max, false).
|
||||||
|
UpdateColumn("message_count", gorm.Expr("message_count + 1"))
|
||||||
|
if res.Error != nil {
|
||||||
|
return false, errors.Wrap(res.Error, "increment message count if below")
|
||||||
|
}
|
||||||
|
return res.RowsAffected > 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecrementMessageCount 回滚一次消息计数(计数已递增但消息落库失败时调用)。
|
||||||
|
func (db *conversations) DecrementMessageCount(ctx context.Context, id uint) error {
|
||||||
|
return db.WithContext(ctx).Model(&Conversation{}).
|
||||||
|
Where("id = ? AND message_count > 0", id).
|
||||||
|
UpdateColumn("message_count", gorm.Expr("message_count - 1")).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// MaybeClose 当消息数达到上限时关闭对话(幂等,供发送消息后调用)。
|
||||||
|
func (db *conversations) MaybeClose(ctx context.Context, id uint, max int) error {
|
||||||
|
return db.WithContext(ctx).Model(&Conversation{}).
|
||||||
|
Where("id = ? AND message_count >= ? AND is_closed = ?", id, max, false).
|
||||||
|
Update("is_closed", true).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *conversations) Close(ctx context.Context, id uint) error {
|
||||||
|
return db.WithContext(ctx).Model(&Conversation{}).Where("id = ?", id).Update("is_closed", true).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *conversations) ListByOwner(ctx context.Context, ownerID uint, limit, offset int) ([]*Conversation, error) {
|
||||||
|
var convs []*Conversation
|
||||||
|
q := db.WithContext(ctx).Where("owner_id = ? AND is_deleted_by_owner = ? AND token != ''", ownerID, false).
|
||||||
|
Order("created_at DESC")
|
||||||
|
if limit > 0 {
|
||||||
|
q = q.Limit(limit)
|
||||||
|
if offset > 0 {
|
||||||
|
q = q.Offset(offset)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := q.Find(&convs).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "list by owner")
|
||||||
|
}
|
||||||
|
return convs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *conversations) CountByOwner(ctx context.Context, ownerID uint) (int64, error) {
|
||||||
|
var count int64
|
||||||
|
if err := db.WithContext(ctx).Model(&Conversation{}).
|
||||||
|
Where("owner_id = ? AND is_deleted_by_owner = ? AND token != ''", ownerID, false).
|
||||||
|
Count(&count).Error; err != nil {
|
||||||
|
return 0, errors.Wrap(err, "count by owner")
|
||||||
|
}
|
||||||
|
return count, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *conversations) ListByAsker(ctx context.Context, askerID uint, limit, offset int) ([]*Conversation, error) {
|
||||||
|
var convs []*Conversation
|
||||||
|
q := db.WithContext(ctx).Where("asker_id = ? AND is_deleted_by_owner = ? AND token != ''", askerID, false).
|
||||||
|
Order("created_at DESC")
|
||||||
|
if limit > 0 {
|
||||||
|
q = q.Limit(limit)
|
||||||
|
if offset > 0 {
|
||||||
|
q = q.Offset(offset)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := q.Find(&convs).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "list by asker")
|
||||||
|
}
|
||||||
|
return convs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *conversations) CountByAsker(ctx context.Context, askerID uint) (int64, error) {
|
||||||
|
var count int64
|
||||||
|
if err := db.WithContext(ctx).Model(&Conversation{}).
|
||||||
|
Where("asker_id = ? AND is_deleted_by_owner = ? AND token != ''", askerID, false).
|
||||||
|
Count(&count).Error; err != nil {
|
||||||
|
return 0, errors.Wrap(err, "count by asker")
|
||||||
|
}
|
||||||
|
return count, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *conversations) MarkDeletedByOwner(ctx context.Context, id uint) error {
|
||||||
|
var conv Conversation
|
||||||
|
if err := db.WithContext(ctx).First(&conv, id).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
// 已删除或不存在:幂等,不影响调用方。
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return errors.Wrap(err, "get conversation for delete")
|
||||||
|
}
|
||||||
|
if conv.IsDeletedByOwner {
|
||||||
|
// 已经是删除状态:幂等返回,避免重复请求多次回退配额计数。
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.WithContext(ctx).Model(&Conversation{}).Where("id = ?", id).Update("is_deleted_by_owner", true).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "mark conversation deleted by owner")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 回退定量收集计数:删除私聊会话等价于少一条已收集内容,
|
||||||
|
// 否则达上限后即便删掉旧会话,功能仍会显示 quota_reached 关闭,须手动重置计数。
|
||||||
|
if conv.OwnerID != 0 {
|
||||||
|
if err := FeatureControls.IncrementQuota(ctx, conv.OwnerID, FeatureChat, -1); err != nil {
|
||||||
|
logrus.WithContext(ctx).WithError(err).Errorf("Failed to decrement chat quota for user %d", conv.OwnerID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
|
"github.com/uptrace/opentelemetry-go-extra/otelgorm"
|
||||||
|
"gorm.io/driver/mysql"
|
||||||
|
"gorm.io/driver/postgres"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/conf"
|
||||||
|
)
|
||||||
|
|
||||||
|
var AllTables = []interface{}{
|
||||||
|
&User{}, &Question{}, &FollowUp{}, &CensorLog{}, &UploadImage{}, &UploadImageQuestion{},
|
||||||
|
&Conversation{}, &Message{}, &MessageImage{}, &UserBlock{},
|
||||||
|
// 匿名投票
|
||||||
|
&Vote{}, &VoteOption{}, &VoteFormField{}, &VoteSubmission{},
|
||||||
|
// 功能开关(提问 / 私聊 / 投票 的开关、定时、定量收集)
|
||||||
|
&FeatureControl{},
|
||||||
|
}
|
||||||
|
|
||||||
|
func Init(typ, dsn string) (*gorm.DB, error) {
|
||||||
|
var dialector gorm.Dialector
|
||||||
|
|
||||||
|
switch typ {
|
||||||
|
case "mysql", "":
|
||||||
|
dialector = mysql.Open(dsn)
|
||||||
|
case "postgres":
|
||||||
|
dialector = postgres.Open(dsn)
|
||||||
|
default:
|
||||||
|
return nil, errors.Errorf("unknown database type: %q", typ)
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := gorm.Open(dialector, &gorm.Config{
|
||||||
|
SkipDefaultTransaction: true,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "connect to database")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 配置连接池
|
||||||
|
sqlDB, err := db.DB()
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get sql.DB from gorm")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1C1G 低配环境:调低连接池,避免每个 DB 连接占用过多内存。
|
||||||
|
// 提问箱是低并发场景,10 个打开连接绰绰有余。
|
||||||
|
// 最大打开连接数
|
||||||
|
sqlDB.SetMaxOpenConns(10)
|
||||||
|
// 最大空闲连接数
|
||||||
|
sqlDB.SetMaxIdleConns(4)
|
||||||
|
// 连接最大存活时间(避免长连接被数据库服务端断开)
|
||||||
|
sqlDB.SetConnMaxLifetime(5 * time.Minute)
|
||||||
|
// 空闲连接最大存活时间
|
||||||
|
sqlDB.SetConnMaxIdleTime(3 * time.Minute)
|
||||||
|
|
||||||
|
// 仅在明确开启迁移清理开关时处理 users 表历史重复值,避免服务启动时静默改写账号数据。
|
||||||
|
// 正常部署应先离线检查并清理重复 email/domain,再执行 AutoMigrate。
|
||||||
|
if conf.Database.DedupeUniqueFields {
|
||||||
|
if err := dedupeUniqueFields(db); err != nil {
|
||||||
|
return nil, errors.Wrap(err, "dedupe unique fields before migrate")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.AutoMigrate(AllTables...); err != nil {
|
||||||
|
return nil, errors.Wrap(err, "auto migrate")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 功能开关初始化:为历史账号补齐 feature_controls 行(私聊沿用 users.allow_chat)。
|
||||||
|
// 幂等,已初始化的账号不会重复写入;失败不阻断启动,仅告警,避免依赖表抖动导致服务起不来。
|
||||||
|
if err := backfillFeatureControls(db); err != nil {
|
||||||
|
logrus.WithError(err).Warn("初始化功能开关配置时异常(可在功能管理页手动保存一次以生成配置)")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 私聊开关纠偏:旧版 backfill 曾把未开启私聊的账号写为开启(GORM 零值陷阱),
|
||||||
|
// 启动期幂等复位;同样不阻断启动,失败仅告警。
|
||||||
|
if err := reconcileLegacyChatEnabled(db); err != nil {
|
||||||
|
logrus.WithError(err).Warn("私聊开关历史数据纠偏时异常(可在功能管理页手动调整私聊开关)")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 私聊收集上限下线:私聊不再支持收集上限(UI 已隐藏,保存时强制清零),
|
||||||
|
// 启动期把历史残留的上限/计数一并清零,避免私聊「莫名关闭」。幂等,失败仅告警。
|
||||||
|
if err := normalizeChatQuota(db); err != nil {
|
||||||
|
logrus.WithError(err).Warn("私聊收集上限历史数据清理时异常(可在功能管理页保存一次私聊设置)")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 启动期补充高频查询复合索引(幂等,适合既有库)。
|
||||||
|
// 仅 PostgreSQL 需要:这些索引针对服务端真实查询模式(按归属用户+私密+时间、
|
||||||
|
// 按 asker、按展示/投票状态+可见性+时间、按会话/发送者+时间)。
|
||||||
|
// 本项目实际使用 PostgreSQL(详见 code-review-2026-08-28.md P1-4)。
|
||||||
|
if typ == "postgres" {
|
||||||
|
if err := ensureFrequentlyUsedIndexes(db); err != nil {
|
||||||
|
// 索引创建失败不应阻断启动,仅告警,便于在运维侧排查。
|
||||||
|
logrus.WithError(err).Warn("创建高频查询复合索引时异常(可能部分索引未建立,不影响服务启动)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Users = NewUsersStore(db)
|
||||||
|
Questions = NewQuestionsStore(db)
|
||||||
|
FollowUps = NewFollowUpsStore(db)
|
||||||
|
CensorLogs = NewCensorLogsStore(db)
|
||||||
|
UploadImages = NewUploadImagesStore(db)
|
||||||
|
Conversations = NewConversationStore(db)
|
||||||
|
Messages = NewMessageStore(db)
|
||||||
|
MessageImages = NewMessageImageStore(db)
|
||||||
|
Votes = NewVotesStore(db)
|
||||||
|
VoteOptions = NewVoteOptionsStore(db)
|
||||||
|
VoteFormFields = NewVoteFormFieldsStore(db)
|
||||||
|
VoteSubmissions = NewVoteSubmissionsStore(db)
|
||||||
|
FeatureControls = NewFeatureControlsStore(db)
|
||||||
|
|
||||||
|
if err := db.Use(otelgorm.NewPlugin(
|
||||||
|
otelgorm.WithDBName(conf.Database.Name),
|
||||||
|
)); err != nil {
|
||||||
|
return nil, errors.Wrap(err, "register otelgorm plugin")
|
||||||
|
}
|
||||||
|
|
||||||
|
if typ == "postgres" {
|
||||||
|
if err := fixPostgresSequences(db); err != nil {
|
||||||
|
return nil, errors.Wrap(err, "fix postgres sequences")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return db, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// dedupeUniqueFields 在 AutoMigrate 之前清理 users 表中重复的 email / domain:
|
||||||
|
// 每个重复值仅保留 id 最小(最早注册)的一行,其余行该字段置为 NULL。
|
||||||
|
// NULL 在 MySQL / PostgreSQL / SQLite 的唯一索引中互不冲突,因此置空即可让唯一索引成功建立。
|
||||||
|
// 幂等:重复数据被清理后再次启动时无任何操作。跨数据库兼容(仅使用标准 SQL,无目标表子查询)。
|
||||||
|
func dedupeUniqueFields(db *gorm.DB) error {
|
||||||
|
for _, field := range []string{"email", "domain"} {
|
||||||
|
var keepIDs []uint
|
||||||
|
var dupVals []string
|
||||||
|
|
||||||
|
rows, err := db.Table("users").
|
||||||
|
Select("MIN(id) AS keep_id, " + field + " AS val").
|
||||||
|
Where(field + " IS NOT NULL").
|
||||||
|
Group(field).
|
||||||
|
Having("COUNT(*) > 1").
|
||||||
|
Rows()
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "query duplicate %s", field)
|
||||||
|
}
|
||||||
|
for rows.Next() {
|
||||||
|
var keepID uint
|
||||||
|
var val string
|
||||||
|
if err := rows.Scan(&keepID, &val); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return errors.Wrapf(err, "scan duplicate %s", field)
|
||||||
|
}
|
||||||
|
keepIDs = append(keepIDs, keepID)
|
||||||
|
dupVals = append(dupVals, val)
|
||||||
|
}
|
||||||
|
if err := rows.Close(); err != nil {
|
||||||
|
return errors.Wrapf(err, "close rows for %s", field)
|
||||||
|
}
|
||||||
|
if rows.Err() != nil {
|
||||||
|
return errors.Wrapf(rows.Err(), "iterate duplicate %s", field)
|
||||||
|
}
|
||||||
|
if len(keepIDs) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
res := db.Table("users").
|
||||||
|
Where(field+" IS NOT NULL").
|
||||||
|
Where(field+" IN ?", dupVals).
|
||||||
|
Where("id NOT IN ?", keepIDs).
|
||||||
|
Update(field, nil)
|
||||||
|
if res.Error != nil {
|
||||||
|
return errors.Wrapf(res.Error, "clean duplicate %s", field)
|
||||||
|
}
|
||||||
|
if res.RowsAffected > 0 {
|
||||||
|
logrus.WithField("field", field).
|
||||||
|
Warnf("迁移前置清理:%d 行重复的 %s 已置空(保留最早注册的账号)", res.RowsAffected, field)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ensureFrequentlyUsedIndexes 在 AutoMigrate 之后创建高频查询所需的复合索引。
|
||||||
|
// 全部使用 CREATE INDEX IF NOT EXISTS,幂等、可在既有库上安全运行,重复执行无副作用。
|
||||||
|
// 索引设计依据服务端真实查询模式(详见 code-review-2026-08-28.md P1-4):
|
||||||
|
// - questions: 按 user_id + is_private + created_at 过滤排序(提问箱列表);
|
||||||
|
// 按 asker_user_id 查询(我发起的提问)。
|
||||||
|
// - users: 按 show_in_home + created_at(首页展示箱列表)。
|
||||||
|
// - votes: 按 status + visibility + created_at(探索页/提问箱页公开投票)。
|
||||||
|
// - messages: 按 conversation_id + created_at、sender_id + created_at(私信列表/会话消息)。
|
||||||
|
func ensureFrequentlyUsedIndexes(db *gorm.DB) error {
|
||||||
|
indexes := []string{
|
||||||
|
`CREATE INDEX IF NOT EXISTS idx_questions_asker_user_id ON questions(asker_user_id)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS idx_questions_user_private_created ON questions(user_id, is_private, created_at)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS idx_users_show_in_home_created ON users(show_in_home, created_at)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS idx_votes_status_visibility_created ON votes(status, visibility, created_at)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS idx_messages_sender_created ON messages(sender_id, created_at)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS idx_messages_conversation_created ON messages(conversation_id, created_at)`,
|
||||||
|
}
|
||||||
|
for _, ddl := range indexes {
|
||||||
|
if err := db.Exec(ddl).Error; err != nil {
|
||||||
|
return errors.Wrapf(err, "create index: %s", ddl)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func fixPostgresSequences(db *gorm.DB) error {
|
||||||
|
// 使用配置的 schema(未配置时回退 public),避免硬编码 nekobox。
|
||||||
|
schema := conf.Database.Schema
|
||||||
|
if schema == "" {
|
||||||
|
schema = "public"
|
||||||
|
}
|
||||||
|
|
||||||
|
tablesWithID := []string{"users", "questions", "follow_ups", "censor_logs", "upload_images", "conversations", "messages", "message_images", "votes", "vote_options", "vote_form_fields", "vote_submissions", "feature_controls"}
|
||||||
|
for _, table := range tablesWithID {
|
||||||
|
seqName := table + "_id_seq"
|
||||||
|
resetQuery := fmt.Sprintf(`
|
||||||
|
CREATE SEQUENCE IF NOT EXISTS %s.%s;
|
||||||
|
ALTER TABLE %s.%s
|
||||||
|
ALTER COLUMN id SET DEFAULT nextval('%s.%s');
|
||||||
|
SELECT setval('%s.%s',
|
||||||
|
COALESCE((SELECT MAX(id) FROM %s.%s), 1)::bigint,
|
||||||
|
true);
|
||||||
|
`, schema, seqName, schema, table, schema, seqName, schema, seqName, schema, table)
|
||||||
|
if err := db.Exec(resetQuery).Error; err != nil {
|
||||||
|
return fmt.Errorf("修复表 %s 序列时出错: %w", table, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,723 @@
|
|||||||
|
// 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 db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/clause"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/dbutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
var FeatureControls FeatureControlsStore
|
||||||
|
|
||||||
|
var _ FeatureControlsStore = (*featureControls)(nil)
|
||||||
|
|
||||||
|
// 受控功能标识(feature_controls.feature 取值)。
|
||||||
|
const (
|
||||||
|
FeatureQuestion = "question" // 提问
|
||||||
|
FeatureChat = "chat" // 私聊
|
||||||
|
FeatureVote = "vote" // 投票
|
||||||
|
)
|
||||||
|
|
||||||
|
// FeatureKeys 全部受控功能,顺序即功能管理页的展示顺序。
|
||||||
|
var FeatureKeys = []string{FeatureQuestion, FeatureChat, FeatureVote}
|
||||||
|
|
||||||
|
// 功能不可用原因(空串表示可用)。
|
||||||
|
const (
|
||||||
|
FeatureReasonDisabled = "disabled" // 手动关闭
|
||||||
|
FeatureReasonNotStarted = "not_started" // 未到开放时间
|
||||||
|
FeatureReasonEnded = "ended" // 已过关闭时间
|
||||||
|
FeatureReasonQuotaReached = "quota_reached" // 已达定量收集上限
|
||||||
|
)
|
||||||
|
|
||||||
|
// QuotaLimitMax 单个功能的收集上限最大值,防止误填极大值。
|
||||||
|
const QuotaLimitMax = 1_000_000
|
||||||
|
|
||||||
|
type FeatureControlsStore interface {
|
||||||
|
// Get 读取某功能的配置;无记录时返回该功能的默认配置(不落库)。
|
||||||
|
Get(ctx context.Context, userID uint, feature string) (*FeatureControl, error)
|
||||||
|
// ListByUserID 读取某用户全部功能的配置(无记录的功能不出现在结果中)。
|
||||||
|
ListByUserID(ctx context.Context, userID uint) ([]*FeatureControl, error)
|
||||||
|
// ListByUserIDs 批量读取多个用户同一功能的配置(探索页等批量场景用,避免 N+1)。
|
||||||
|
ListByUserIDs(ctx context.Context, userIDs []uint, feature string) (map[uint]*FeatureControl, error)
|
||||||
|
// Save 写入配置(不存在则创建,存在则更新开关/时间窗/上限,不影响已收集计数)。
|
||||||
|
Save(ctx context.Context, userID uint, feature string, opts UpdateFeatureControlOptions) error
|
||||||
|
// ResetQuota 清零收集计数,重新开始一轮定量收集。
|
||||||
|
ResetQuota(ctx context.Context, userID uint, feature string) error
|
||||||
|
// IncrementQuota 累加收集计数;无记录时按 delta 创建。
|
||||||
|
IncrementQuota(ctx context.Context, userID uint, feature string, delta int64) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFeatureControlsStore(db *gorm.DB) FeatureControlsStore {
|
||||||
|
return &featureControls{db}
|
||||||
|
}
|
||||||
|
|
||||||
|
type featureControls struct {
|
||||||
|
*gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
// FeatureControl 提问箱单个功能(提问 / 私聊 / 投票)的开关、定时与定量收集配置。
|
||||||
|
//
|
||||||
|
// 三类控制互不覆盖,最终可用状态由 Evaluate 综合计算:
|
||||||
|
// - Enabled:手动总开关;
|
||||||
|
// - OpenAt / CloseAt:定时开放与定时关闭(nil 表示不限制该侧);
|
||||||
|
// - QuotaLimit / QuotaCount:定量收集,累计收集数达到上限后自动关闭(0 表示不限制)。
|
||||||
|
//
|
||||||
|
// 计数不做定时重置:一轮收集结束后由箱主在功能管理页手动「重置计数」开启下一轮,
|
||||||
|
// 避免与定时开关叠加产生难以预期的自动恢复行为。
|
||||||
|
type FeatureControl struct {
|
||||||
|
dbutil.Model
|
||||||
|
UserID uint `gorm:"uniqueIndex:idx_feature_control_user_feature;not null" json:"-"`
|
||||||
|
Feature string `gorm:"size:20;uniqueIndex:idx_feature_control_user_feature;not null" json:"feature"`
|
||||||
|
// ⚠️ 不要给 Enabled 加 gorm:"default:true" 标签:
|
||||||
|
// GORM 在 Create 时会把零值 false 替换为字段默认值(true),导致「取消勾选保存」后
|
||||||
|
// 数据库里仍是 true、复选框自动恢复为勾选。去掉标签后 GORM 会原样写入显式设置的值。
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
// OpenAt / CloseAt:一次性定时开放 / 关闭(nil 表示不限制该侧)。
|
||||||
|
OpenAt *time.Time `json:"open_at"`
|
||||||
|
CloseAt *time.Time `json:"close_at"`
|
||||||
|
// 循环定时(每周循环):ScheduleDays 为逗号分隔的周几(0=周日…6=周六,与 time.Weekday 一致),
|
||||||
|
// 空表示每天都开放;ScheduleStart/ScheduleEnd 为每日时间段 "HH:MM"(留空表示该日全天)。
|
||||||
|
// 两者都为空时表示未启用循环定时。
|
||||||
|
ScheduleDays string `gorm:"size:31" json:"schedule_days"`
|
||||||
|
ScheduleStart string `gorm:"size:5" json:"schedule_start"`
|
||||||
|
ScheduleEnd string `gorm:"size:5" json:"schedule_end"`
|
||||||
|
QuotaLimit int64 `gorm:"default:0" json:"quota_limit"`
|
||||||
|
QuotaCount int64 `gorm:"default:0" json:"quota_count"`
|
||||||
|
QuotaResetAt *time.Time `json:"quota_reset_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// FeatureState 某功能在某一时刻的综合状态。
|
||||||
|
type FeatureState struct {
|
||||||
|
Enabled bool // 手动开关
|
||||||
|
Open bool // 综合(开关 + 定时 + 定量)后的最终可用状态
|
||||||
|
Reason string // 不可用原因,空串表示可用(取值见 FeatureReason*)
|
||||||
|
QuotaLimit int64 // 收集上限(0 = 不限制)
|
||||||
|
QuotaCount int64 // 已收集数量
|
||||||
|
OpenAt *time.Time // 一次性定时开放时间
|
||||||
|
CloseAt *time.Time // 一次性定时关闭时间
|
||||||
|
NextOpenAt *time.Time // 下一次开放时间(可能来自一次性窗口或循环定时;永久关闭时为 nil)
|
||||||
|
LastCloseAt *time.Time // 最近一次关闭时间(从未开放过时为 nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Evaluate 计算该功能在 now 时刻的综合状态。
|
||||||
|
// 判定优先级:手动关闭 > 未到一次性开放时间 > 已过一次性关闭时间 > 不在循环定时窗口内 > 达到收集上限。
|
||||||
|
func (fc *FeatureControl) Evaluate(now time.Time) FeatureState {
|
||||||
|
st := FeatureState{
|
||||||
|
Enabled: fc.Enabled,
|
||||||
|
QuotaLimit: fc.QuotaLimit,
|
||||||
|
QuotaCount: fc.QuotaCount,
|
||||||
|
OpenAt: fc.OpenAt,
|
||||||
|
CloseAt: fc.CloseAt,
|
||||||
|
}
|
||||||
|
// 先算好下次开放 / 最近关闭,供 reason 判定与展示复用。
|
||||||
|
st.NextOpenAt = fc.nextOpenAt(now)
|
||||||
|
st.LastCloseAt = fc.lastCloseAt(now)
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case !fc.Enabled:
|
||||||
|
st.Reason = FeatureReasonDisabled
|
||||||
|
// 手动关闭与时间无关,不展示开放/关闭时间
|
||||||
|
st.NextOpenAt, st.LastCloseAt = nil, nil
|
||||||
|
case fc.OpenAt != nil && now.Before(*fc.OpenAt):
|
||||||
|
st.Reason = FeatureReasonNotStarted
|
||||||
|
case fc.CloseAt != nil && !now.Before(*fc.CloseAt):
|
||||||
|
// 已过一次性关闭时间:一次性窗口是硬性外边界,循环定时仅在窗口内生效,
|
||||||
|
// 因此之后不会再开放(nextOpenAt 已按 CloseAt 约束计算,返回 nil)。
|
||||||
|
st.Reason = FeatureReasonEnded
|
||||||
|
st.NextOpenAt = nil
|
||||||
|
default:
|
||||||
|
switch fc.scheduleSlotStatus(now) {
|
||||||
|
case scheduleBeforeStart:
|
||||||
|
st.Reason = FeatureReasonNotStarted
|
||||||
|
case scheduleAfterEnd:
|
||||||
|
if st.NextOpenAt != nil {
|
||||||
|
st.Reason = FeatureReasonNotStarted
|
||||||
|
} else {
|
||||||
|
st.Reason = FeatureReasonEnded
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if st.Reason == "" && fc.QuotaLimit > 0 && fc.QuotaCount >= fc.QuotaLimit {
|
||||||
|
st.Reason = FeatureReasonQuotaReached
|
||||||
|
// 定量上限与时间无关,不展示开放/关闭时间
|
||||||
|
st.NextOpenAt, st.LastCloseAt = nil, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
st.Open = st.Reason == ""
|
||||||
|
return st
|
||||||
|
}
|
||||||
|
|
||||||
|
// scheduleSlotStatus 表示 now 相对循环定时窗口的位置。
|
||||||
|
type scheduleSlotStatus int
|
||||||
|
|
||||||
|
const (
|
||||||
|
scheduleInWindow scheduleSlotStatus = iota // 在开放窗口内
|
||||||
|
scheduleBeforeStart // 今天开放,但未到开始时间
|
||||||
|
scheduleAfterEnd // 已过结束时间,或今天不在开放日
|
||||||
|
)
|
||||||
|
|
||||||
|
// scheduleActive 判断是否启用了循环定时。
|
||||||
|
// 规则:设置了开放日,或同时设置了开始/结束时间,即视为启用;
|
||||||
|
// 只设置单侧时间视为配置异常,由路由层校验拦截。
|
||||||
|
func (fc *FeatureControl) scheduleActive() bool {
|
||||||
|
return fc.ScheduleDays != "" || (fc.ScheduleStart != "" && fc.ScheduleEnd != "")
|
||||||
|
}
|
||||||
|
|
||||||
|
// scheduleDayOpen 判断某天是否为开放日(ScheduleDays 为空 = 每天都开放)。
|
||||||
|
func (fc *FeatureControl) scheduleDayOpen(day time.Time) bool {
|
||||||
|
return fc.ScheduleDays == "" || containsWeekday(fc.ScheduleDays, int(day.Weekday()))
|
||||||
|
}
|
||||||
|
|
||||||
|
// scheduleWindow 返回单日开放窗口的分钟数 [startM, endM)。
|
||||||
|
// 未设置时间段时视为全天 [0, 1440)。配置非法时返回错误(调用方按"不限制"处理)。
|
||||||
|
func (fc *FeatureControl) scheduleWindow() (startM, endM int, err error) {
|
||||||
|
if fc.ScheduleStart == "" && fc.ScheduleEnd == "" {
|
||||||
|
return 0, 24 * 60, nil
|
||||||
|
}
|
||||||
|
if startM, err = parseHHMM(fc.ScheduleStart); err != nil {
|
||||||
|
return 0, 0, errors.Wrap(err, "parse schedule start")
|
||||||
|
}
|
||||||
|
if endM, err = parseHHMM(fc.ScheduleEnd); err != nil {
|
||||||
|
return 0, 0, errors.Wrap(err, "parse schedule end")
|
||||||
|
}
|
||||||
|
if endM <= startM {
|
||||||
|
return 0, 0, errors.New("schedule end must be after start")
|
||||||
|
}
|
||||||
|
return startM, endM, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// scheduleSlotStatus 返回 now 相对循环定时窗口的位置;未启用循环定时时恒为"在窗口内"。
|
||||||
|
func (fc *FeatureControl) scheduleSlotStatus(now time.Time) scheduleSlotStatus {
|
||||||
|
if !fc.scheduleActive() {
|
||||||
|
return scheduleInWindow
|
||||||
|
}
|
||||||
|
if !fc.scheduleDayOpen(now) {
|
||||||
|
return scheduleAfterEnd
|
||||||
|
}
|
||||||
|
startM, endM, err := fc.scheduleWindow()
|
||||||
|
if err != nil {
|
||||||
|
return scheduleInWindow // 配置异常按不限制处理(路由层已校验,此处兜底)
|
||||||
|
}
|
||||||
|
mins := now.Hour()*60 + now.Minute()
|
||||||
|
switch {
|
||||||
|
case mins < startM:
|
||||||
|
return scheduleBeforeStart
|
||||||
|
case mins >= endM:
|
||||||
|
return scheduleAfterEnd
|
||||||
|
}
|
||||||
|
return scheduleInWindow
|
||||||
|
}
|
||||||
|
|
||||||
|
// nextOpenAt 计算下一次可开放的时间(严格晚于 now)。
|
||||||
|
// 同时考虑一次性窗口与循环定时,返回二者中最早的下一次开放时刻;永久关闭时返回 nil。
|
||||||
|
func (fc *FeatureControl) nextOpenAt(now time.Time) *time.Time {
|
||||||
|
var earliest *time.Time
|
||||||
|
|
||||||
|
// 未启用循环定时时,一次性开放时间即为下一次开放。
|
||||||
|
// 启用后由下方按日扫描统一处理(一次性开放时间也必须落在循环窗口内)。
|
||||||
|
if fc.OpenAt != nil && fc.OpenAt.After(now) && !fc.scheduleActive() {
|
||||||
|
t := *fc.OpenAt
|
||||||
|
earliest = &t
|
||||||
|
}
|
||||||
|
|
||||||
|
if fc.scheduleActive() {
|
||||||
|
startM, endM, err := fc.scheduleWindow()
|
||||||
|
if err == nil {
|
||||||
|
day := startOfDay(now)
|
||||||
|
// 扫描今天起的 8 天:7 天覆盖全部周几组合,多 1 天兜底边界。
|
||||||
|
for i := 0; i < 8; i++ {
|
||||||
|
d := day.AddDate(0, 0, i)
|
||||||
|
if !fc.scheduleDayOpen(d) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
slotStart := d.Add(time.Duration(startM) * time.Minute)
|
||||||
|
slotEnd := d.Add(time.Duration(endM) * time.Minute)
|
||||||
|
// 与一次性窗口求交集:有效开放起点 = max(时段起点, 一次性开放时间),且须在时段与一次性关闭时间之前
|
||||||
|
effStart := slotStart
|
||||||
|
if fc.OpenAt != nil && fc.OpenAt.After(effStart) {
|
||||||
|
effStart = *fc.OpenAt
|
||||||
|
}
|
||||||
|
if !effStart.Before(slotEnd) {
|
||||||
|
continue // 有效开放起点晚于该日时段结束,该日无有效窗口
|
||||||
|
}
|
||||||
|
if fc.CloseAt != nil && !effStart.Before(*fc.CloseAt) {
|
||||||
|
continue // 有效开放起点已过一次性关闭时间
|
||||||
|
}
|
||||||
|
if effStart.After(now) {
|
||||||
|
if earliest == nil || effStart.Before(*earliest) {
|
||||||
|
t := effStart
|
||||||
|
earliest = &t
|
||||||
|
}
|
||||||
|
break // 该日找到最早有效开放点即可(同一日只有一个窗口)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return earliest
|
||||||
|
}
|
||||||
|
|
||||||
|
// lastCloseAt 计算最近一次关闭的时间(严格早于 now);从未开放过时返回 nil。
|
||||||
|
func (fc *FeatureControl) lastCloseAt(now time.Time) *time.Time {
|
||||||
|
var latest *time.Time
|
||||||
|
|
||||||
|
// 未启用循环定时时,一次性关闭时间即为最近一次关闭。
|
||||||
|
// 启用后由下方按日扫描统一处理(与时段结束取较早者)。
|
||||||
|
if fc.CloseAt != nil && fc.CloseAt.Before(now) && !fc.scheduleActive() {
|
||||||
|
t := *fc.CloseAt
|
||||||
|
latest = &t
|
||||||
|
}
|
||||||
|
|
||||||
|
if fc.scheduleActive() {
|
||||||
|
startM, endM, err := fc.scheduleWindow()
|
||||||
|
if err == nil {
|
||||||
|
day := startOfDay(now)
|
||||||
|
// 从今天向前扫描 8 天,找最近一次已结束的窗口。
|
||||||
|
for i := 0; i < 8; i++ {
|
||||||
|
d := day.AddDate(0, 0, -i)
|
||||||
|
if !fc.scheduleDayOpen(d) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
slotStart := d.Add(time.Duration(startM) * time.Minute)
|
||||||
|
slotEnd := d.Add(time.Duration(endM) * time.Minute)
|
||||||
|
// 与一次性窗口求交集:有效关闭点 = min(时段结束, 一次性关闭时间)
|
||||||
|
effEnd := slotEnd
|
||||||
|
if fc.CloseAt != nil && fc.CloseAt.Before(effEnd) {
|
||||||
|
effEnd = *fc.CloseAt
|
||||||
|
}
|
||||||
|
if effEnd.Before(slotStart) {
|
||||||
|
continue // 一次性关闭时间早于该日时段起点,该日无有效窗口
|
||||||
|
}
|
||||||
|
if effEnd.Before(now) {
|
||||||
|
if latest == nil || effEnd.After(*latest) {
|
||||||
|
t := effEnd
|
||||||
|
latest = &t
|
||||||
|
}
|
||||||
|
break // 已找到最近一次关闭
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return latest
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseHHMM 解析 "HH:MM" 为当天第几分钟。
|
||||||
|
func parseHHMM(s string) (int, error) {
|
||||||
|
t, err := time.Parse("15:04", s)
|
||||||
|
if err != nil {
|
||||||
|
return 0, errors.Wrap(err, "parse HH:MM")
|
||||||
|
}
|
||||||
|
return t.Hour()*60 + t.Minute(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// containsWeekday 判断逗号分隔的周几列表(0=周日…6=周六)是否包含 wd。
|
||||||
|
func containsWeekday(days string, wd int) bool {
|
||||||
|
for _, part := range strings.Split(days, ",") {
|
||||||
|
part = strings.TrimSpace(part)
|
||||||
|
if part == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
n, err := strconv.Atoi(part)
|
||||||
|
if err == nil && n == wd {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// startOfDay 返回 t 所在日历日的零点(保持时区一致)。
|
||||||
|
func startOfDay(t time.Time) time.Time {
|
||||||
|
y, m, d := t.Date()
|
||||||
|
return time.Date(y, m, d, 0, 0, 0, 0, t.Location())
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultFeatureControl 返回某功能的默认配置(尚未落库时的行为)。
|
||||||
|
// 提问与投票默认开启(与历史行为一致);私聊默认关闭,沿用 users.allow_chat 的默认值,
|
||||||
|
// 避免历史账号在功能上线后被动开启私聊。
|
||||||
|
func DefaultFeatureControl(userID uint, feature string) *FeatureControl {
|
||||||
|
return &FeatureControl{
|
||||||
|
UserID: userID,
|
||||||
|
Feature: feature,
|
||||||
|
Enabled: feature != FeatureChat,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// FeatureStateOf 便捷入口:读取某用户某功能在当前的综合状态。
|
||||||
|
// 查询失败或无存储时回退到默认配置,保证单个依赖表异常不会让整站功能不可用。
|
||||||
|
func FeatureStateOf(ctx context.Context, userID uint, feature string) FeatureState {
|
||||||
|
if FeatureControls == nil {
|
||||||
|
return DefaultFeatureControl(userID, feature).Evaluate(time.Now())
|
||||||
|
}
|
||||||
|
fc, err := FeatureControls.Get(ctx, userID, feature)
|
||||||
|
if err != nil {
|
||||||
|
logrus.WithContext(ctx).WithError(err).Errorf("Failed to get feature control %q of user %d", feature, userID)
|
||||||
|
return DefaultFeatureControl(userID, feature).Evaluate(time.Now())
|
||||||
|
}
|
||||||
|
return fc.Evaluate(time.Now())
|
||||||
|
}
|
||||||
|
|
||||||
|
// FeatureOpen 便捷入口:某用户某功能当前是否可用。
|
||||||
|
func FeatureOpen(ctx context.Context, userID uint, feature string) bool {
|
||||||
|
return FeatureStateOf(ctx, userID, feature).Open
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsValidFeature 判断功能标识是否合法(防越权写入未知功能)。
|
||||||
|
func IsValidFeature(feature string) bool {
|
||||||
|
for _, k := range FeatureKeys {
|
||||||
|
if k == feature {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *featureControls) Get(ctx context.Context, userID uint, feature string) (*FeatureControl, error) {
|
||||||
|
var fc FeatureControl
|
||||||
|
err := db.WithContext(ctx).Where("user_id = ? AND feature = ?", userID, feature).First(&fc).Error
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return DefaultFeatureControl(userID, feature), nil
|
||||||
|
}
|
||||||
|
return nil, errors.Wrap(err, "get feature control")
|
||||||
|
}
|
||||||
|
return &fc, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *featureControls) ListByUserID(ctx context.Context, userID uint) ([]*FeatureControl, error) {
|
||||||
|
var list []*FeatureControl
|
||||||
|
err := db.WithContext(ctx).
|
||||||
|
Where("user_id = ?", userID).
|
||||||
|
Order("feature ASC").
|
||||||
|
Find(&list).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "list feature controls by user id")
|
||||||
|
}
|
||||||
|
return list, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *featureControls) ListByUserIDs(ctx context.Context, userIDs []uint, feature string) (map[uint]*FeatureControl, error) {
|
||||||
|
result := make(map[uint]*FeatureControl, len(userIDs))
|
||||||
|
if len(userIDs) == 0 {
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
var list []*FeatureControl
|
||||||
|
if err := db.WithContext(ctx).
|
||||||
|
Where("user_id IN ? AND feature = ?", userIDs, feature).
|
||||||
|
Find(&list).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "list feature controls by user ids")
|
||||||
|
}
|
||||||
|
for _, fc := range list {
|
||||||
|
result[fc.UserID] = fc
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdateFeatureControlOptions struct {
|
||||||
|
Enabled bool
|
||||||
|
OpenAt *time.Time
|
||||||
|
CloseAt *time.Time
|
||||||
|
ScheduleDays string
|
||||||
|
ScheduleStart string
|
||||||
|
ScheduleEnd string
|
||||||
|
QuotaLimit int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save 写入功能配置。使用 ON CONFLICT 幂等写入,并显式列出更新列,
|
||||||
|
// 避免把 quota_count(已收集数量)误重置为 0。
|
||||||
|
func (db *featureControls) Save(ctx context.Context, userID uint, feature string, opts UpdateFeatureControlOptions) error {
|
||||||
|
now := time.Now()
|
||||||
|
fc := &FeatureControl{
|
||||||
|
// UpdatedAt 显式写入(gorm 的 on-conflict 更新列会用到);CreatedAt 留零值由 gorm 自动填充
|
||||||
|
Model: dbutil.Model{UpdatedAt: now},
|
||||||
|
UserID: userID,
|
||||||
|
Feature: feature,
|
||||||
|
Enabled: opts.Enabled,
|
||||||
|
OpenAt: opts.OpenAt,
|
||||||
|
CloseAt: opts.CloseAt,
|
||||||
|
ScheduleDays: opts.ScheduleDays,
|
||||||
|
ScheduleStart: opts.ScheduleStart,
|
||||||
|
ScheduleEnd: opts.ScheduleEnd,
|
||||||
|
QuotaLimit: opts.QuotaLimit,
|
||||||
|
}
|
||||||
|
err := db.WithContext(ctx).Clauses(clause.OnConflict{
|
||||||
|
Columns: []clause.Column{{Name: "user_id"}, {Name: "feature"}},
|
||||||
|
DoUpdates: clause.AssignmentColumns([]string{
|
||||||
|
"enabled", "open_at", "close_at",
|
||||||
|
"schedule_days", "schedule_start", "schedule_end",
|
||||||
|
"quota_limit", "updated_at",
|
||||||
|
}),
|
||||||
|
}).Create(fc).Error
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "save feature control")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResetQuota 清零收集计数并记录重置时间。无记录时创建一条(沿用该功能的默认开关值)。
|
||||||
|
func (db *featureControls) ResetQuota(ctx context.Context, userID uint, feature string) error {
|
||||||
|
now := time.Now()
|
||||||
|
res := db.WithContext(ctx).Model(&FeatureControl{}).
|
||||||
|
Where("user_id = ? AND feature = ?", userID, feature).
|
||||||
|
Updates(map[string]interface{}{
|
||||||
|
"quota_count": 0,
|
||||||
|
"quota_reset_at": now,
|
||||||
|
"updated_at": now,
|
||||||
|
})
|
||||||
|
if res.Error != nil {
|
||||||
|
return errors.Wrap(res.Error, "reset feature quota")
|
||||||
|
}
|
||||||
|
if res.RowsAffected > 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// 尚无记录:按默认配置创建(提问/投票默认开启,私聊默认关闭)
|
||||||
|
fc := DefaultFeatureControl(userID, feature)
|
||||||
|
fc.QuotaResetAt = &now
|
||||||
|
if err := db.WithContext(ctx).
|
||||||
|
Clauses(clause.OnConflict{DoNothing: true}).
|
||||||
|
Create(fc).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "create feature control on reset quota")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// IncrementQuota 累加收集计数(delta 可为负,用于删除内容时回退计数)。
|
||||||
|
// 负 delta 不会把计数减到 0 以下(WHERE quota_count > 0),避免误删历史内容导致负计数。
|
||||||
|
func (db *featureControls) IncrementQuota(ctx context.Context, userID uint, feature string, delta int64) error {
|
||||||
|
if delta == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
now := time.Now()
|
||||||
|
q := db.WithContext(ctx).Model(&FeatureControl{}).
|
||||||
|
Where("user_id = ? AND feature = ?", userID, feature)
|
||||||
|
if delta < 0 {
|
||||||
|
q = q.Where("quota_count > 0")
|
||||||
|
}
|
||||||
|
res := q.Updates(map[string]interface{}{
|
||||||
|
"quota_count": gorm.Expr("quota_count + ?", delta),
|
||||||
|
"updated_at": now,
|
||||||
|
})
|
||||||
|
if res.Error != nil {
|
||||||
|
return errors.Wrap(res.Error, "increment feature quota")
|
||||||
|
}
|
||||||
|
if res.RowsAffected > 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 尚无配置行:建一条并把计数初始化为本条(负数按 0 起步,不产生负计数)。
|
||||||
|
fc := DefaultFeatureControl(userID, feature)
|
||||||
|
if delta > 0 {
|
||||||
|
fc.QuotaCount = delta
|
||||||
|
}
|
||||||
|
fc.QuotaResetAt = &now
|
||||||
|
created := db.WithContext(ctx).
|
||||||
|
Clauses(clause.OnConflict{DoNothing: true}).
|
||||||
|
Create(fc)
|
||||||
|
if created.Error != nil {
|
||||||
|
return errors.Wrap(created.Error, "create feature control on increment quota")
|
||||||
|
}
|
||||||
|
if created.RowsAffected > 0 || delta <= 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// 并发下配置行可能刚被其它请求创建:补一次累加,保证计数不丢。
|
||||||
|
retry := db.WithContext(ctx).Model(&FeatureControl{}).
|
||||||
|
Where("user_id = ? AND feature = ?", userID, feature).
|
||||||
|
Updates(map[string]interface{}{
|
||||||
|
"quota_count": gorm.Expr("quota_count + ?", delta),
|
||||||
|
"updated_at": time.Now(),
|
||||||
|
})
|
||||||
|
if retry.Error != nil {
|
||||||
|
return errors.Wrap(retry.Error, "increment feature quota (retry)")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// backfillFeatureControls 为尚未初始化的历史账号补齐功能配置行。
|
||||||
|
//
|
||||||
|
// 背景:私聊开关此前落在 users.allow_chat,提问/投票则一直默认开启。功能上线后若没有
|
||||||
|
// 对应的配置行,Get 会回退到默认值(私聊默认关闭),导致已开启私聊的历史账号被静默关闭。
|
||||||
|
// 因此在 AutoMigrate 之后按 users.allow_chat 回填私聊开关,其余功能按"开启"回填。
|
||||||
|
//
|
||||||
|
// 幂等:每轮只挑出仍缺配置行的账号,写完后进入下一轮,直到没有遗漏。
|
||||||
|
// 分批 + ON CONFLICT DO NOTHING,避免"边插入边查同一张表"在不同数据库上的差异行为,
|
||||||
|
// 并保证并发启动(多实例同时启动)时不会重复插入。
|
||||||
|
func backfillFeatureControls(db *gorm.DB) error {
|
||||||
|
// backfillBatchSize 每轮处理的账号数,控制单次事务体积与内存占用。
|
||||||
|
const backfillBatchSize = 500
|
||||||
|
|
||||||
|
type backfillRow struct {
|
||||||
|
UserID uint
|
||||||
|
AllowChat bool
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, feature := range FeatureKeys {
|
||||||
|
defaultEnabled := feature != FeatureChat
|
||||||
|
created := int64(0)
|
||||||
|
|
||||||
|
for {
|
||||||
|
var rows []backfillRow
|
||||||
|
err := db.Table("users").
|
||||||
|
Select("users.id AS user_id, users.allow_chat AS allow_chat").
|
||||||
|
Joins("LEFT JOIN feature_controls fc ON fc.user_id = users.id AND fc.feature = ?", feature).
|
||||||
|
Where("users.deleted_at IS NULL AND fc.id IS NULL").
|
||||||
|
Limit(backfillBatchSize).
|
||||||
|
Scan(&rows).Error
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "query users without feature control %s", feature)
|
||||||
|
}
|
||||||
|
if len(rows) == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
batch := make([]FeatureControl, 0, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
enabled := defaultEnabled
|
||||||
|
if feature == FeatureChat {
|
||||||
|
enabled = r.AllowChat
|
||||||
|
}
|
||||||
|
batch = append(batch, FeatureControl{
|
||||||
|
UserID: r.UserID,
|
||||||
|
Feature: feature,
|
||||||
|
Enabled: enabled,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
res := db.Clauses(clause.OnConflict{DoNothing: true}).Create(&batch)
|
||||||
|
if res.Error != nil {
|
||||||
|
return errors.Wrapf(res.Error, "backfill feature controls: %s", feature)
|
||||||
|
}
|
||||||
|
// 本轮没有任何新行落库:说明并发实例已写完或数据异常,停止循环避免死循环。
|
||||||
|
if res.RowsAffected == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
created += res.RowsAffected
|
||||||
|
if len(rows) < backfillBatchSize {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if created > 0 {
|
||||||
|
logrus.WithField("feature", feature).
|
||||||
|
Infof("功能开关初始化:为 %d 个历史账号补齐配置", created)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// reconcileLegacyChatEnabled 修复旧版 backfill 写入的私聊错误开关。
|
||||||
|
//
|
||||||
|
// 背景:早期版本 FeatureControl.Enabled 带 gorm:"default:true" 标签,backfill 为
|
||||||
|
// allow_chat=false 的用户补私聊行时,false 被 GORM 替换为默认值 true,导致私聊被被动开启;
|
||||||
|
// 且 UpdateChatSettings 会把 users.allow_chat 反向同步为 true,形成持久化。
|
||||||
|
//
|
||||||
|
// 纠偏条件(必须同时满足,只命中"纯 backfill 默认行",绝不碰箱主配置过的行):
|
||||||
|
// - feature = 'chat' 且 enabled = true;
|
||||||
|
// - 对应 users.allow_chat = false(箱主从未在面板开启私聊——面板开启会同步 allow_chat=true);
|
||||||
|
// - 该行无任何自定义配置(open_at / close_at 为空、quota_limit = 0、循环定时为空);
|
||||||
|
// - updated_at <= created_at(从未被面板保存过,updated_at 未变化)。
|
||||||
|
//
|
||||||
|
// 满足条件即复位 feature_controls.enabled = false,并同步 users.allow_chat = false。
|
||||||
|
// 幂等:每轮只处理仍满足条件的行,直到没有遗漏;已复位/已配置的行不会重复命中。
|
||||||
|
func reconcileLegacyChatEnabled(db *gorm.DB) error {
|
||||||
|
// reconcileBatchSize 每轮处理的账号数,控制单次事务体积。
|
||||||
|
const reconcileBatchSize = 500
|
||||||
|
|
||||||
|
// pureDefaultFilterFC / pureDefaultFilterPlain 只匹配纯默认配置的私聊行
|
||||||
|
// (无一次性窗口/循环定时/定量上限)。两者仅列前缀不同:
|
||||||
|
// - FC 版带 "fc." 前缀,用于 SELECT(feature_controls fc 别名场景);
|
||||||
|
// - 纯版不带前缀,用于 UPDATE(GORM 不会为 UPDATE 自动加别名,带前缀会报
|
||||||
|
// missing FROM-clause entry for table "fc")。
|
||||||
|
// 同时兼容旧行 schedule 列为 NULL 与新行空串两种情况。
|
||||||
|
pureDefaultFilterFC := "fc.open_at IS NULL AND fc.close_at IS NULL AND fc.quota_limit = 0" +
|
||||||
|
" AND (fc.schedule_days IS NULL OR fc.schedule_days = '')" +
|
||||||
|
" AND (fc.schedule_start IS NULL OR fc.schedule_start = '')" +
|
||||||
|
" AND (fc.schedule_end IS NULL OR fc.schedule_end = '')"
|
||||||
|
pureDefaultFilterPlain := "open_at IS NULL AND close_at IS NULL AND quota_limit = 0" +
|
||||||
|
" AND (schedule_days IS NULL OR schedule_days = '')" +
|
||||||
|
" AND (schedule_start IS NULL OR schedule_start = '')" +
|
||||||
|
" AND (schedule_end IS NULL OR schedule_end = '')"
|
||||||
|
|
||||||
|
fixed := int64(0)
|
||||||
|
for {
|
||||||
|
var rows []struct{ UserID uint }
|
||||||
|
err := db.Table("feature_controls fc").
|
||||||
|
Select("fc.user_id").
|
||||||
|
Joins("JOIN users u ON u.id = fc.user_id AND u.allow_chat = false").
|
||||||
|
Where("fc.feature = ? AND fc.enabled = true", FeatureChat).
|
||||||
|
Where(pureDefaultFilterFC).
|
||||||
|
Where("fc.updated_at <= fc.created_at").
|
||||||
|
Where("fc.deleted_at IS NULL AND u.deleted_at IS NULL").
|
||||||
|
Limit(reconcileBatchSize).
|
||||||
|
Scan(&rows).Error
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "query legacy chat rows to reconcile")
|
||||||
|
}
|
||||||
|
if len(rows) == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
userIDs := make([]uint, 0, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
userIDs = append(userIDs, r.UserID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 复位 feature_controls.enabled(同一批用户 + 同样的纯默认条件,避免误伤并发新增配置)。
|
||||||
|
res := db.Table("feature_controls").
|
||||||
|
Where("user_id IN ? AND feature = ? AND enabled = true", userIDs, FeatureChat).
|
||||||
|
Where(pureDefaultFilterPlain).
|
||||||
|
Where("deleted_at IS NULL").
|
||||||
|
Update("enabled", false)
|
||||||
|
if res.Error != nil {
|
||||||
|
return errors.Wrap(res.Error, "reset legacy chat enabled")
|
||||||
|
}
|
||||||
|
fixed += res.RowsAffected
|
||||||
|
|
||||||
|
// 同步 users.allow_chat,保证两处一致。
|
||||||
|
if err := db.Table("users").
|
||||||
|
Where("id IN ? AND allow_chat = true", userIDs).
|
||||||
|
Where("deleted_at IS NULL").
|
||||||
|
Update("allow_chat", false).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "sync legacy users.allow_chat")
|
||||||
|
}
|
||||||
|
|
||||||
|
if int64(len(rows)) < reconcileBatchSize {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if fixed > 0 {
|
||||||
|
logrus.WithField("count", fixed).
|
||||||
|
Warn("私聊开关纠偏:旧版数据把未开启私聊的账号置为开启,已复位为关闭")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// normalizeChatQuota 清零私聊行上历史残留的收集上限与计数。
|
||||||
|
//
|
||||||
|
// 背景:私聊不提供收集上限能力(会话是双向对话,限制「新建会话数」意义不大),
|
||||||
|
// UI 已隐藏该字段、保存时强制清零;此处在启动期做一次性兜底,把旧版本
|
||||||
|
// 设置过的私聊上限/计数统一清零,避免达到残留上限后私聊「莫名关闭」。
|
||||||
|
// 幂等:重复执行不产生任何变更,失败由调用方告警(不阻断启动)。
|
||||||
|
func normalizeChatQuota(db *gorm.DB) error {
|
||||||
|
res := db.Model(&FeatureControl{}).
|
||||||
|
Where("feature = ? AND (quota_limit > 0 OR quota_count > 0)", FeatureChat).
|
||||||
|
Updates(map[string]interface{}{"quota_limit": 0, "quota_count": 0})
|
||||||
|
if res.Error != nil {
|
||||||
|
return errors.Wrap(res.Error, "normalize chat feature quota")
|
||||||
|
}
|
||||||
|
if res.RowsAffected > 0 {
|
||||||
|
logrus.WithField("count", res.RowsAffected).
|
||||||
|
Info("私聊收集上限已下线:已清零历史残留的私聊收集上限与计数")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,341 @@
|
|||||||
|
// 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 db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestFeatureControlEvaluate 覆盖开关 / 定时 / 定量三类控制的组合与优先级。
|
||||||
|
// 纯逻辑测试,不依赖外部数据库。
|
||||||
|
func TestFeatureControlEvaluate(t *testing.T) {
|
||||||
|
now := time.Date(2026, 8, 31, 12, 0, 0, 0, time.UTC)
|
||||||
|
past := now.Add(-time.Hour)
|
||||||
|
future := now.Add(time.Hour)
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
fc FeatureControl
|
||||||
|
wantOk bool
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "开启且无限制",
|
||||||
|
fc: FeatureControl{Enabled: true},
|
||||||
|
wantOk: true, want: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "手动关闭优先于其它条件",
|
||||||
|
fc: FeatureControl{Enabled: false, OpenAt: &past, CloseAt: &future, QuotaLimit: 1},
|
||||||
|
wantOk: false, want: FeatureReasonDisabled,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "未到开放时间",
|
||||||
|
fc: FeatureControl{Enabled: true, OpenAt: &future},
|
||||||
|
wantOk: false, want: FeatureReasonNotStarted,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "开放时间已过但功能仍开启",
|
||||||
|
fc: FeatureControl{Enabled: true, OpenAt: &past},
|
||||||
|
wantOk: true, want: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "已过关闭时间",
|
||||||
|
fc: FeatureControl{Enabled: true, OpenAt: &past, CloseAt: &past},
|
||||||
|
wantOk: false, want: FeatureReasonEnded,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "刚好到达关闭时间即关闭",
|
||||||
|
fc: FeatureControl{Enabled: true, CloseAt: &now},
|
||||||
|
wantOk: false, want: FeatureReasonEnded,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "未到收集上限",
|
||||||
|
fc: FeatureControl{Enabled: true, QuotaLimit: 10, QuotaCount: 9},
|
||||||
|
wantOk: true, want: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "恰好达到收集上限",
|
||||||
|
fc: FeatureControl{Enabled: true, QuotaLimit: 10, QuotaCount: 10},
|
||||||
|
wantOk: false, want: FeatureReasonQuotaReached,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "超过收集上限",
|
||||||
|
fc: FeatureControl{Enabled: true, QuotaLimit: 10, QuotaCount: 12},
|
||||||
|
wantOk: false, want: FeatureReasonQuotaReached,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "上限为 0 表示不限制",
|
||||||
|
fc: FeatureControl{Enabled: true, QuotaLimit: 0, QuotaCount: 9999},
|
||||||
|
wantOk: true, want: "",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
st := tt.fc.Evaluate(now)
|
||||||
|
if st.Open != tt.wantOk || st.Reason != tt.want {
|
||||||
|
t.Fatalf("Evaluate() = (open=%v, reason=%q), want (open=%v, reason=%q)",
|
||||||
|
st.Open, st.Reason, tt.wantOk, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestDefaultFeatureControl 私聊默认关闭(沿用 users.allow_chat 的历史默认),
|
||||||
|
// 提问与投票默认开启,保证功能上线不改变既有行为。
|
||||||
|
func TestDefaultFeatureControl(t *testing.T) {
|
||||||
|
cases := map[string]bool{
|
||||||
|
FeatureQuestion: true,
|
||||||
|
FeatureChat: false,
|
||||||
|
FeatureVote: true,
|
||||||
|
}
|
||||||
|
for feature, want := range cases {
|
||||||
|
if got := DefaultFeatureControl(1, feature).Enabled; got != want {
|
||||||
|
t.Fatalf("DefaultFeatureControl(%q).Enabled = %v, want %v", feature, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIsValidFeature(t *testing.T) {
|
||||||
|
for _, k := range FeatureKeys {
|
||||||
|
if !IsValidFeature(k) {
|
||||||
|
t.Fatalf("IsValidFeature(%q) = false, want true", k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, k := range []string{"", "chat ", "CHAT", "poll", "messages"} {
|
||||||
|
if IsValidFeature(k) {
|
||||||
|
t.Fatalf("IsValidFeature(%q) = true, want false", k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFeatureControlSchedule 覆盖循环定时(每周开放日 + 每日时间段)的 Evaluate 判定。
|
||||||
|
func TestFeatureControlSchedule(t *testing.T) {
|
||||||
|
// 固定在一个周四 12:00(time.Weekday: 0=周日…4=周四…6=周六)
|
||||||
|
now := time.Date(2026, 9, 3, 12, 0, 0, 0, time.UTC) // 2026-09-03 是周四
|
||||||
|
thursday := int(now.Weekday())
|
||||||
|
if thursday != 4 {
|
||||||
|
t.Fatalf("test precondition: 2026-09-03 should be Thursday, got %d", thursday)
|
||||||
|
}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
fc FeatureControl
|
||||||
|
wantOk bool
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "无循环定时不影响判定",
|
||||||
|
fc: FeatureControl{Enabled: true},
|
||||||
|
wantOk: true, want: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "每日时间段内开放",
|
||||||
|
fc: FeatureControl{Enabled: true, ScheduleStart: "09:00", ScheduleEnd: "18:00"},
|
||||||
|
wantOk: true, want: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "每日时间段开始前关闭",
|
||||||
|
fc: FeatureControl{Enabled: true, ScheduleStart: "13:00", ScheduleEnd: "18:00"},
|
||||||
|
wantOk: false, want: FeatureReasonNotStarted,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "每日时间段结束后关闭(次日会再开)",
|
||||||
|
fc: FeatureControl{Enabled: true, ScheduleStart: "09:00", ScheduleEnd: "11:00"},
|
||||||
|
wantOk: false, want: FeatureReasonNotStarted,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "当天不在开放日关闭(未来还会再开)",
|
||||||
|
fc: FeatureControl{Enabled: true, ScheduleDays: "0", ScheduleStart: "09:00", ScheduleEnd: "18:00"},
|
||||||
|
wantOk: false, want: FeatureReasonNotStarted,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "只设开放日(不设时间)表示全天",
|
||||||
|
fc: FeatureControl{Enabled: true, ScheduleDays: "4"},
|
||||||
|
wantOk: true, want: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "只设时间(不设开放日)表示每天该时段",
|
||||||
|
fc: FeatureControl{Enabled: true, ScheduleStart: "09:00", ScheduleEnd: "18:00"},
|
||||||
|
wantOk: true, want: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "开放日与时间段组合:非开放日关闭",
|
||||||
|
fc: FeatureControl{Enabled: true, ScheduleDays: "1,3,5", ScheduleStart: "09:00", ScheduleEnd: "18:00"},
|
||||||
|
wantOk: false, want: FeatureReasonNotStarted, // 周四不在 1,3,5 中
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "开放日与时间段组合:开放日+时段内开放",
|
||||||
|
fc: FeatureControl{Enabled: true, ScheduleDays: "2,4", ScheduleStart: "09:00", ScheduleEnd: "18:00"},
|
||||||
|
wantOk: true, want: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "循环定时达到收集上限",
|
||||||
|
fc: FeatureControl{Enabled: true, ScheduleDays: "4", ScheduleStart: "09:00", ScheduleEnd: "18:00", QuotaLimit: 5, QuotaCount: 5},
|
||||||
|
wantOk: false, want: FeatureReasonQuotaReached,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "手动关闭优先于循环定时",
|
||||||
|
fc: FeatureControl{Enabled: false, ScheduleDays: "4", ScheduleStart: "09:00", ScheduleEnd: "18:00"},
|
||||||
|
wantOk: false, want: FeatureReasonDisabled,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "一次性窗口与循环定时叠加:窗口内+时段内开放",
|
||||||
|
fc: FeatureControl{Enabled: true, OpenAt: &[]time.Time{now.Add(-time.Hour)}[0], CloseAt: &[]time.Time{now.Add(24 * time.Hour)}[0], ScheduleStart: "09:00", ScheduleEnd: "18:00"},
|
||||||
|
wantOk: true, want: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "一次性窗口已关闭后循环定时不再生效(硬边界)",
|
||||||
|
fc: FeatureControl{Enabled: true, OpenAt: &[]time.Time{now.Add(-48 * time.Hour)}[0], CloseAt: &[]time.Time{now.Add(-24 * time.Hour)}[0], ScheduleDays: "4", ScheduleStart: "09:00", ScheduleEnd: "18:00"},
|
||||||
|
wantOk: false, want: FeatureReasonEnded,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "一次性窗口已关闭且无循环定时",
|
||||||
|
fc: FeatureControl{Enabled: true, OpenAt: &[]time.Time{now.Add(-48 * time.Hour)}[0], CloseAt: &[]time.Time{now.Add(-24 * time.Hour)}[0]},
|
||||||
|
wantOk: false, want: FeatureReasonEnded,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
st := tt.fc.Evaluate(now)
|
||||||
|
if st.Open != tt.wantOk || st.Reason != tt.want {
|
||||||
|
t.Fatalf("Evaluate() = (open=%v, reason=%q), want (open=%v, reason=%q)",
|
||||||
|
st.Open, st.Reason, tt.wantOk, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFeatureControlNextOpenAtLastCloseAt 覆盖「下次开放时间 / 上次关闭时间」的计算。
|
||||||
|
func TestFeatureControlNextOpenAtLastCloseAt(t *testing.T) {
|
||||||
|
// 2026-09-03 12:00 UTC(周四)
|
||||||
|
now := time.Date(2026, 9, 3, 12, 0, 0, 0, time.UTC)
|
||||||
|
|
||||||
|
t.Run("循环定时与一次性窗口交集:当天时段内更晚开放", func(t *testing.T) {
|
||||||
|
// now=周四 12:00,循环每天 09:00-18:00;一次性开放时间 = 今天 14:00 → 今天 14:00 开放
|
||||||
|
openAt := time.Date(2026, 9, 3, 14, 0, 0, 0, time.UTC)
|
||||||
|
closeAt := time.Date(2026, 9, 3, 20, 0, 0, 0, time.UTC)
|
||||||
|
fc := FeatureControl{Enabled: true, OpenAt: &openAt, CloseAt: &closeAt,
|
||||||
|
ScheduleStart: "09:00", ScheduleEnd: "18:00"}
|
||||||
|
st := fc.Evaluate(now)
|
||||||
|
if st.Reason != FeatureReasonNotStarted {
|
||||||
|
t.Fatalf("reason = %q, want not_started", st.Reason)
|
||||||
|
}
|
||||||
|
if st.NextOpenAt == nil || !st.NextOpenAt.Equal(openAt) {
|
||||||
|
t.Fatalf("NextOpenAt = %v, want %v(今天 14:00)", st.NextOpenAt, openAt)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("一次性窗口在循环时段结束后才开放则当天不开放", func(t *testing.T) {
|
||||||
|
// 一次性开放时间 20:00 晚于循环时段结束 18:00 → 今天无有效窗口,下次开放 = 明天 09:00
|
||||||
|
openAt := time.Date(2026, 9, 3, 20, 0, 0, 0, time.UTC)
|
||||||
|
closeAt := time.Date(2026, 9, 5, 20, 0, 0, 0, time.UTC)
|
||||||
|
fc := FeatureControl{Enabled: true, OpenAt: &openAt, CloseAt: &closeAt,
|
||||||
|
ScheduleStart: "09:00", ScheduleEnd: "18:00"}
|
||||||
|
st := fc.Evaluate(now)
|
||||||
|
if st.Reason != FeatureReasonNotStarted {
|
||||||
|
t.Fatalf("reason = %q, want not_started", st.Reason)
|
||||||
|
}
|
||||||
|
wantNext := time.Date(2026, 9, 4, 9, 0, 0, 0, time.UTC)
|
||||||
|
if st.NextOpenAt == nil || !st.NextOpenAt.Equal(wantNext) {
|
||||||
|
t.Fatalf("NextOpenAt = %v, want %v(明天 09:00)", st.NextOpenAt, wantNext)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("手动关闭与定量上限不展示时间信息", func(t *testing.T) {
|
||||||
|
disabled := FeatureControl{Enabled: false, ScheduleStart: "09:00", ScheduleEnd: "18:00"}
|
||||||
|
st := disabled.Evaluate(now)
|
||||||
|
if st.Reason != FeatureReasonDisabled || st.NextOpenAt != nil || st.LastCloseAt != nil {
|
||||||
|
t.Fatalf("disabled state = (reason=%q, next=%v, last=%v), want nil times",
|
||||||
|
st.Reason, st.NextOpenAt, st.LastCloseAt)
|
||||||
|
}
|
||||||
|
quota := FeatureControl{Enabled: true, ScheduleStart: "09:00", ScheduleEnd: "18:00", QuotaLimit: 1, QuotaCount: 1}
|
||||||
|
st = quota.Evaluate(now)
|
||||||
|
if st.Reason != FeatureReasonQuotaReached || st.NextOpenAt != nil || st.LastCloseAt != nil {
|
||||||
|
t.Fatalf("quota state = (reason=%q, next=%v, last=%v), want nil times",
|
||||||
|
st.Reason, st.NextOpenAt, st.LastCloseAt)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("一次性窗口未到开放时间", func(t *testing.T) {
|
||||||
|
openAt := now.Add(2 * time.Hour)
|
||||||
|
closeAt := now.Add(24 * time.Hour)
|
||||||
|
fc := FeatureControl{Enabled: true, OpenAt: &openAt, CloseAt: &closeAt}
|
||||||
|
st := fc.Evaluate(now)
|
||||||
|
if st.NextOpenAt == nil || !st.NextOpenAt.Equal(openAt) {
|
||||||
|
t.Fatalf("NextOpenAt = %v, want %v", st.NextOpenAt, openAt)
|
||||||
|
}
|
||||||
|
if st.LastCloseAt != nil {
|
||||||
|
t.Fatalf("LastCloseAt = %v, want nil(从未开放过)", st.LastCloseAt)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("一次性窗口已结束", func(t *testing.T) {
|
||||||
|
openAt := now.Add(-48 * time.Hour)
|
||||||
|
closeAt := now.Add(-24 * time.Hour)
|
||||||
|
fc := FeatureControl{Enabled: true, OpenAt: &openAt, CloseAt: &closeAt}
|
||||||
|
st := fc.Evaluate(now)
|
||||||
|
if st.NextOpenAt != nil {
|
||||||
|
t.Fatalf("NextOpenAt = %v, want nil(无循环定时,永久关闭)", st.NextOpenAt)
|
||||||
|
}
|
||||||
|
if st.LastCloseAt == nil || !st.LastCloseAt.Equal(closeAt) {
|
||||||
|
t.Fatalf("LastCloseAt = %v, want %v", st.LastCloseAt, closeAt)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("循环定时:每天 09:00-18:00", func(t *testing.T) {
|
||||||
|
fc := FeatureControl{Enabled: true, ScheduleStart: "09:00", ScheduleEnd: "18:00"}
|
||||||
|
// 12:00 在窗口内:下次开放 = 明天 09:00;上次关闭 = 今天 18:00 尚未结束 → 昨天 18:00
|
||||||
|
st := fc.Evaluate(now)
|
||||||
|
if st.Open != true {
|
||||||
|
t.Fatalf("should be open, got reason=%q", st.Reason)
|
||||||
|
}
|
||||||
|
wantNext := time.Date(2026, 9, 4, 9, 0, 0, 0, time.UTC)
|
||||||
|
if st.NextOpenAt == nil || !st.NextOpenAt.Equal(wantNext) {
|
||||||
|
t.Fatalf("NextOpenAt = %v, want %v", st.NextOpenAt, wantNext)
|
||||||
|
}
|
||||||
|
wantLast := time.Date(2026, 9, 2, 18, 0, 0, 0, time.UTC)
|
||||||
|
if st.LastCloseAt == nil || !st.LastCloseAt.Equal(wantLast) {
|
||||||
|
t.Fatalf("LastCloseAt = %v, want %v", st.LastCloseAt, wantLast)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("循环定时:18:00 已过", func(t *testing.T) {
|
||||||
|
evening := time.Date(2026, 9, 3, 20, 0, 0, 0, time.UTC)
|
||||||
|
fc := FeatureControl{Enabled: true, ScheduleStart: "09:00", ScheduleEnd: "18:00"}
|
||||||
|
st := fc.Evaluate(evening)
|
||||||
|
if st.Open {
|
||||||
|
t.Fatal("should be closed after daily end")
|
||||||
|
}
|
||||||
|
wantNext := time.Date(2026, 9, 4, 9, 0, 0, 0, time.UTC)
|
||||||
|
if st.NextOpenAt == nil || !st.NextOpenAt.Equal(wantNext) {
|
||||||
|
t.Fatalf("NextOpenAt = %v, want %v", st.NextOpenAt, wantNext)
|
||||||
|
}
|
||||||
|
wantLast := time.Date(2026, 9, 3, 18, 0, 0, 0, time.UTC)
|
||||||
|
if st.LastCloseAt == nil || !st.LastCloseAt.Equal(wantLast) {
|
||||||
|
t.Fatalf("LastCloseAt = %v, want %v", st.LastCloseAt, wantLast)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("循环定时:仅周五开放(今天周四)", func(t *testing.T) {
|
||||||
|
fc := FeatureControl{Enabled: true, ScheduleDays: "5"} // 周五全天
|
||||||
|
st := fc.Evaluate(now)
|
||||||
|
if st.Open {
|
||||||
|
t.Fatal("should be closed on non-scheduled day")
|
||||||
|
}
|
||||||
|
wantNext := time.Date(2026, 9, 4, 0, 0, 0, 0, time.UTC) // 周五零点
|
||||||
|
if st.NextOpenAt == nil || !st.NextOpenAt.Equal(wantNext) {
|
||||||
|
t.Fatalf("NextOpenAt = %v, want %v", st.NextOpenAt, wantNext)
|
||||||
|
}
|
||||||
|
// 全天窗口 [周五 00:00, 周六 00:00),最近一次关闭 = 上周六零点
|
||||||
|
wantLast := time.Date(2026, 8, 29, 0, 0, 0, 0, time.UTC)
|
||||||
|
if st.LastCloseAt == nil || !st.LastCloseAt.Equal(wantLast) {
|
||||||
|
t.Fatalf("LastCloseAt = %v, want %v", st.LastCloseAt, wantLast)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/clause"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/dbutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MaxFollowUpCount 每条提问允许的最大追问次数(防滥用)。
|
||||||
|
// 提问者被回答后,用 token(或登录账号)继续追问,达到上限后不可再追问。
|
||||||
|
const MaxFollowUpCount = 3
|
||||||
|
|
||||||
|
// 追问相关错误(供 handler 区分处理,避免把业务错误当 500)
|
||||||
|
var (
|
||||||
|
// ErrFollowUpLimitReached 追问次数已达上限
|
||||||
|
ErrFollowUpLimitReached = errors.New("follow up limit reached")
|
||||||
|
// ErrFollowUpNotFound 追问不存在或不属于该问题
|
||||||
|
ErrFollowUpNotFound = errors.New("follow up not found")
|
||||||
|
// ErrFollowUpAlreadyAnswered 追问已被回答(禁止覆盖)
|
||||||
|
ErrFollowUpAlreadyAnswered = errors.New("follow up already answered")
|
||||||
|
)
|
||||||
|
|
||||||
|
var FollowUps FollowUpsStore
|
||||||
|
|
||||||
|
type FollowUpsStore interface {
|
||||||
|
// CreateIfBelowLimit 原子创建追问:仅当该问题追问次数未达上限时创建。
|
||||||
|
// 返回 created=false 且 err==ErrFollowUpLimitReached 表示已达上限。
|
||||||
|
// 通过事务内锁定问题行,串行化同一问题的并发追问,消除 count-then-create 竞态。
|
||||||
|
CreateIfBelowLimit(ctx context.Context, opts CreateFollowUpOptions) (created bool, err error)
|
||||||
|
GetByQuestionID(ctx context.Context, questionID uint) ([]*FollowUp, error)
|
||||||
|
// GetLatestByQuestionID 返回某条提问最新的一条追问;无追问时返回 (nil, nil)。
|
||||||
|
GetLatestByQuestionID(ctx context.Context, questionID uint) (*FollowUp, error)
|
||||||
|
// GetByQuestionIDs 批量获取多个提问的追问,按 question_id 分组返回。
|
||||||
|
// 用于账号导出等场景,将 N 次单题查询合并为 1 次 IN 查询,避免 N+1。
|
||||||
|
GetByQuestionIDs(ctx context.Context, questionIDs []uint) (map[uint][]*FollowUp, error)
|
||||||
|
CountByQuestionID(ctx context.Context, questionID uint) (int64, error)
|
||||||
|
// AnswerByID 回答某条追问;questionID 用于防止越权(必须属于该问题)。
|
||||||
|
// 仅允许回答尚未回答的追问(answer 为空),已回答的返回 ErrFollowUpAlreadyAnswered,
|
||||||
|
// 不存在/不属于该问题返回 ErrFollowUpNotFound。
|
||||||
|
AnswerByID(ctx context.Context, questionID uint, id uint, answer string) error
|
||||||
|
// UpdateAnswerByID 修改某条追问的回答内容(带 question_id 条件防止越权),
|
||||||
|
// 与 AnswerByID 不同,此处允许覆盖已回答的追问(供主人修改回复使用)。
|
||||||
|
// 不存在/不属于该问题返回 ErrFollowUpNotFound。
|
||||||
|
UpdateAnswerByID(ctx context.Context, questionID uint, id uint, answer string) error
|
||||||
|
// DeleteByQuestionID 删除某条提问时级联清理其全部追问(软删除,与提问保持一致)。
|
||||||
|
DeleteByQuestionID(ctx context.Context, questionID uint) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFollowUpsStore(db *gorm.DB) FollowUpsStore {
|
||||||
|
return &followUps{db}
|
||||||
|
}
|
||||||
|
|
||||||
|
type followUps struct {
|
||||||
|
*gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
// FollowUp 表示对某条提问的一轮追问。
|
||||||
|
type FollowUp struct {
|
||||||
|
dbutil.Model
|
||||||
|
QuestionID uint `gorm:"index:idx_follow_up_question" json:"question_id"`
|
||||||
|
Content string `gorm:"type:text" json:"content"`
|
||||||
|
Answer string `gorm:"type:text" json:"answer"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateFollowUpOptions struct {
|
||||||
|
QuestionID uint
|
||||||
|
Content string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *followUps) CreateIfBelowLimit(ctx context.Context, opts CreateFollowUpOptions) (bool, error) {
|
||||||
|
created := false
|
||||||
|
err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
|
// 锁定问题行,串行化同一问题的并发追问(MySQL/Postgres 均支持 FOR UPDATE)。
|
||||||
|
var q Question
|
||||||
|
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||||
|
Select("id").
|
||||||
|
First(&q, opts.QuestionID).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "lock question for follow up")
|
||||||
|
}
|
||||||
|
|
||||||
|
var count int64
|
||||||
|
if err := tx.Model(&FollowUp{}).
|
||||||
|
Where("question_id = ?", opts.QuestionID).
|
||||||
|
Count(&count).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "count follow ups by question id")
|
||||||
|
}
|
||||||
|
if count >= MaxFollowUpCount {
|
||||||
|
return ErrFollowUpLimitReached
|
||||||
|
}
|
||||||
|
|
||||||
|
f := &FollowUp{
|
||||||
|
QuestionID: opts.QuestionID,
|
||||||
|
Content: opts.Content,
|
||||||
|
}
|
||||||
|
if err := tx.Create(f).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "create follow up")
|
||||||
|
}
|
||||||
|
created = true
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return created, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetByQuestionID 按时间正序返回某条提问的所有追问。
|
||||||
|
func (db *followUps) GetByQuestionID(ctx context.Context, questionID uint) ([]*FollowUp, error) {
|
||||||
|
var followUps []*FollowUp
|
||||||
|
if err := db.WithContext(ctx).
|
||||||
|
Where("question_id = ?", questionID).
|
||||||
|
Order("created_at ASC").
|
||||||
|
Find(&followUps).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get follow ups by question id")
|
||||||
|
}
|
||||||
|
return followUps, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLatestByQuestionID 返回某条提问最新的一条追问(created_at 倒序取首条);
|
||||||
|
// 无追问时返回 (nil, nil)。供发布追问前校验"上一条是否已回复"。
|
||||||
|
func (db *followUps) GetLatestByQuestionID(ctx context.Context, questionID uint) (*FollowUp, error) {
|
||||||
|
var fu FollowUp
|
||||||
|
err := db.WithContext(ctx).
|
||||||
|
Where("question_id = ?", questionID).
|
||||||
|
Order("created_at DESC").
|
||||||
|
Limit(1).
|
||||||
|
First(&fu).Error
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return nil, errors.Wrap(err, "get latest follow up by question id")
|
||||||
|
}
|
||||||
|
return &fu, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetByQuestionIDs 批量获取多个提问的追问,按 question_id 分组返回(解决导出 N+1)。
|
||||||
|
func (db *followUps) GetByQuestionIDs(ctx context.Context, questionIDs []uint) (map[uint][]*FollowUp, error) {
|
||||||
|
result := make(map[uint][]*FollowUp)
|
||||||
|
if len(questionIDs) == 0 {
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
var items []*FollowUp
|
||||||
|
if err := db.WithContext(ctx).
|
||||||
|
Where("question_id IN ?", questionIDs).
|
||||||
|
Order("question_id ASC, created_at ASC").
|
||||||
|
Find(&items).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get follow ups by question ids")
|
||||||
|
}
|
||||||
|
for _, fu := range items {
|
||||||
|
result[fu.QuestionID] = append(result[fu.QuestionID], fu)
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CountByQuestionID 统计某条提问的追问次数,用于限制追问上限。
|
||||||
|
func (db *followUps) CountByQuestionID(ctx context.Context, questionID uint) (int64, error) {
|
||||||
|
var count int64
|
||||||
|
if err := db.WithContext(ctx).
|
||||||
|
Model(&FollowUp{}).
|
||||||
|
Where("question_id = ?", questionID).
|
||||||
|
Count(&count).Error; err != nil {
|
||||||
|
return 0, errors.Wrap(err, "count follow ups by question id")
|
||||||
|
}
|
||||||
|
return count, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AnswerByID 更新某条追问的回答内容(带 question_id 条件防止越权)。
|
||||||
|
// 原子更新条件含 answer=”:已回答的追问不会被覆盖(避免重复提交时邮件/回答被二次写入)。
|
||||||
|
// RowsAffected==0 时再查一次以区分"不存在"与"已回答",返回对应错误。
|
||||||
|
func (db *followUps) AnswerByID(ctx context.Context, questionID uint, id uint, answer string) error {
|
||||||
|
res := db.WithContext(ctx).
|
||||||
|
Model(&FollowUp{}).
|
||||||
|
Where("id = ? AND question_id = ? AND answer = ''", id, questionID).
|
||||||
|
Update("answer", answer)
|
||||||
|
if res.Error != nil {
|
||||||
|
return errors.Wrap(res.Error, "answer follow up")
|
||||||
|
}
|
||||||
|
if res.RowsAffected == 0 {
|
||||||
|
var cnt int64
|
||||||
|
if err := db.WithContext(ctx).
|
||||||
|
Model(&FollowUp{}).
|
||||||
|
Where("id = ? AND question_id = ?", id, questionID).
|
||||||
|
Count(&cnt).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "check follow up existence")
|
||||||
|
}
|
||||||
|
if cnt == 0 {
|
||||||
|
return ErrFollowUpNotFound
|
||||||
|
}
|
||||||
|
return ErrFollowUpAlreadyAnswered
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateAnswerByID 修改某条追问的回答内容(带 question_id 条件防止越权),
|
||||||
|
// 允许覆盖已回答的追问(用于主人修改回复)。不存在/不属于该问题返回 ErrFollowUpNotFound。
|
||||||
|
func (db *followUps) UpdateAnswerByID(ctx context.Context, questionID uint, id uint, answer string) error {
|
||||||
|
res := db.WithContext(ctx).
|
||||||
|
Model(&FollowUp{}).
|
||||||
|
Where("id = ? AND question_id = ?", id, questionID).
|
||||||
|
Update("answer", answer)
|
||||||
|
if res.Error != nil {
|
||||||
|
return errors.Wrap(res.Error, "update follow up answer")
|
||||||
|
}
|
||||||
|
if res.RowsAffected == 0 {
|
||||||
|
return ErrFollowUpNotFound
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteByQuestionID 删除某条提问时级联清理其全部追问(软删除,与提问保持一致)。
|
||||||
|
func (db *followUps) DeleteByQuestionID(ctx context.Context, questionID uint) error {
|
||||||
|
if err := db.WithContext(ctx).Where("question_id = ?", questionID).Delete(&FollowUp{}).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "delete follow ups by question id")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
// Copyright 2023 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 db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/dbutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
// newTestDB returns a test database instance with the cleanup function.
|
||||||
|
func newTestDB(t *testing.T) (*gorm.DB, func(...string) error) {
|
||||||
|
return dbutil.NewTestDB(t, AllTables...)
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/dbutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
var Messages MessageStore
|
||||||
|
|
||||||
|
type MessageStore interface {
|
||||||
|
Create(ctx context.Context, opts CreateMessageOptions) (*Message, error)
|
||||||
|
GetByConversationID(ctx context.Context, conversationID uint, cursor *dbutil.Cursor) ([]*Message, error)
|
||||||
|
// GetFirstMessagesByConversationIDs 批量获取多个会话的第一条消息(解决 N+1 查询)
|
||||||
|
GetFirstMessagesByConversationIDs(ctx context.Context, conversationIDs []uint) (map[uint]string, error)
|
||||||
|
// GetAllByConversationIDs 批量获取多个会话的全部消息(导出用,不分页),按 conversation_id 分组。
|
||||||
|
// 将每个会话原本的 1 次查询合并为 1 次 IN 查询,避免 N+1。
|
||||||
|
GetAllByConversationIDs(ctx context.Context, conversationIDs []uint) (map[uint][]*Message, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMessageStore(db *gorm.DB) MessageStore {
|
||||||
|
return &messages{db}
|
||||||
|
}
|
||||||
|
|
||||||
|
type messages struct {
|
||||||
|
*gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
type Message struct {
|
||||||
|
dbutil.Model
|
||||||
|
ConversationID uint `gorm:"index:idx_message_conversation" json:"conversation_id"`
|
||||||
|
SenderID uint `json:"sender_id"`
|
||||||
|
Content string `gorm:"type:text" json:"content"`
|
||||||
|
Read bool `gorm:"default:false" json:"read"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateMessageOptions struct {
|
||||||
|
ConversationID uint
|
||||||
|
SenderID uint
|
||||||
|
Content string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *messages) Create(ctx context.Context, opts CreateMessageOptions) (*Message, error) {
|
||||||
|
msg := &Message{
|
||||||
|
ConversationID: opts.ConversationID,
|
||||||
|
SenderID: opts.SenderID,
|
||||||
|
Content: opts.Content,
|
||||||
|
}
|
||||||
|
if err := db.WithContext(ctx).Create(msg).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "create message")
|
||||||
|
}
|
||||||
|
return msg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *messages) GetByConversationID(ctx context.Context, conversationID uint, cursor *dbutil.Cursor) ([]*Message, error) {
|
||||||
|
var messages []*Message
|
||||||
|
q := db.WithContext(ctx).Where("conversation_id = ?", conversationID)
|
||||||
|
|
||||||
|
limit := 50
|
||||||
|
if cursor != nil {
|
||||||
|
if cursor.Value != nil && fmt.Sprintf("%v", cursor.Value) != "" {
|
||||||
|
q = q.Where("id < ?", cursor.Value)
|
||||||
|
}
|
||||||
|
limit = cursor.Limit()
|
||||||
|
}
|
||||||
|
|
||||||
|
q = q.Order("created_at ASC")
|
||||||
|
q = q.Limit(limit)
|
||||||
|
|
||||||
|
if err := q.Find(&messages).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get messages")
|
||||||
|
}
|
||||||
|
return messages, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFirstMessagesByConversationIDs 批量获取多个会话的第一条消息内容。
|
||||||
|
// 使用窗口函数 ROW_NUMBER() 选出每个会话最早的消息,避免 N+1 查询。
|
||||||
|
func (db *messages) GetFirstMessagesByConversationIDs(ctx context.Context, conversationIDs []uint) (map[uint]string, error) {
|
||||||
|
if len(conversationIDs) == 0 {
|
||||||
|
return make(map[uint]string), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用子查询 + ROW_NUMBER 窗口函数获取每个 conversation 的第一条消息
|
||||||
|
// 兼容 MySQL 8+ / PostgreSQL / SQLite 3.25+
|
||||||
|
var results []struct {
|
||||||
|
ConversationID uint `gorm:"column:conversation_id"`
|
||||||
|
Content string `gorm:"column:content"`
|
||||||
|
}
|
||||||
|
|
||||||
|
err := db.WithContext(ctx).Raw(`
|
||||||
|
SELECT conversation_id, content FROM (
|
||||||
|
SELECT conversation_id, content,
|
||||||
|
ROW_NUMBER() OVER (PARTITION BY conversation_id ORDER BY created_at ASC) AS rn
|
||||||
|
FROM messages
|
||||||
|
WHERE conversation_id IN ?
|
||||||
|
) sub WHERE rn = 1
|
||||||
|
`, conversationIDs).Scan(&results).Error
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get first messages batch")
|
||||||
|
}
|
||||||
|
|
||||||
|
resultMap := make(map[uint]string, len(results))
|
||||||
|
for _, r := range results {
|
||||||
|
resultMap[r.ConversationID] = r.Content
|
||||||
|
}
|
||||||
|
return resultMap, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAllByConversationIDs 批量获取多个会话的全部消息(导出用,不分页),按 conversation_id 分组。
|
||||||
|
// 用于账号导出:将每个会话原本的 1 次查询合并为 1 次 IN 查询,避免 N+1。
|
||||||
|
func (db *messages) GetAllByConversationIDs(ctx context.Context, conversationIDs []uint) (map[uint][]*Message, error) {
|
||||||
|
result := make(map[uint][]*Message)
|
||||||
|
if len(conversationIDs) == 0 {
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
var items []*Message
|
||||||
|
if err := db.WithContext(ctx).
|
||||||
|
Where("conversation_id IN ?", conversationIDs).
|
||||||
|
Order("conversation_id ASC, created_at ASC").
|
||||||
|
Find(&items).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get messages by conversation ids")
|
||||||
|
}
|
||||||
|
for _, m := range items {
|
||||||
|
result[m.ConversationID] = append(result[m.ConversationID], m)
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
var MessageImages MessageImageStore
|
||||||
|
|
||||||
|
type MessageImageStore interface {
|
||||||
|
Create(ctx context.Context, opts CreateMessageImageOptions) (*MessageImage, error)
|
||||||
|
GetByMessageIDs(ctx context.Context, messageIDs []uint) (map[uint][]*MessageImage, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMessageImageStore(db *gorm.DB) MessageImageStore {
|
||||||
|
return &messageImages{db}
|
||||||
|
}
|
||||||
|
|
||||||
|
type messageImages struct {
|
||||||
|
*gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
type MessageImage struct {
|
||||||
|
gorm.Model
|
||||||
|
MessageID uint `gorm:"index" json:"message_id"`
|
||||||
|
URL string `gorm:"size:500" json:"url"`
|
||||||
|
FileName string `gorm:"size:200" json:"file_name"`
|
||||||
|
FileSize int64 `json:"file_size"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateMessageImageOptions struct {
|
||||||
|
MessageID uint
|
||||||
|
URL string
|
||||||
|
FileName string
|
||||||
|
FileSize int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *messageImages) Create(ctx context.Context, opts CreateMessageImageOptions) (*MessageImage, error) {
|
||||||
|
img := &MessageImage{
|
||||||
|
MessageID: opts.MessageID,
|
||||||
|
URL: opts.URL,
|
||||||
|
FileName: opts.FileName,
|
||||||
|
FileSize: opts.FileSize,
|
||||||
|
}
|
||||||
|
if err := db.WithContext(ctx).Create(img).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "create message image")
|
||||||
|
}
|
||||||
|
return img, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *messageImages) GetByMessageIDs(ctx context.Context, messageIDs []uint) (map[uint][]*MessageImage, error) {
|
||||||
|
var images []*MessageImage
|
||||||
|
if err := db.WithContext(ctx).Where("message_id IN ?", messageIDs).Find(&images).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get message images")
|
||||||
|
}
|
||||||
|
result := make(map[uint][]*MessageImage)
|
||||||
|
for _, img := range images {
|
||||||
|
result[img.MessageID] = append(result[img.MessageID], img)
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/subtle"
|
||||||
|
"encoding/hex"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
|
"github.com/wuhan005/gadget"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/conf"
|
||||||
|
)
|
||||||
|
|
||||||
|
// bcryptCost is the cost parameter for bcrypt (10 is a good default, 12 for higher security).
|
||||||
|
const bcryptCost = 10
|
||||||
|
|
||||||
|
// bcryptMaxPasswordLen is the effective input length of bcrypt (72 bytes).
|
||||||
|
// bcrypt 只使用前 72 字节;新版 x/crypto 对超长密码直接返回错误,
|
||||||
|
// 这里统一截断到 72 字节(与 bcrypt 原生语义一致),避免走错误分支。
|
||||||
|
const bcryptMaxPasswordLen = 72
|
||||||
|
|
||||||
|
// encodePasswordBcrypt hashes a password with bcrypt.
|
||||||
|
// 注意:失败时绝不能静默降级为 HMAC-SHA1 弱哈希(此前行为),
|
||||||
|
// 返回空串会让该账号所有密码校验失败并留下错误日志,比弱哈希更安全。
|
||||||
|
func encodePasswordBcrypt(password string) string {
|
||||||
|
if len(password) > bcryptMaxPasswordLen {
|
||||||
|
password = password[:bcryptMaxPasswordLen]
|
||||||
|
}
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost)
|
||||||
|
if err != nil {
|
||||||
|
// cost 为常量 10,正常不会到这里;防御性记录,不降级为弱哈希。
|
||||||
|
logrus.WithError(err).Error("bcrypt generate failed")
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return string(hash)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isBcryptHash checks if the given string is a bcrypt hash.
|
||||||
|
func isBcryptHash(hash string) bool {
|
||||||
|
return strings.HasPrefix(hash, "$2a$") || strings.HasPrefix(hash, "$2b$") || strings.HasPrefix(hash, "$2y$")
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsBcryptHash exported for use in other packages.
|
||||||
|
func IsBcryptHash(hash string) bool {
|
||||||
|
return isBcryptHash(hash)
|
||||||
|
}
|
||||||
|
|
||||||
|
// authenticatePassword verifies a password against either bcrypt or legacy HMAC-SHA1 hash.
|
||||||
|
// Returns (true, newHash) if the password matches. If the old HMAC-SHA1 format was used,
|
||||||
|
// newHash contains the upgraded bcrypt hash — caller should persist it.
|
||||||
|
func authenticatePassword(storedHash, password string) (bool, string) {
|
||||||
|
if storedHash == "" {
|
||||||
|
return false, ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try bcrypt first (new format).
|
||||||
|
if isBcryptHash(storedHash) {
|
||||||
|
err := bcrypt.CompareHashAndPassword([]byte(storedHash), []byte(password))
|
||||||
|
return err == nil, ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fall back to legacy HMAC-SHA1(常量时间比较,防时序侧信道)。
|
||||||
|
legacyHash := gadget.HmacSha1(password, conf.Server.Salt)
|
||||||
|
if subtle.ConstantTimeCompare([]byte(legacyHash), []byte(storedHash)) == 1 {
|
||||||
|
// Password matches legacy format — upgrade to bcrypt.
|
||||||
|
return true, encodePasswordBcrypt(password)
|
||||||
|
}
|
||||||
|
|
||||||
|
return false, ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// needsRehash checks if a bcrypt hash should be rehashed (e.g., cost changed).
|
||||||
|
func needsRehash(hash string) bool {
|
||||||
|
cost, err := bcrypt.Cost([]byte(hash))
|
||||||
|
if err != nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return cost != bcryptCost
|
||||||
|
}
|
||||||
|
|
||||||
|
// HexEncodeToString is a helper to encode bytes as hex for legacy hash comparison.
|
||||||
|
func HexEncodeToString(src []byte) string {
|
||||||
|
return hex.EncodeToString(src)
|
||||||
|
}
|
||||||
@@ -0,0 +1,546 @@
|
|||||||
|
// 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 db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
|
"github.com/thanhpk/randstr"
|
||||||
|
"gorm.io/datatypes"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/dbutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
var Questions QuestionsStore
|
||||||
|
|
||||||
|
type QuestionsStore interface {
|
||||||
|
Create(ctx context.Context, opts CreateQuestionOptions) (*Question, error)
|
||||||
|
GetByID(ctx context.Context, id uint) (*Question, error)
|
||||||
|
GetByUserID(ctx context.Context, userID uint, opts GetQuestionsByUserIDOptions) ([]*Question, error)
|
||||||
|
GetByAskUserID(ctx context.Context, userID uint, opts GetQuestionsByAskUserIDOptions) ([]*Question, error)
|
||||||
|
AnswerByID(ctx context.Context, id uint, answer string) error
|
||||||
|
DeleteByID(ctx context.Context, id uint) error
|
||||||
|
UpdateCensor(ctx context.Context, id uint, opts UpdateQuestionCensorOptions) error
|
||||||
|
Count(ctx context.Context, userID uint, opts GetQuestionsCountOptions) (int64, error)
|
||||||
|
SetPrivate(ctx context.Context, id uint) error
|
||||||
|
SetPublic(ctx context.Context, id uint) error
|
||||||
|
SetPinned(ctx context.Context, id uint, pinned bool) error
|
||||||
|
SetRead(ctx context.Context, id uint) error
|
||||||
|
SetUnread(ctx context.Context, id uint) error
|
||||||
|
SearchByUserID(ctx context.Context, userID uint, keyword string) ([]*Question, error)
|
||||||
|
GetHotQuestions(ctx context.Context, limit int) ([]*Question, error)
|
||||||
|
|
||||||
|
// 全站统计
|
||||||
|
QuestionStats(ctx context.Context) (*QuestionStats, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// QuestionStats 全站提问聚合统计(不按单个用户过滤,供首页"提问箱信息统计"使用)。
|
||||||
|
type QuestionStats struct {
|
||||||
|
TotalQuestions int64
|
||||||
|
AnsweredQuestions int64
|
||||||
|
LastQuestionAt *time.Time // 最后一个提问发生时间(questions.created_at 最大值)
|
||||||
|
LastAnswerAt *time.Time // 最后一个回答发生时间(已回答问题的 updated_at 最大值)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewQuestionsStore(db *gorm.DB) QuestionsStore {
|
||||||
|
return &questions{db}
|
||||||
|
}
|
||||||
|
|
||||||
|
type questions struct {
|
||||||
|
*gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
type Question struct {
|
||||||
|
dbutil.Model
|
||||||
|
FromIP string `json:"-"`
|
||||||
|
UserID uint `gorm:"index:idx_question_user_id" json:"-"`
|
||||||
|
Content string `json:"content"`
|
||||||
|
ContentCensorMetadata datatypes.JSON `json:"-"`
|
||||||
|
Token string `json:"-"`
|
||||||
|
Answer string `json:"answer"`
|
||||||
|
AnswerCensorMetadata datatypes.JSON `json:"-"`
|
||||||
|
ReceiveReplyEmail string `json:"-"`
|
||||||
|
AskerUserID uint `json:"-"`
|
||||||
|
IsPrivate bool `gorm:"default: FALSE; NOT NULL" json:"-"`
|
||||||
|
IsPinned bool `gorm:"default: FALSE; NOT NULL" json:"is_pinned"`
|
||||||
|
// IsRead 标记箱主是否已读/处理过该提问。有效"已读" = IsRead=true 或 已有回答(answer != "")。
|
||||||
|
// 已回答的问题恒为已读且锁定,不可改回未读(见 SetUnread 的 answer='' 条件与上层校验)。
|
||||||
|
IsRead bool `gorm:"default: FALSE; NOT NULL" json:"is_read"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateQuestionOptions struct {
|
||||||
|
FromIP string
|
||||||
|
UserID uint
|
||||||
|
Content string
|
||||||
|
ReceiveReplyEmail string
|
||||||
|
AskerUserID uint
|
||||||
|
IsPrivate bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *questions) Create(ctx context.Context, opts CreateQuestionOptions) (*Question, error) {
|
||||||
|
question := Question{
|
||||||
|
FromIP: opts.FromIP,
|
||||||
|
UserID: opts.UserID,
|
||||||
|
Token: randstr.String(6),
|
||||||
|
Content: opts.Content,
|
||||||
|
ReceiveReplyEmail: opts.ReceiveReplyEmail,
|
||||||
|
AskerUserID: opts.AskerUserID,
|
||||||
|
IsPrivate: opts.IsPrivate,
|
||||||
|
}
|
||||||
|
return &question, db.WithContext(ctx).Create(&question).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdateQuestionCensorOptions struct {
|
||||||
|
ContentCensorMetadata json.RawMessage
|
||||||
|
AnswerCensorMetadata json.RawMessage
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *questions) UpdateCensor(ctx context.Context, id uint, opts UpdateQuestionCensorOptions) error {
|
||||||
|
question, err := db.GetByID(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "get by ID")
|
||||||
|
}
|
||||||
|
|
||||||
|
contentCensorMetadata := question.ContentCensorMetadata
|
||||||
|
if checkTextCensorResponseValid(opts.ContentCensorMetadata) {
|
||||||
|
contentCensorMetadata = datatypes.JSON(opts.ContentCensorMetadata)
|
||||||
|
}
|
||||||
|
answerCensorMetadata := question.AnswerCensorMetadata
|
||||||
|
if checkTextCensorResponseValid(opts.AnswerCensorMetadata) {
|
||||||
|
answerCensorMetadata = datatypes.JSON(opts.AnswerCensorMetadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
return db.WithContext(ctx).Model(&Question{}).Where("id = ?", id).Updates(&Question{
|
||||||
|
ContentCensorMetadata: contentCensorMetadata,
|
||||||
|
AnswerCensorMetadata: answerCensorMetadata,
|
||||||
|
}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkTextCensorResponseValid(raw json.RawMessage) bool {
|
||||||
|
if len(raw) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
if bytes.EqualFold(raw, []byte("null")) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
var response struct {
|
||||||
|
SourceName string `json:"source_name"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &response); err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return response.SourceName != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
var ErrQuestionNotExist = errors.New("提问不存在")
|
||||||
|
|
||||||
|
func (db *questions) GetByID(ctx context.Context, id uint) (*Question, error) {
|
||||||
|
var question Question
|
||||||
|
if err := db.WithContext(ctx).First(&question, id).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, ErrQuestionNotExist
|
||||||
|
}
|
||||||
|
return nil, errors.Wrap(err, "get question by ID")
|
||||||
|
}
|
||||||
|
return &question, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetQuestionsByUserIDOptions struct {
|
||||||
|
*dbutil.Cursor
|
||||||
|
FilterAnswered bool // 已废弃,推荐使用 AnsweredStatus
|
||||||
|
ShowPrivate bool // 已废弃,推荐使用 PrivateStatus
|
||||||
|
AnsweredStatus int // 0: 全部, 1: 已回答, 2: 未回答
|
||||||
|
PrivateStatus int // 0: 全部, 1: 仅公开(is_private=false), 2: 仅私密(is_private=true)
|
||||||
|
ReadStatus int // 0: 全部, 1: 已读(is_read=true 或已回答), 2: 未读
|
||||||
|
SortOrder string // "ASC" 或 "DESC",默认 "DESC"
|
||||||
|
PinFirst bool // 置顶优先:is_pinned 的提问排在最前(公开主页使用)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetByUserID 根据用户 ID 获取提问列表,支持游标分页
|
||||||
|
func (db *questions) GetByUserID(ctx context.Context, userID uint, opts GetQuestionsByUserIDOptions) ([]*Question, error) {
|
||||||
|
q := db.WithContext(ctx).Model(&Question{}).Where("user_id = ?", userID)
|
||||||
|
|
||||||
|
// 回答状态筛选
|
||||||
|
if opts.AnsweredStatus == 1 {
|
||||||
|
q = q.Where("answer != ''")
|
||||||
|
} else if opts.AnsweredStatus == 2 {
|
||||||
|
q = q.Where("answer = ''")
|
||||||
|
} else if opts.FilterAnswered {
|
||||||
|
// 兼容旧调用
|
||||||
|
q = q.Where("answer != ''")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 私密状态筛选
|
||||||
|
if opts.PrivateStatus == 1 {
|
||||||
|
q = q.Where("is_private = false")
|
||||||
|
} else if opts.PrivateStatus == 2 {
|
||||||
|
q = q.Where("is_private = true")
|
||||||
|
} else if !opts.ShowPrivate && opts.PrivateStatus == 0 {
|
||||||
|
// 兼容旧调用:如果 ShowPrivate=false 且未指定 PrivateStatus,则过滤私密
|
||||||
|
q = q.Where("is_private = false")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 阅读状态筛选:已读 = is_read=true 或已回答;未读 = is_read=false 且未回答。
|
||||||
|
// 使用括号包裹 OR 条件,避免与前面的 user_id 等条件产生 AND/OR 优先级问题。
|
||||||
|
if opts.ReadStatus == 1 {
|
||||||
|
q = q.Where("(is_read = ? OR answer != '')", true)
|
||||||
|
} else if opts.ReadStatus == 2 {
|
||||||
|
q = q.Where("(is_read = ? AND answer = '')", false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 排序方向先规范化,游标方向依赖它(ASC=下一页 id 更大,DESC=下一页 id 更小)。
|
||||||
|
sortOrder := opts.SortOrder
|
||||||
|
if sortOrder == "" {
|
||||||
|
sortOrder = "DESC"
|
||||||
|
}
|
||||||
|
if sortOrder != "ASC" && sortOrder != "DESC" {
|
||||||
|
sortOrder = "DESC"
|
||||||
|
}
|
||||||
|
|
||||||
|
// 游标分页
|
||||||
|
// 关键语义:携带游标却无法解析时,不再“忽略游标、从首页重新开始”。
|
||||||
|
// 旧行为会导致「加载更多」重复返回第一页内容、按钮永不消失(内容重复的
|
||||||
|
// 直接根因之一,见 history-template 的复合游标改造历史)。改为直接返回
|
||||||
|
// 空列表:上层(ListAPI/Pager 等)据此判定 has_more=false,前端按钮收敛。
|
||||||
|
if opts.Cursor != nil && opts.Cursor.Value != nil {
|
||||||
|
cursorStr := fmt.Sprintf("%v", opts.Cursor.Value)
|
||||||
|
if cursorStr != "" {
|
||||||
|
if opts.PinFirst {
|
||||||
|
// 置顶优先场景下,排序为 (is_pinned DESC, created_at, id),
|
||||||
|
// 必须用"复合键集"(keyset)游标,否则置顶项与非置顶项 id 交错时
|
||||||
|
// 单纯 id < 游标会漏掉介于置顶项 id 之间、但排在更后面的非置顶项。
|
||||||
|
// 游标格式:"<isPinned>.<createdAtUnixNano>.<id>"。
|
||||||
|
isPinned, createdAt, idVal, ok := parsePinCursor(cursorStr)
|
||||||
|
if !ok {
|
||||||
|
return []*Question{}, nil
|
||||||
|
}
|
||||||
|
// 排序为 (is_pinned DESC, created_at DESC, id DESC),下一页 = 排序序位严格在游标之后的行。
|
||||||
|
// 注意:is_pinned 在 PG 下是 boolean,与整型比较(boolean < integer)无操作符会直接报错,
|
||||||
|
// 因此必须传 Go bool 而非 0/1 整型(MySQL 下 bool 亦兼容 tinyint)。
|
||||||
|
// 游标位于置顶段时,后续行 = 置顶段内 (created_at,id) 更小 + 全部非置顶段;
|
||||||
|
// 游标位于非置顶段时,后续行 = 非置顶段内 (created_at,id) 更小。
|
||||||
|
if isPinned == 1 {
|
||||||
|
q = q.Where(
|
||||||
|
"(is_pinned = ? AND created_at < ?) OR (is_pinned = ? AND created_at = ? AND id < ?) OR (is_pinned = ?)",
|
||||||
|
true, createdAt, true, createdAt, idVal, false,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
q = q.Where(
|
||||||
|
"(is_pinned = ? AND created_at < ?) OR (is_pinned = ? AND created_at = ? AND id < ?)",
|
||||||
|
false, createdAt, false, createdAt, idVal,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 游标必须为纯数字 id:直接传 string 在 PG 下会因 integer < text 无操作符而报错。
|
||||||
|
// 且 ASC(旧在前)时下一页 id 更大,DESC(新在前)时下一页 id 更小。
|
||||||
|
idVal, err := strconv.ParseUint(cursorStr, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
// 同上:游标非法不再回退首页,直接收敛为空列表。
|
||||||
|
return []*Question{}, nil
|
||||||
|
}
|
||||||
|
if sortOrder == "ASC" {
|
||||||
|
q = q.Where("id > ?", idVal)
|
||||||
|
} else {
|
||||||
|
q = q.Where("id < ?", idVal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if opts.Cursor != nil {
|
||||||
|
limit := opts.Cursor.Limit()
|
||||||
|
q = q.Limit(limit)
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts.PinFirst {
|
||||||
|
// 公开主页:置顶优先;用 id 作为稳定 tiebreaker 保证排序完全确定。
|
||||||
|
q = q.Order("is_pinned DESC, created_at " + sortOrder + ", id " + sortOrder)
|
||||||
|
} else {
|
||||||
|
q = q.Order("created_at " + sortOrder + ", id " + sortOrder)
|
||||||
|
}
|
||||||
|
|
||||||
|
var questions []*Question
|
||||||
|
if err := q.Find(&questions).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get questions by user id")
|
||||||
|
}
|
||||||
|
return questions, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// parsePinCursor 解析 PinFirst 分页的复合键集游标,格式 "<isPinned>.<createdAtUnixNano>.<id>"。
|
||||||
|
// 返回 (isPinned, createdAt, id, ok);格式非法时 ok=false,调用方应忽略该游标(从首页重新开始)。
|
||||||
|
//
|
||||||
|
// 时区约定(务必保持,否则线上翻页会退化为首页死循环):
|
||||||
|
// EncodePinCursor 的 nano 取自 DB 读回的 CreatedAt.UnixNano(),生产列是
|
||||||
|
// timestamp WITHOUT time zone,读写按「墙钟即 UTC」对称,因此 Parse 侧必须把 nano
|
||||||
|
// 还原成 UTC 墙钟的 time.Time(time.Unix(0,nano).UTC()),再交给 GORM 与无时区列比较。
|
||||||
|
// 若直接返回 time.Unix(0, nano)(Location=服务器本地时区),当进程 TZ 非 UTC 时
|
||||||
|
// (如 Asia/Shanghai)墙钟会偏移 +8h,导致 keyset 条件 created_at < 偏移时间恒为真,
|
||||||
|
// 游标形同虚设,每次请求都退回第一页 → 「加载更多」无限重复且按钮永不消失。
|
||||||
|
func parsePinCursor(s string) (int, time.Time, uint, bool) {
|
||||||
|
parts := strings.Split(s, ".")
|
||||||
|
if len(parts) != 3 {
|
||||||
|
return 0, time.Time{}, 0, false
|
||||||
|
}
|
||||||
|
isPinned, err := strconv.Atoi(parts[0])
|
||||||
|
if err != nil {
|
||||||
|
return 0, time.Time{}, 0, false
|
||||||
|
}
|
||||||
|
nano, err := strconv.ParseInt(parts[1], 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return 0, time.Time{}, 0, false
|
||||||
|
}
|
||||||
|
idVal, err := strconv.ParseUint(parts[2], 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return 0, time.Time{}, 0, false
|
||||||
|
}
|
||||||
|
return isPinned, time.Unix(0, nano).UTC(), uint(idVal), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// EncodePinCursor 生成 PinFirst 分页游标(供路由层把末条记录编码进下一页游标)。
|
||||||
|
func EncodePinCursor(isPinned bool, createdAt time.Time, id uint) string {
|
||||||
|
v := 0
|
||||||
|
if isPinned {
|
||||||
|
v = 1
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%d.%d.%d", v, createdAt.UnixNano(), id)
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetQuestionsByAskUserIDOptions struct {
|
||||||
|
*dbutil.Cursor
|
||||||
|
FilterAnswered bool
|
||||||
|
ShowPrivate bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *questions) GetByAskUserID(ctx context.Context, userID uint, opts GetQuestionsByAskUserIDOptions) ([]*Question, error) {
|
||||||
|
where := `asker_user_id = ?`
|
||||||
|
args := userID
|
||||||
|
|
||||||
|
if opts.FilterAnswered {
|
||||||
|
where = `asker_user_id = ? AND answer != ''`
|
||||||
|
}
|
||||||
|
if !opts.ShowPrivate {
|
||||||
|
where += ` AND is_private = false`
|
||||||
|
}
|
||||||
|
|
||||||
|
questions, err := db.getBy(ctx, opts.Cursor, where, args)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get by")
|
||||||
|
}
|
||||||
|
return questions, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// getBy 保留用于 GetByAskUserID 等旧逻辑
|
||||||
|
func (db *questions) getBy(ctx context.Context, cursor *dbutil.Cursor, whereQuery string, args ...interface{}) ([]*Question, error) {
|
||||||
|
var questions []*Question
|
||||||
|
q := db.WithContext(ctx).Where(whereQuery, args...)
|
||||||
|
|
||||||
|
if cursor != nil {
|
||||||
|
cursorID := cursor.Value
|
||||||
|
if cursorID != nil && fmt.Sprintf("%v", cursorID) != "" {
|
||||||
|
// 游标必须为纯数字 id:直接传 string 在 PG 下会因 integer < text 无操作符而报错。
|
||||||
|
// 解析失败不再忽略游标回退首页(会导致「加载更多」重复首页内容),
|
||||||
|
// 直接收敛为空列表,令调用方按“无更多”处理。
|
||||||
|
idVal, err := strconv.ParseUint(fmt.Sprintf("%v", cursorID), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return []*Question{}, nil
|
||||||
|
}
|
||||||
|
if idVal > 0 {
|
||||||
|
q = q.Where(`id < ?`, idVal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
limit := cursor.Limit()
|
||||||
|
q = q.Limit(limit)
|
||||||
|
}
|
||||||
|
|
||||||
|
q = q.Order("created_at DESC")
|
||||||
|
if err := q.Find(&questions).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get questions by page ID")
|
||||||
|
}
|
||||||
|
return questions, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *questions) AnswerByID(ctx context.Context, id uint, answer string) error {
|
||||||
|
var question Question
|
||||||
|
if err := db.WithContext(ctx).First(&question, id).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrQuestionNotExist
|
||||||
|
}
|
||||||
|
return errors.Wrap(err, "get question by ID")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.WithContext(ctx).Model(&question).Where("id = ?", id).
|
||||||
|
Updates(map[string]interface{}{"answer": answer, "is_read": true}).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "update question answer")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *questions) DeleteByID(ctx context.Context, id uint) error {
|
||||||
|
var question Question
|
||||||
|
if err := db.WithContext(ctx).First(&question, id).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrQuestionNotExist
|
||||||
|
}
|
||||||
|
return errors.Wrap(err, "get question by ID")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.WithContext(ctx).Delete(&Question{}, id).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "delete question")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 级联清理子表:追问与上传图片,避免删除提问后残留孤儿记录。
|
||||||
|
if err := FollowUps.DeleteByQuestionID(ctx, id); err != nil {
|
||||||
|
logrus.WithContext(ctx).WithError(err).Errorf("Failed to cascade delete follow ups for question %d", id)
|
||||||
|
}
|
||||||
|
if err := UploadImages.DeleteByQuestionID(ctx, id); err != nil {
|
||||||
|
logrus.WithContext(ctx).WithError(err).Errorf("Failed to cascade delete upload images for question %d", id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 回退定量收集计数:删除提问等价于少一条已收集内容,
|
||||||
|
// 否则达上限后即便删掉旧提问,功能仍会显示 quota_reached 关闭,须手动重置计数。
|
||||||
|
if question.UserID != 0 {
|
||||||
|
if err := FeatureControls.IncrementQuota(ctx, question.UserID, FeatureQuestion, -1); err != nil {
|
||||||
|
logrus.WithContext(ctx).WithError(err).Errorf("Failed to decrement question quota for user %d", question.UserID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetQuestionsCountOptions struct {
|
||||||
|
FilterAnswered bool
|
||||||
|
ShowPrivate bool
|
||||||
|
IsPrivate *bool // 非 nil 时按该值过滤 is_private
|
||||||
|
IsPinned *bool // 非 nil 时按该值过滤 is_pinned
|
||||||
|
ReadStatus int // 0: 全部, 1: 已读(is_read=true 或已回答), 2: 未读
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *questions) Count(ctx context.Context, userID uint, opts GetQuestionsCountOptions) (int64, error) {
|
||||||
|
q := db.WithContext(ctx).Model(&Question{})
|
||||||
|
if opts.FilterAnswered {
|
||||||
|
q = q.Where(`user_id = ? AND answer != ''`, userID)
|
||||||
|
} else {
|
||||||
|
q = q.Where(`user_id = ?`, userID)
|
||||||
|
}
|
||||||
|
if !opts.ShowPrivate {
|
||||||
|
q = q.Where(`is_private = ?`, false)
|
||||||
|
}
|
||||||
|
if opts.IsPrivate != nil {
|
||||||
|
q = q.Where(`is_private = ?`, *opts.IsPrivate)
|
||||||
|
}
|
||||||
|
if opts.IsPinned != nil {
|
||||||
|
q = q.Where(`is_pinned = ?`, *opts.IsPinned)
|
||||||
|
}
|
||||||
|
// 阅读状态筛选:已读 = is_read=true 或已回答;未读 = is_read=false 且未回答。
|
||||||
|
if opts.ReadStatus == 1 {
|
||||||
|
q = q.Where("(is_read = ? OR answer != '')", true)
|
||||||
|
} else if opts.ReadStatus == 2 {
|
||||||
|
q = q.Where("(is_read = ? AND answer = '')", false)
|
||||||
|
}
|
||||||
|
|
||||||
|
var count int64
|
||||||
|
return count, q.Count(&count).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *questions) SetPrivate(ctx context.Context, id uint) error {
|
||||||
|
return db.WithContext(ctx).Model(&Question{}).Where("id = ?", id).Update("is_private", true).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetPinned 设置/取消问题的置顶状态。
|
||||||
|
func (db *questions) SetPinned(ctx context.Context, id uint, pinned bool) error {
|
||||||
|
return db.WithContext(ctx).Model(&Question{}).Where("id = ?", id).Update("is_pinned", pinned).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *questions) SetPublic(ctx context.Context, id uint) error {
|
||||||
|
return db.WithContext(ctx).Model(&Question{}).Where("id = ?", id).Update("is_private", false).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetRead 标记提问为已读(箱主侧手动标记,或作为其他语义化操作的前置状态)。
|
||||||
|
func (db *questions) SetRead(ctx context.Context, id uint) error {
|
||||||
|
return db.WithContext(ctx).Model(&Question{}).Where("id = ?", id).Update("is_read", true).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetUnread 标记提问为未读。已回答的提问恒为已读且锁定,故追加 answer=” 条件:
|
||||||
|
// 即使上层遗漏校验,也不会把已回答的提问错误地改回未读(纵深防御)。
|
||||||
|
func (db *questions) SetUnread(ctx context.Context, id uint) error {
|
||||||
|
return db.WithContext(ctx).Model(&Question{}).Where("id = ? AND answer = ''", id).Update("is_read", false).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// SearchByUserID 全文搜索提问箱主人收到的提问(含私密,仅限本人管理后台使用)。
|
||||||
|
// 使用 LIKE 模糊匹配问题内容与回答;keyword 中的通配符 % _ \ 会被转义,避免模式滥用。
|
||||||
|
func (db *questions) SearchByUserID(ctx context.Context, userID uint, keyword string) ([]*Question, error) {
|
||||||
|
escaped := escapeLike(keyword)
|
||||||
|
var questions []*Question
|
||||||
|
if err := db.WithContext(ctx).
|
||||||
|
Where("user_id = ? AND (content LIKE ? OR answer LIKE ?)", userID, "%"+escaped+"%", "%"+escaped+"%").
|
||||||
|
Order("created_at DESC").
|
||||||
|
Find(&questions).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "search questions by user id")
|
||||||
|
}
|
||||||
|
return questions, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// escapeLike 转义 LIKE 模式中的特殊字符。
|
||||||
|
func escapeLike(s string) string {
|
||||||
|
r := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`)
|
||||||
|
return r.Replace(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetHotQuestions 返回"热门问题":最新活跃的公开已回答提问(按回答更新时间倒序)。
|
||||||
|
// 提问箱没有点赞数据,用"最近被回答"作为热度近似,适合主页/探索页展示。
|
||||||
|
func (db *questions) GetHotQuestions(ctx context.Context, limit int) ([]*Question, error) {
|
||||||
|
if limit <= 0 {
|
||||||
|
limit = 10
|
||||||
|
}
|
||||||
|
var questions []*Question
|
||||||
|
if err := db.WithContext(ctx).
|
||||||
|
Where("is_private = ? AND answer != ''", false).
|
||||||
|
Order("updated_at DESC").
|
||||||
|
Limit(limit).
|
||||||
|
Find(&questions).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get hot questions")
|
||||||
|
}
|
||||||
|
return questions, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// QuestionStats 返回全站提问相关聚合统计。
|
||||||
|
// 使用 gorm 查询构造器生成 COUNT / MAX,兼容 MySQL 与 PostgreSQL。
|
||||||
|
// 最后一个回答时间取"已回答问题"的 updated_at 最大值——回答动作会更新 updated_at,
|
||||||
|
// 与 crontab 旧逻辑(answer 非空记录中 updated_at 最大)一致。
|
||||||
|
func (db *questions) QuestionStats(ctx context.Context) (*QuestionStats, error) {
|
||||||
|
var total, answered int64
|
||||||
|
if err := db.WithContext(ctx).Model(&Question{}).Count(&total).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "count questions")
|
||||||
|
}
|
||||||
|
if err := db.WithContext(ctx).Model(&Question{}).Where("answer != ''").Count(&answered).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "count answered questions")
|
||||||
|
}
|
||||||
|
|
||||||
|
var t struct {
|
||||||
|
LastQ *time.Time `gorm:"column:last_q"`
|
||||||
|
LastA *time.Time `gorm:"column:last_a"`
|
||||||
|
}
|
||||||
|
if err := db.WithContext(ctx).Model(&Question{}).
|
||||||
|
Select("MAX(created_at) AS last_q, MAX(CASE WHEN answer != '' THEN updated_at ELSE NULL END) AS last_a").
|
||||||
|
Scan(&t).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get last question/answer time")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &QuestionStats{
|
||||||
|
TotalQuestions: total,
|
||||||
|
AnsweredQuestions: answered,
|
||||||
|
LastQuestionAt: t.LastQ,
|
||||||
|
LastAnswerAt: t.LastA,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,467 @@
|
|||||||
|
// Copyright 2023 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 db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
|
"github.com/tamakyi/TamaBox/internal/dbutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestQuestions(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
db, cleanup := newTestDB(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
questionsStore := NewQuestionsStore(db)
|
||||||
|
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
test func(t *testing.T, ctx context.Context, db *questions)
|
||||||
|
}{
|
||||||
|
{"Create", testQuestionsCreate},
|
||||||
|
{"GetByID", testQuestionsGetByID},
|
||||||
|
{"GetByUserID", testQuestionsGetByUserID},
|
||||||
|
{"GetByAskUserID", testQuestionsGetByAskUserID},
|
||||||
|
{"AnswerByID", testQuestionsAnswerByID},
|
||||||
|
{"DeleteByID", testQuestionsDeleteByID},
|
||||||
|
{"UpdateCensor", testQuestionsUpdateCensor},
|
||||||
|
{"Count", testQuestionsCount},
|
||||||
|
{"SetPrivate", testQuestionsSetPrivate},
|
||||||
|
{"SetPublic", testQuestionsSetPublic},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
t.Cleanup(func() {
|
||||||
|
if err := cleanup("questions"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
tc.test(t, ctx, questionsStore.(*questions))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testQuestionsCreate(t *testing.T, ctx context.Context, db *questions) {
|
||||||
|
t.Run("normal", func(t *testing.T) {
|
||||||
|
got, err := db.Create(ctx, CreateQuestionOptions{
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 1,
|
||||||
|
Content: "Hello, world!",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
AskerUserID: 0,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
got.Token = ""
|
||||||
|
got.CreatedAt = time.Time{}
|
||||||
|
got.UpdatedAt = time.Time{}
|
||||||
|
|
||||||
|
want := &Question{
|
||||||
|
Model: dbutil.Model{
|
||||||
|
ID: 1,
|
||||||
|
},
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 1,
|
||||||
|
Content: "Hello, world!",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
}
|
||||||
|
require.Equal(t, got, want)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func testQuestionsGetByID(t *testing.T, ctx context.Context, db *questions) {
|
||||||
|
_, err := db.Create(ctx, CreateQuestionOptions{
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 1,
|
||||||
|
Content: "Hello, world!",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
AskerUserID: 0,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
t.Run("normal", func(t *testing.T) {
|
||||||
|
got, err := db.GetByID(ctx, 1)
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
got.Token = ""
|
||||||
|
got.CreatedAt = time.Time{}
|
||||||
|
got.UpdatedAt = time.Time{}
|
||||||
|
|
||||||
|
want := &Question{
|
||||||
|
Model: dbutil.Model{
|
||||||
|
ID: 1,
|
||||||
|
},
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 1,
|
||||||
|
Content: "Hello, world!",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
}
|
||||||
|
require.Equal(t, got, want)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("not found", func(t *testing.T) {
|
||||||
|
_, err := db.GetByID(ctx, 404)
|
||||||
|
require.Equal(t, ErrQuestionNotExist, err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func testQuestionsGetByUserID(t *testing.T, ctx context.Context, db *questions) {
|
||||||
|
_, err := db.Create(ctx, CreateQuestionOptions{
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 1,
|
||||||
|
Content: "Content - 1",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
AskerUserID: 0,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
_, err = db.Create(ctx, CreateQuestionOptions{
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 2,
|
||||||
|
Content: "Content - 2",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
AskerUserID: 0,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
_, err = db.Create(ctx, CreateQuestionOptions{
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 1,
|
||||||
|
Content: "Content - 3",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
AskerUserID: 0,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
t.Run("all", func(t *testing.T) {
|
||||||
|
got, err := db.GetByUserID(ctx, 1, GetQuestionsByUserIDOptions{})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
for _, g := range got {
|
||||||
|
g.Token = ""
|
||||||
|
g.CreatedAt = time.Time{}
|
||||||
|
g.UpdatedAt = time.Time{}
|
||||||
|
}
|
||||||
|
|
||||||
|
want := []*Question{
|
||||||
|
{
|
||||||
|
Model: dbutil.Model{
|
||||||
|
ID: 3,
|
||||||
|
},
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 1,
|
||||||
|
Content: "Content - 3",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Model: dbutil.Model{
|
||||||
|
ID: 1,
|
||||||
|
},
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 1,
|
||||||
|
Content: "Content - 1",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
require.Equal(t, want, got)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("cursor", func(t *testing.T) {
|
||||||
|
got, err := db.GetByUserID(ctx, 1, GetQuestionsByUserIDOptions{
|
||||||
|
Cursor: &dbutil.Cursor{
|
||||||
|
Value: 3,
|
||||||
|
PageSize: 10,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
for _, g := range got {
|
||||||
|
g.Token = ""
|
||||||
|
g.CreatedAt = time.Time{}
|
||||||
|
g.UpdatedAt = time.Time{}
|
||||||
|
}
|
||||||
|
|
||||||
|
want := []*Question{
|
||||||
|
{
|
||||||
|
Model: dbutil.Model{
|
||||||
|
ID: 1,
|
||||||
|
},
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 1,
|
||||||
|
Content: "Content - 1",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
require.Equal(t, want, got)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("not found", func(t *testing.T) {
|
||||||
|
_, err := db.GetByID(ctx, 404)
|
||||||
|
require.Equal(t, ErrQuestionNotExist, err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func testQuestionsGetByAskUserID(t *testing.T, ctx context.Context, db *questions) {
|
||||||
|
_, err := db.Create(ctx, CreateQuestionOptions{
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 1,
|
||||||
|
Content: "Content - 1",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
AskerUserID: 1,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
_, err = db.Create(ctx, CreateQuestionOptions{
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 2,
|
||||||
|
Content: "Content - 2",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
AskerUserID: 2,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
_, err = db.Create(ctx, CreateQuestionOptions{
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 2,
|
||||||
|
Content: "Content - 2",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
AskerUserID: 2,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
t.Run("all", func(t *testing.T) {
|
||||||
|
got, err := db.GetByAskUserID(ctx, 1, GetQuestionsByAskUserIDOptions{})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
for _, g := range got {
|
||||||
|
g.Token = ""
|
||||||
|
g.CreatedAt = time.Time{}
|
||||||
|
g.UpdatedAt = time.Time{}
|
||||||
|
}
|
||||||
|
|
||||||
|
want := []*Question{
|
||||||
|
{
|
||||||
|
Model: dbutil.Model{
|
||||||
|
ID: 1,
|
||||||
|
},
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 1,
|
||||||
|
Content: "Content - 1",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
AskerUserID: 1,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
require.Equal(t, want, got)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("cursor", func(t *testing.T) {
|
||||||
|
got, err := db.GetByAskUserID(ctx, 2, GetQuestionsByAskUserIDOptions{
|
||||||
|
Cursor: &dbutil.Cursor{
|
||||||
|
Value: 3,
|
||||||
|
PageSize: 10,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
for _, g := range got {
|
||||||
|
g.Token = ""
|
||||||
|
g.CreatedAt = time.Time{}
|
||||||
|
g.UpdatedAt = time.Time{}
|
||||||
|
}
|
||||||
|
|
||||||
|
want := []*Question{
|
||||||
|
{
|
||||||
|
Model: dbutil.Model{
|
||||||
|
ID: 2,
|
||||||
|
},
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 2,
|
||||||
|
Content: "Content - 2",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
AskerUserID: 2,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
require.Equal(t, want, got)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("not found", func(t *testing.T) {
|
||||||
|
_, err := db.GetByID(ctx, 404)
|
||||||
|
require.Equal(t, ErrQuestionNotExist, err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func testQuestionsAnswerByID(t *testing.T, ctx context.Context, db *questions) {
|
||||||
|
t.Run("normal", func(t *testing.T) {
|
||||||
|
_, err := db.Create(ctx, CreateQuestionOptions{
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 1,
|
||||||
|
Content: "Content - 1",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
AskerUserID: 1,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
err = db.AnswerByID(ctx, 1, "Answer - 1")
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
got, err := db.GetByID(ctx, 1)
|
||||||
|
require.Nil(t, err)
|
||||||
|
require.Equal(t, "Answer - 1", got.Answer)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("not found", func(t *testing.T) {
|
||||||
|
err := db.AnswerByID(ctx, 404, "Answer - 1")
|
||||||
|
require.Equal(t, ErrQuestionNotExist, err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func testQuestionsDeleteByID(t *testing.T, ctx context.Context, db *questions) {
|
||||||
|
t.Run("normal", func(t *testing.T) {
|
||||||
|
_, err := db.Create(ctx, CreateQuestionOptions{
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 1,
|
||||||
|
Content: "Content - 1",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
AskerUserID: 1,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
err = db.DeleteByID(ctx, 1)
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
_, err = db.GetByID(ctx, 1)
|
||||||
|
require.Equal(t, ErrQuestionNotExist, err)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("not found", func(t *testing.T) {
|
||||||
|
err := db.DeleteByID(ctx, 404)
|
||||||
|
require.Equal(t, ErrQuestionNotExist, err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func testQuestionsUpdateCensor(t *testing.T, ctx context.Context, db *questions) {
|
||||||
|
t.Run("normal", func(t *testing.T) {
|
||||||
|
_, err := db.Create(ctx, CreateQuestionOptions{
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 1,
|
||||||
|
Content: "Content - 1",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
AskerUserID: 1,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
err = db.DeleteByID(ctx, 1)
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
_, err = db.GetByID(ctx, 1)
|
||||||
|
require.Equal(t, ErrQuestionNotExist, err)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("not found", func(t *testing.T) {
|
||||||
|
err := db.UpdateCensor(ctx, 404, UpdateQuestionCensorOptions{})
|
||||||
|
require.NotNil(t, err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func testQuestionsCount(t *testing.T, ctx context.Context, db *questions) {
|
||||||
|
_, err := db.Create(ctx, CreateQuestionOptions{
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 1,
|
||||||
|
Content: "Content - 1",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
AskerUserID: 1,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
_, err = db.Create(ctx, CreateQuestionOptions{
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 2,
|
||||||
|
Content: "Content - 2",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
AskerUserID: 0,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
_, err = db.Create(ctx, CreateQuestionOptions{
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 1,
|
||||||
|
Content: "Content - 3",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
AskerUserID: 0,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
err = db.AnswerByID(ctx, 3, "Answer - 3")
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
t.Run("normal", func(t *testing.T) {
|
||||||
|
got, err := db.Count(ctx, 1, GetQuestionsCountOptions{})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
want := int64(2)
|
||||||
|
require.Equal(t, want, got)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("filter", func(t *testing.T) {
|
||||||
|
got, err := db.Count(ctx, 1, GetQuestionsCountOptions{FilterAnswered: true})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
want := int64(1)
|
||||||
|
require.Equal(t, want, got)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("not found", func(t *testing.T) {
|
||||||
|
got, err := db.Count(ctx, 404, GetQuestionsCountOptions{})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
want := int64(0)
|
||||||
|
require.Equal(t, want, got)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func testQuestionsSetPrivate(t *testing.T, ctx context.Context, db *questions) {
|
||||||
|
_, err := db.Create(ctx, CreateQuestionOptions{
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 1,
|
||||||
|
Content: "Content - 1",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
AskerUserID: 1,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
t.Run("normal", func(t *testing.T) {
|
||||||
|
err = db.SetPrivate(ctx, 1)
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
got, err := db.GetByID(ctx, 1)
|
||||||
|
require.Nil(t, err)
|
||||||
|
require.True(t, got.IsPrivate)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func testQuestionsSetPublic(t *testing.T, ctx context.Context, db *questions) {
|
||||||
|
_, err := db.Create(ctx, CreateQuestionOptions{
|
||||||
|
FromIP: "114.5.1.4",
|
||||||
|
UserID: 1,
|
||||||
|
Content: "Content - 1",
|
||||||
|
ReceiveReplyEmail: "[email protected]",
|
||||||
|
AskerUserID: 1,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
t.Run("normal", func(t *testing.T) {
|
||||||
|
err = db.SetPublic(ctx, 1)
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
got, err := db.GetByID(ctx, 1)
|
||||||
|
require.Nil(t, err)
|
||||||
|
require.False(t, got.IsPrivate)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
// Copyright 2023 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 db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/samber/lo"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
var UploadImages UploadImagesStore
|
||||||
|
|
||||||
|
var _ UploadImagesStore = (*uploadImages)(nil)
|
||||||
|
|
||||||
|
type UploadImagesStore interface {
|
||||||
|
Create(ctx context.Context, opts CreateUploadImageOptions) (*UploadImage, error)
|
||||||
|
GetByQuestionID(ctx context.Context, questionID uint) ([]*UploadImage, error)
|
||||||
|
// GetByQuestionIDs 批量获取多个提问的图片,按 question_id 分组返回。
|
||||||
|
// 用于账号导出等场景,将 N 次单题查询合并为少量 IN 查询,避免 N+1。
|
||||||
|
GetByQuestionIDs(ctx context.Context, questionIDs []uint) (map[uint][]*UploadImage, error)
|
||||||
|
GetByTypeQuestionID(ctx context.Context, typ UploadImageQuestionType, questionID uint) ([]*UploadImage, error)
|
||||||
|
// DeleteByQuestionID 删除某条提问时级联清理其全部上传图片记录(软删除,与提问保持一致)。
|
||||||
|
DeleteByQuestionID(ctx context.Context, questionID uint) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUploadImagesStore(db *gorm.DB) UploadImagesStore {
|
||||||
|
return &uploadImages{db}
|
||||||
|
}
|
||||||
|
|
||||||
|
type uploadImages struct {
|
||||||
|
*gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
type UploadImage struct {
|
||||||
|
gorm.Model
|
||||||
|
UploaderUserID uint
|
||||||
|
Name string
|
||||||
|
FileSize int64
|
||||||
|
Md5 string
|
||||||
|
Key string
|
||||||
|
}
|
||||||
|
|
||||||
|
type UploadImageQuestionType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
UploadImageQuestionTypeAsk UploadImageQuestionType = "ask"
|
||||||
|
UploadImageQuestionTypeAnswer UploadImageQuestionType = "answer"
|
||||||
|
)
|
||||||
|
|
||||||
|
type UploadImageQuestion struct {
|
||||||
|
Type UploadImageQuestionType
|
||||||
|
UploadImageID uint `gorm:"primaryKey"`
|
||||||
|
QuestionID uint `gorm:"primaryKey"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateUploadImageOptions struct {
|
||||||
|
Type UploadImageQuestionType
|
||||||
|
QuestionID uint
|
||||||
|
UploaderUserID uint
|
||||||
|
Name string
|
||||||
|
FileSize int64
|
||||||
|
Md5 string
|
||||||
|
Key string
|
||||||
|
IsDeletingPrevious bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *uploadImages) Create(ctx context.Context, opts CreateUploadImageOptions) (*UploadImage, error) {
|
||||||
|
image := &UploadImage{
|
||||||
|
UploaderUserID: opts.UploaderUserID,
|
||||||
|
Name: opts.Name,
|
||||||
|
FileSize: opts.FileSize,
|
||||||
|
Md5: opts.Md5,
|
||||||
|
Key: opts.Key,
|
||||||
|
}
|
||||||
|
if err := db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if err := tx.WithContext(ctx).Create(image).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "create image")
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts.IsDeletingPrevious {
|
||||||
|
if err := tx.WithContext(ctx).Where("type = ? AND question_id = ?", opts.Type, opts.QuestionID).Delete(&UploadImageQuestion{}).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "delete previous image question link")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := tx.WithContext(ctx).Create(&UploadImageQuestion{
|
||||||
|
Type: opts.Type,
|
||||||
|
UploadImageID: image.ID,
|
||||||
|
QuestionID: opts.QuestionID,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "create image question link")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return image, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *uploadImages) getBy(ctx context.Context, where string, args ...interface{}) ([]*UploadImage, error) {
|
||||||
|
var uploadImageQuestions []*UploadImageQuestion
|
||||||
|
if err := db.WithContext(ctx).Model(&UploadImageQuestion{}).Where(where, args...).Find(&uploadImageQuestions).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get image questions")
|
||||||
|
}
|
||||||
|
|
||||||
|
uploadImageIDs := lo.Map(uploadImageQuestions, func(item *UploadImageQuestion, _ int) uint {
|
||||||
|
return item.UploadImageID
|
||||||
|
})
|
||||||
|
|
||||||
|
var uploadImages []*UploadImage
|
||||||
|
if err := db.WithContext(ctx).Model(&UploadImage{}).Where("id IN ?", uploadImageIDs).Order("id ASC").Find(&uploadImages).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get images")
|
||||||
|
}
|
||||||
|
return uploadImages, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *uploadImages) GetByQuestionID(ctx context.Context, questionID uint) ([]*UploadImage, error) {
|
||||||
|
return db.getBy(ctx, "question_id = ?", questionID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetByQuestionIDs 批量获取多个提问的图片,按 question_id 分组返回(解决导出 N+1)。
|
||||||
|
// 实现:先按 IN 批量取关联行,再按 IN 批量取图片主体,最后在内存中按 question_id 归组,
|
||||||
|
// 将每个提问原本的 2 次查询降为整体 2 次查询。
|
||||||
|
func (db *uploadImages) GetByQuestionIDs(ctx context.Context, questionIDs []uint) (map[uint][]*UploadImage, error) {
|
||||||
|
result := make(map[uint][]*UploadImage)
|
||||||
|
if len(questionIDs) == 0 {
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var links []*UploadImageQuestion
|
||||||
|
if err := db.WithContext(ctx).Model(&UploadImageQuestion{}).Where("question_id IN ?", questionIDs).Find(&links).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get image questions batch")
|
||||||
|
}
|
||||||
|
if len(links) == 0 {
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
imageIDs := lo.Map(links, func(item *UploadImageQuestion, _ int) uint {
|
||||||
|
return item.UploadImageID
|
||||||
|
})
|
||||||
|
var images []*UploadImage
|
||||||
|
if err := db.WithContext(ctx).Model(&UploadImage{}).Where("id IN ?", imageIDs).Order("id ASC").Find(&images).Error; err != nil {
|
||||||
|
return nil, errors.Wrap(err, "get images batch")
|
||||||
|
}
|
||||||
|
imageByID := lo.SliceToMap(images, func(img *UploadImage) (uint, *UploadImage) {
|
||||||
|
return img.ID, img
|
||||||
|
})
|
||||||
|
|
||||||
|
for _, link := range links {
|
||||||
|
if img, ok := imageByID[link.UploadImageID]; ok {
|
||||||
|
result[link.QuestionID] = append(result[link.QuestionID], img)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *uploadImages) GetByTypeQuestionID(ctx context.Context, typ UploadImageQuestionType, questionID uint) ([]*UploadImage, error) {
|
||||||
|
return db.getBy(ctx, "type = ? AND question_id = ?", typ, questionID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteByQuestionID 删除某条提问时级联清理其全部上传图片记录(软删除,与提问保持一致)。
|
||||||
|
// 注意:question_id 列在关联表 upload_image_questions 上,不在 upload_images 表上,
|
||||||
|
// 需先查关联行拿到 imageID 列表,再软删图片主体并删除关联行(同一事务内完成)。
|
||||||
|
// 注:仅清理数据库记录,对象存储中的实际文件不在此处删除(避免误删复用资源)。
|
||||||
|
func (db *uploadImages) DeleteByQuestionID(ctx context.Context, questionID uint) error {
|
||||||
|
return db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
var links []*UploadImageQuestion
|
||||||
|
if err := tx.WithContext(ctx).Where("question_id = ?", questionID).Find(&links).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "get image questions for delete")
|
||||||
|
}
|
||||||
|
if len(links) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
imageIDs := lo.Map(links, func(item *UploadImageQuestion, _ int) uint {
|
||||||
|
return item.UploadImageID
|
||||||
|
})
|
||||||
|
if err := tx.WithContext(ctx).Where("id IN ?", imageIDs).Delete(&UploadImage{}).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "delete upload images by question id")
|
||||||
|
}
|
||||||
|
if err := tx.WithContext(ctx).Where("question_id = ?", questionID).Delete(&UploadImageQuestion{}).Error; err != nil {
|
||||||
|
return errors.Wrap(err, "delete image question links")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
// Copyright 2023 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 db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestUploadImages(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
db, cleanup := newTestDB(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
uploadImagesStore := NewUploadImagesStore(db)
|
||||||
|
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
test func(t *testing.T, ctx context.Context, db *uploadImages)
|
||||||
|
}{
|
||||||
|
{"Create", testUploadImagesCreate},
|
||||||
|
{"GetByQuestionID", testUploadImagesGetByQuestionID},
|
||||||
|
{"GetByTypeQuestionID", testUploadImagesGetByTypeQuestionID},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
t.Cleanup(func() {
|
||||||
|
if err := cleanup("upload_images"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
tc.test(t, ctx, uploadImagesStore.(*uploadImages))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testUploadImagesCreate(t *testing.T, ctx context.Context, db *uploadImages) {
|
||||||
|
got, err := db.Create(ctx, CreateUploadImageOptions{
|
||||||
|
Type: UploadImageQuestionTypeAsk,
|
||||||
|
QuestionID: 1,
|
||||||
|
UploaderUserID: 1,
|
||||||
|
Name: "test.png",
|
||||||
|
FileSize: 12345,
|
||||||
|
Md5: "d41d8cd98f00b204e9800998ecf8427e",
|
||||||
|
Key: "uploads/test.png",
|
||||||
|
IsDeletingPrevious: false,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
want := &UploadImage{
|
||||||
|
Model: got.Model,
|
||||||
|
UploaderUserID: 1,
|
||||||
|
Name: "test.png",
|
||||||
|
FileSize: 12345,
|
||||||
|
Md5: "d41d8cd98f00b204e9800998ecf8427e",
|
||||||
|
Key: "uploads/test.png",
|
||||||
|
}
|
||||||
|
require.Equal(t, want, got)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testUploadImagesGetByQuestionID(t *testing.T, ctx context.Context, db *uploadImages) {
|
||||||
|
_, err := db.Create(ctx, CreateUploadImageOptions{
|
||||||
|
Type: UploadImageQuestionTypeAsk,
|
||||||
|
QuestionID: 1,
|
||||||
|
UploaderUserID: 1,
|
||||||
|
Name: "test.png",
|
||||||
|
FileSize: 12345,
|
||||||
|
Md5: "d41d8cd98f00b204e9800998ecf8427e",
|
||||||
|
Key: "uploads/test.png",
|
||||||
|
IsDeletingPrevious: false,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
t.Run("normal", func(t *testing.T) {
|
||||||
|
got, err := db.GetByQuestionID(ctx, 1)
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
want := []*UploadImage{{
|
||||||
|
Model: got[0].Model,
|
||||||
|
UploaderUserID: 1,
|
||||||
|
Name: "test.png",
|
||||||
|
FileSize: 12345,
|
||||||
|
Md5: "d41d8cd98f00b204e9800998ecf8427e",
|
||||||
|
Key: "uploads/test.png",
|
||||||
|
}}
|
||||||
|
require.Equal(t, got, want)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("not found", func(t *testing.T) {
|
||||||
|
got, err := db.GetByQuestionID(ctx, 2)
|
||||||
|
require.Nil(t, err)
|
||||||
|
require.Equal(t, 0, len(got))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func testUploadImagesGetByTypeQuestionID(t *testing.T, ctx context.Context, db *uploadImages) {
|
||||||
|
_, err := db.Create(ctx, CreateUploadImageOptions{
|
||||||
|
Type: UploadImageQuestionTypeAsk,
|
||||||
|
QuestionID: 1,
|
||||||
|
UploaderUserID: 1,
|
||||||
|
Name: "test.png",
|
||||||
|
FileSize: 12345,
|
||||||
|
Md5: "d41d8cd98f00b204e9800998ecf8427e",
|
||||||
|
Key: "uploads/test.png",
|
||||||
|
IsDeletingPrevious: false,
|
||||||
|
})
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
t.Run("normal", func(t *testing.T) {
|
||||||
|
got, err := db.GetByTypeQuestionID(ctx, UploadImageQuestionTypeAsk, 1)
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
want := []*UploadImage{{
|
||||||
|
Model: got[0].Model,
|
||||||
|
UploaderUserID: 1,
|
||||||
|
Name: "test.png",
|
||||||
|
FileSize: 12345,
|
||||||
|
Md5: "d41d8cd98f00b204e9800998ecf8427e",
|
||||||
|
Key: "uploads/test.png",
|
||||||
|
}}
|
||||||
|
require.Equal(t, got, want)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("not found", func(t *testing.T) {
|
||||||
|
got, err := db.GetByTypeQuestionID(ctx, UploadImageQuestionTypeAsk, 2)
|
||||||
|
require.Nil(t, err)
|
||||||
|
require.Equal(t, 0, len(got))
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
// 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 db
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// UserBlock 记录用户拉黑关系(UserID 拉黑了 BlockedID)。
|
||||||
|
// 使用独立关联表而非在 users 上存 JSON,以获得:
|
||||||
|
// - (user_id, blocked_id) 唯一索引保证幂等,并发拉黑不会互相覆盖;
|
||||||
|
// - 判断是否拉黑走索引查询,无需反序列化整串 JSON。
|
||||||
|
//
|
||||||
|
// 注意:本表采用物理删除(取消拉黑即删行),不使用 gorm.DeletedAt 软删除,
|
||||||
|
// 否则「拉黑 → 取消 → 再拉黑」会因软删记录仍占用唯一索引而插入冲突。
|
||||||
|
type UserBlock struct {
|
||||||
|
ID uint `gorm:"primarykey"`
|
||||||
|
UserID uint `gorm:"not null;uniqueIndex:idx_user_block_unique"`
|
||||||
|
BlockedID uint `gorm:"not null;uniqueIndex:idx_user_block_unique"`
|
||||||
|
CreatedAt time.Time `json:"-"`
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user