feat: 议题功能,游客凭 5 位数字图片验证码提交
24 个文件变更
+1662
-10
fqh@example.com
| •internal/captcha/captcha.go | +295 -0 |
| •internal/captcha/captcha_test.go | +104 -0 |
| •internal/server/home.go | +1 -1 |
| •internal/server/issues.go | +277 -0 |
| •internal/server/issues_test.go | +290 -0 |
| •internal/server/repo.go | +2 -0 |
| •internal/server/server.go | +20 -0 |
| •internal/server/slash_test.go | +38 -0 |
| •internal/store/issues.go | +207 -0 |
| •internal/store/issues_test.go | +184 -0 |
| •internal/store/store.go | +13 -1 |
| •webroot/static/style.css | +49 -0 |
| •webroot/templates/issue.html | +50 -0 |
| •webroot/templates/issue_new.html | +62 -0 |
| •webroot/templates/issues.html | +61 -0 |
| •webroot/templates/layout.html | +1 -0 |
| •webroot/templates/repo_activity.html | +1 -1 |
| •webroot/templates/repo_blob.html | +1 -1 |
| •webroot/templates/repo_branches.html | +1 -1 |
| •webroot/templates/repo_commits.html | +1 -1 |
| •webroot/templates/repo_home.html | +1 -1 |
| •webroot/templates/repo_release.html | +1 -1 |
| •webroot/templates/repo_releases.html | +1 -1 |
| •webroot/templates/repo_settings.html | +1 -1 |
变更内容
diff --git a/internal/captcha/captcha.go b/internal/captcha/captcha.go
new file mode 100644
index 0000000..f6aab59
--- /dev/null
+++ b/internal/captcha/captcha.go
@@ -0,0 +1,295 @@
+// Package captcha 提供访客提交议题所需的 5 位数字图片验证码。
+//
+// 设计要点:
+// - 零第三方依赖:数字用 7 段码笔画绘制(随机旋转 + 抖动 + 干扰线噪点),
+// 标准库 image/png 直接编码,不引入字体文件;
+// - 验证码一次性:验证通过或过期即销毁,内存存储(gitcat 单实例部署),
+// 防止同一份验证码被反复重放。
+package captcha
+
+import (
+ "bytes"
+ "crypto/rand"
+ "encoding/hex"
+ "errors"
+ "image"
+ "image/color"
+ "image/png"
+ "math"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Store 是验证码的内存存储:id -> 一次性验证码。
+type Store struct {
+ mu sync.Mutex
+ items map[string]captchaItem
+ ttl time.Duration
+ last time.Time
+}
+
+type captchaItem struct {
+ code string
+ expires time.Time
+}
+
+// NewStore 创建验证码存储,ttl 为验证码有效期。
+func NewStore(ttl time.Duration) *Store {
+ return &Store{items: map[string]captchaItem{}, ttl: ttl, last: time.Now()}
+}
+
+// New 生成一条新验证码,返回存储 id(调用方应把 id 写入 Cookie,
+// 让用户提交时带上)。旧的同 id 记录自然过期,无需显式清理。
+func (s *Store) New() (id string, err error) {
+ b := make([]byte, 16)
+ if _, err = rand.Read(b); err != nil {
+ return "", err
+ }
+ id = hex.EncodeToString(b)
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if time.Since(s.last) > time.Minute {
+ s.sweep(time.Now())
+ }
+ s.items[id] = captchaItem{code: randomDigits(5), expires: time.Now().Add(s.ttl)}
+ return id, nil
+}
+
+// Verify 校验用户输入(输入中的空白会被忽略)。无论对错,验证码都立即销毁(一次性)。
+func (s *Store) Verify(id, input string) bool {
+ if id == "" || len(input) > 16 {
+ return false
+ }
+ input = NormalizeInput(input)
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ item, ok := s.items[id]
+ if !ok {
+ return false
+ }
+ delete(s.items, id) // 一次性:不管对错都作废
+ if time.Now().After(item.expires) {
+ return false
+ }
+ return input == item.code
+}
+
+// PNG 渲染指定 id 的验证码图片;不存在或已过期时返回错误。
+// 与 Verify 不同,渲染不会销毁验证码(图片可能被浏览器重新加载)。
+func (s *Store) PNG(id string) ([]byte, error) {
+ s.mu.Lock()
+ item, ok := s.items[id]
+ s.mu.Unlock()
+ if !ok || time.Now().After(item.expires) {
+ return nil, errCaptchaNotFound
+ }
+ return PNG(item.code)
+}
+
+// errCaptchaNotFound 表示验证码 id 不存在或已过期。
+var errCaptchaNotFound = errors.New("验证码不存在或已过期")
+
+// Code 返回 id 对应的验证码明文。id 由 HttpOnly Cookie 持有、只有发起请求的
+// 浏览器自己能看到,因此暴露它不会帮助第三方绕过验证;主要供测试与排障使用。
+func (s *Store) Code(id string) (string, bool) {
+ if id == "" {
+ return "", false
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ item, ok := s.items[id]
+ if !ok || time.Now().After(item.expires) {
+ return "", false
+ }
+ return item.code, true
+}
+
+// sweep 清掉过期项。调用方需持有锁。
+func (s *Store) sweep(now time.Time) {
+ for id, item := range s.items {
+ if now.After(item.expires) {
+ delete(s.items, id)
+ }
+ }
+ s.last = now
+}
+
+func randomDigits(n int) string {
+ b := make([]byte, n)
+ _, _ = rand.Read(b)
+ for i := range b {
+ b[i] = '0' + b[i]%10
+ }
+ return string(b)
+}
+
+// ---------------------------------------------------------------- 图片渲染
+
+// 画布与字形尺寸(像素)。
+const (
+ digitW = 18 // 单个数字笔画区域的宽
+ digitH = 30 // 单个数字笔画区域的高
+ cellW = 26 // 数字单元(含间距)
+ cellH = 40
+ padX = 10
+ canvasW = padX*2 + cellW*5
+ canvasH = cellH + 12
+ strokeR = 2 // 笔画半径(线宽 = strokeR*2+1)
+ rotateRange = 0.35
+)
+
+// segDigits 是数字 0-9 的 7 段码段定义,坐标基于 digitW×digitH 字形框。
+var segDigits = map[byte][][][2]int{
+ '0': {{{1, 0}, {17, 0}}, {{19, 2}, {19, 13}}, {{19, 17}, {19, 28}}, {{1, 30}, {17, 30}}, {{-1, 17}, {-1, 28}}, {{-1, 2}, {-1, 13}}},
+ '1': {{{7, 4}, {13, 0}}, {{13, 0}, {13, 30}}},
+ '2': {{{1, 0}, {17, 0}}, {{19, 2}, {19, 13}}, {{1, 15}, {17, 15}}, {{-1, 17}, {-1, 28}}, {{1, 30}, {17, 30}}},
+ '3': {{{1, 0}, {17, 0}}, {{19, 2}, {19, 13}}, {{1, 15}, {17, 15}}, {{19, 17}, {19, 28}}, {{1, 30}, {17, 30}}},
+ '4': {{{-1, 2}, {-1, 13}}, {{1, 15}, {17, 15}}, {{19, 2}, {19, 30}}},
+ '5': {{{1, 0}, {17, 0}}, {{-1, 2}, {-1, 13}}, {{1, 15}, {17, 15}}, {{19, 17}, {19, 28}}, {{1, 30}, {17, 30}}},
+ '6': {{{1, 0}, {17, 0}}, {{-1, 2}, {-1, 28}}, {{1, 15}, {17, 15}}, {{19, 17}, {19, 28}}, {{1, 30}, {17, 30}}},
+ '7': {{{1, 0}, {17, 0}}, {{19, 2}, {19, 30}}},
+ '8': {{{1, 0}, {17, 0}}, {{19, 2}, {19, 13}}, {{1, 15}, {17, 15}}, {{19, 17}, {19, 28}}, {{1, 30}, {17, 30}}, {{-1, 17}, {-1, 28}}, {{-1, 2}, {-1, 13}}},
+ '9': {{{1, 0}, {17, 0}}, {{19, 2}, {19, 13}}, {{1, 15}, {17, 15}}, {{19, 17}, {19, 28}}, {{-1, 2}, {-1, 13}}, {{1, 30}, {17, 30}}},
+}
+
+// PNG 把 5 位验证码渲染成带干扰的 PNG 图片。
+func PNG(code string) ([]byte, error) {
+ img := image.NewRGBA(image.Rect(0, 0, canvasW, canvasH))
+ bg := color.RGBA{244, 249, 247, 255}
+ ink := color.RGBA{35, 64, 82, 255}
+ noise := color.RGBA{148, 178, 196, 255}
+ drawRect(img, img.Rect, bg)
+
+ // 干扰曲线:几条跨画布的折线
+ for i := 0; i < 4; i++ {
+ x := float64(randRange(0, canvasW/3))
+ y := float64(randRange(4, canvasH-4))
+ for x < float64(canvasW) {
+ nx := x + float64(randRange(8, 22))
+ ny := clamp(y+float64(randRange(-14, 14)), 3, canvasH-4)
+ drawThickLine(img, pt(x, y), pt(nx, ny), 1, noise)
+ x, y = nx, ny
+ }
+ }
+ // 噪点
+ for i := 0; i < 90; i++ {
+ x, y := randRange(0, canvasW-1), randRange(0, canvasH-1)
+ img.Set(x, y, noise)
+ }
+
+ // 数字:逐位随机旋转 + 抖动
+ for i := 0; i < len(code) && i < 5; i++ {
+ ang := (float64(randRange(0, 100))/100 - 0.5) * 2 * rotateRange
+ jx := randRange(0, 5)
+ jy := randRange(0, 5)
+ cx := float64(padX + i*cellW + cellW/2)
+ cy := float64(canvasH/2 - 2)
+ rot := func(p [2]float64) [2]float64 {
+ dx, dy := p[0]-cx, p[1]-cy
+ c, s := math.Cos(ang), math.Sin(ang)
+ return [2]float64{cx + dx*c - dy*s, cy + dx*s + dy*c}
+ }
+ segs := segDigits[code[i]]
+ ox := float64(padX + i*cellW + jx)
+ oy := float64(6 + jy)
+ for _, seg := range segs {
+ p0 := rot([2]float64{ox + float64(seg[0][0])*digitW/20, oy + float64(seg[0][1])*digitH/30})
+ p1 := rot([2]float64{ox + float64(seg[1][0])*digitW/20, oy + float64(seg[1][1])*digitH/30})
+ drawThickLine(img, p0, p1, strokeR, ink)
+ }
+ }
+
+ var buf bytes.Buffer
+ if err := png.Encode(&buf, img); err != nil {
+ return nil, err
+ }
+ return buf.Bytes(), nil
+}
+
+func pt(x, y float64) [2]float64 { return [2]float64{x, y} }
+
+func randRange(lo, hi int) int {
+ if hi <= lo {
+ return lo
+ }
+ b := make([]byte, 1)
+ _, _ = rand.Read(b)
+ return lo + int(b[0])%int(hi-lo+1)
+}
+
+func clamp(v, lo, hi float64) float64 {
+ if v < lo {
+ return lo
+ }
+ if v > hi {
+ return hi
+ }
+ return v
+}
+
+func drawRect(img *image.RGBA, r image.Rectangle, c color.RGBA) {
+ for y := r.Min.Y; y < r.Max.Y; y++ {
+ for x := r.Min.X; x < r.Max.X; x++ {
+ img.Set(x, y, c)
+ }
+ }
+}
+
+// drawThickLine 用 Bresenham + 圆点笔画画粗线段。
+func drawThickLine(img *image.RGBA, p0, p1 [2]float64, radius int, c color.RGBA) {
+ x0, y0 := int(math.Round(p0[0])), int(math.Round(p0[1]))
+ x1, y1 := int(math.Round(p1[0])), int(math.Round(p1[1]))
+ dx, dy := abs(x1-x0), -abs(y1-y0)
+ sx, sy := -1, -1
+ if x0 < x1 {
+ sx = 1
+ }
+ if y0 < y1 {
+ sy = 1
+ }
+ err := dx + dy
+ for {
+ fillCircle(img, x0, y0, radius, c)
+ if x0 == x1 && y0 == y1 {
+ break
+ }
+ e2 := 2 * err
+ if e2 >= dy {
+ err += dy
+ x0 += sx
+ }
+ if e2 <= dx {
+ err += dx
+ y0 += sy
+ }
+ }
+}
+
+func fillCircle(img *image.RGBA, cx, cy, r int, c color.RGBA) {
+ for y := cy - r; y <= cy+r; y++ {
+ for x := cx - r; x <= cx+r; x++ {
+ if (x-cx)*(x-cx)+(y-cy)*(y-cy) <= r*r {
+ img.Set(x, y, c)
+ }
+ }
+ }
+}
+
+func abs(v int) int {
+ if v < 0 {
+ return -v
+ }
+ return v
+}
+
+// NormalizeInput 去掉用户输入里的空白,便于宽容比较。
+func NormalizeInput(s string) string {
+ var b strings.Builder
+ for _, r := range s {
+ if r != ' ' && r != '\t' && r != '\n' && r != '\r' {
+ b.WriteRune(r)
+ }
+ }
+ return b.String()
+}
\ No newline at end of file
diff --git a/internal/captcha/captcha_test.go b/internal/captcha/captcha_test.go
new file mode 100644
index 0000000..18a4d20
--- /dev/null
+++ b/internal/captcha/captcha_test.go
@@ -0,0 +1,104 @@
+package captcha
+
+import (
+ "bytes"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestStoreVerifyOnce(t *testing.T) {
+ s := NewStore(5 * time.Minute)
+ id, err := s.New()
+ if err != nil {
+ t.Fatalf("New 失败: %v", err)
+ }
+ code, ok := s.Code(id)
+ if !ok || len(code) != 5 || strings.Trim(code, "0123456789") != "" {
+ t.Fatalf("验证码应为 5 位数字,实际 %q ok=%v", code, ok)
+ }
+ // 错误输入:销毁且不通过
+ if s.Verify(id, "99999") {
+ t.Error("错误验证码不应通过")
+ }
+ if _, ok := s.Code(id); ok {
+ t.Error("校验失败后验证码也应销毁(一次性)")
+ }
+}
+
+func TestStoreSingleUse(t *testing.T) {
+ s := NewStore(5 * time.Minute)
+ id, _ := s.New()
+ code, _ := s.Code(id)
+ if !s.Verify(id, code) {
+ t.Fatal("正确验证码应通过")
+ }
+ if s.Verify(id, code) {
+ t.Error("同一验证码不能使用第二次(防重放)")
+ }
+}
+
+func TestStoreExpired(t *testing.T) {
+ s := NewStore(10 * time.Millisecond)
+ id, _ := s.New()
+ code, _ := s.Code(id)
+ time.Sleep(30 * time.Millisecond)
+ if s.Verify(id, code) {
+ t.Error("过期验证码不应通过")
+ }
+ if _, err := s.PNG(id); err == nil {
+ t.Error("过期验证码不应能渲染图片")
+ }
+}
+
+func TestStoreVerifyNormalizesInput(t *testing.T) {
+ s := NewStore(5 * time.Minute)
+ id, _ := s.New()
+ code, _ := s.Code(id)
+ spaced := strings.Join(strings.Split(code, ""), " ")
+ if !s.Verify(id, spaced) {
+ t.Errorf("带空格输入 %q 应被宽容处理", spaced)
+ }
+}
+
+func TestStoreUnknownID(t *testing.T) {
+ s := NewStore(5 * time.Minute)
+ if s.Verify("no-such-id", "12345") {
+ t.Error("未知 id 不应通过")
+ }
+ if s.Verify("", "12345") {
+ t.Error("空 id 不应通过")
+ }
+}
+
+func TestPNGRender(t *testing.T) {
+ png, err := PNG("0123456789"[2:7]) // "23456"
+ if err != nil {
+ t.Fatalf("PNG 渲染失败: %v", err)
+ }
+ // PNG 文件签名
+ if !bytes.HasPrefix(png, []byte{0x89, 'P', 'N', 'G'}) {
+ t.Fatal("产物不是合法 PNG")
+ }
+ if len(png) < 500 {
+ t.Fatalf("图片过小(%d 字节),疑似内容异常", len(png))
+ }
+ // 每位数字都必须有字形定义,避免渲染出空白图
+ for _, d := range []byte("0123456789") {
+ if _, ok := segDigits[d]; !ok {
+ t.Errorf("数字 %q 缺少字形定义", d)
+ }
+ }
+}
+
+func TestSweepRemovesExpired(t *testing.T) {
+ s := NewStore(10 * time.Millisecond)
+ id, _ := s.New()
+ time.Sleep(30 * time.Millisecond)
+ s.mu.Lock()
+ s.sweep(time.Now())
+ s.mu.Unlock()
+ if _, ok := s.Code(id); ok {
+ t.Error("sweep 后过期项应被清除")
+ }
+}
\ No newline at end of file
diff --git a/internal/server/home.go b/internal/server/home.go
index 7afe507..f8c60f9 100644
--- a/internal/server/home.go
+++ b/internal/server/home.go
@@ -12,7 +12,7 @@ import (
var reservedRepoNames = map[string]bool{
"admin": true, "login": true, "logout": true, "install": true, "new": true,
"settings": true, "static": true, "media": true, "favicon.ico": true, "api": true,
- "avatars": true, "assets": true, "help": true, "about": true,
+ "avatars": true, "assets": true, "help": true, "about": true, "issues": true,
}
func (s *Server) handleHome(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/server/issues.go b/internal/server/issues.go
new file mode 100644
index 0000000..9a29be3
--- /dev/null
+++ b/internal/server/issues.go
@@ -0,0 +1,277 @@
+// 议题(Issues):所有访客都能查看与提交,游客提交需通过 5 位数字图片
+// 验证码(一次性,防重放);登录成员走会话 CSRF。仓库创建者与管理员可以
+// 关闭 / 重新打开 / 删除议题。
+package server
+
+import (
+ "fmt"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+
+ "gitcat/internal/captcha"
+ "gitcat/internal/store"
+)
+
+// 议题相关的限制。
+const (
+ maxIssueTitleRunes = 120
+ maxIssueContentRunes = 5000
+ maxGuestNicknameRunes = 30
+ issuesPerPage = 20
+ captchaTTL = 10 * time.Minute
+ CaptchaCookieName = "gitcat_captcha"
+)
+
+// loadIssue 按路径中的编号读取议题并校验归属仓库。
+func (s *Server) loadIssue(w http.ResponseWriter, r *http.Request, repo *store.Repo) (*store.Issue, bool) {
+ number, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
+ if err != nil || number <= 0 {
+ s.renderError(w, r, http.StatusNotFound, "议题不存在")
+ return nil, false
+ }
+ issue, err := s.st.IssueByNumber(repo.ID, number)
+ if err != nil {
+ s.renderError(w, r, http.StatusNotFound, "议题不存在")
+ return nil, false
+ }
+ return issue, true
+}
+
+// handleIssuesList 议题列表,支持 ?status=closed 与 ?page= 分页。
+func (s *Server) handleIssuesList(w http.ResponseWriter, r *http.Request) {
+ repo, dir, ok := s.loadRepo(w, r)
+ if !ok {
+ return
+ }
+ ref := s.pickRef(dir, repo, "")
+ status := r.URL.Query().Get("status")
+ if status != store.IssueOpen && status != store.IssueClosed {
+ status = ""
+ }
+ pageNo, _ := strconv.Atoi(r.URL.Query().Get("page"))
+ if pageNo < 1 {
+ pageNo = 1
+ }
+ open, closed := s.st.IssueCounts(repo.ID)
+ issues, err := s.st.IssuesByRepo(repo.ID, status, issuesPerPage+1, (pageNo-1)*issuesPerPage)
+ if err != nil {
+ s.renderError(w, r, http.StatusInternalServerError, "读取议题失败:"+err.Error())
+ return
+ }
+ hasMore := len(issues) > issuesPerPage
+ if hasMore {
+ issues = issues[:issuesPerPage]
+ }
+
+ p := s.page(r, repo.Name+" · 议题")
+ p.Active = "repo"
+ p.Data = s.repoCommon(r, repo, dir, ref)
+ p.Data["Tab"] = "issues"
+ p.Data["Issues"] = issues
+ p.Data["Status"] = status
+ p.Data["OpenCount"] = open
+ p.Data["ClosedCount"] = closed
+ p.Data["Page"] = pageNo
+ p.Data["HasPrev"] = pageNo > 1
+ p.Data["HasNext"] = hasMore
+ s.render(w, r, "issues", p)
+}
+
+// handleIssueNewPage 新建议题表单。游客会看到验证码。
+func (s *Server) handleIssueNewPage(w http.ResponseWriter, r *http.Request) {
+ repo, dir, ok := s.loadRepo(w, r)
+ if !ok {
+ return
+ }
+ ref := s.pickRef(dir, repo, "")
+ p := s.page(r, repo.Name+" · 提交议题")
+ p.Active = "repo"
+ p.Data = s.repoCommon(r, repo, dir, ref)
+ p.Data["Tab"] = "issues"
+ s.render(w, r, "issue_new", p)
+}
+
+// handleIssueCreate 提交议题:登录成员校验 CSRF,游客校验验证码。
+func (s *Server) handleIssueCreate(w http.ResponseWriter, r *http.Request) {
+ repo, dir, ok := s.loadRepo(w, r)
+ if !ok {
+ return
+ }
+ ref := s.pickRef(dir, repo, "")
+ u := userFrom(r.Context())
+ title := strings.TrimSpace(r.FormValue("title"))
+ content := strings.TrimSpace(r.FormValue("content"))
+
+ fail := func(msg string) {
+ if u == nil {
+ // 游客:flash 提示并回到表单;验证码已随本次校验作废,表单里会重新加载
+ setFlash(w, msg)
+ http.Redirect(w, r, "/"+repo.Name+"/issues/new", http.StatusFound)
+ return
+ }
+ p := s.page(r, repo.Name+" · 提交议题")
+ p.Active = "repo"
+ p.Error = msg
+ p.Data = s.repoCommon(r, repo, dir, ref)
+ p.Data["Tab"] = "issues"
+ p.Data["Title"] = title
+ p.Data["Content"] = content
+ w.WriteHeader(http.StatusBadRequest)
+ s.render(w, r, "issue_new", p)
+ }
+
+ switch {
+ case title == "":
+ fail("请填写标题")
+ return
+ case len([]rune(title)) > maxIssueTitleRunes:
+ fail(fmt.Sprintf("标题过长(最多 %d 字)", maxIssueTitleRunes))
+ return
+ case len([]rune(content)) > maxIssueContentRunes:
+ fail(fmt.Sprintf("描述过长(最多 %d 字)", maxIssueContentRunes))
+ return
+ }
+
+ if u == nil {
+ // 游客:必须通过一次性图片验证码
+ c, err := r.Cookie(CaptchaCookieName)
+ input := captcha.NormalizeInput(r.FormValue("captcha"))
+ if err != nil || c.Value == "" || !s.captchas.Verify(c.Value, input) {
+ fail("验证码不正确或已过期,请输入最新一张图片里的 5 位数字")
+ return
+ }
+ nickname := store.SanitizeNickname(r.FormValue("nickname"), maxGuestNicknameRunes)
+ if nickname == "" {
+ nickname = "访客"
+ }
+ if _, err := s.st.CreateIssue(repo.ID, nil, "guest", nickname, title, content); err != nil {
+ fail("提交失败:" + err.Error())
+ return
+ }
+ // 清掉已消费的验证码 Cookie
+ http.SetCookie(w, &http.Cookie{Name: CaptchaCookieName, Value: "", Path: "/", MaxAge: -1, HttpOnly: true})
+ setFlash(w, "议题已提交,感谢反馈!")
+ http.Redirect(w, r, "/"+repo.Name+"/issues", http.StatusFound)
+ return
+ }
+
+ if !s.checkCSRF(r) {
+ fail("表单已过期,请返回重试")
+ return
+ }
+ if _, err := s.st.CreateIssue(repo.ID, &u.ID, u.Username, u.Display(), title, content); err != nil {
+ fail("提交失败:" + err.Error())
+ return
+ }
+ setFlash(w, "议题已提交")
+ http.Redirect(w, r, "/"+repo.Name+"/issues", http.StatusFound)
+}
+
+// handleIssueDetail 议题详情。
+func (s *Server) handleIssueDetail(w http.ResponseWriter, r *http.Request) {
+ repo, dir, ok := s.loadRepo(w, r)
+ if !ok {
+ return
+ }
+ issue, ok := s.loadIssue(w, r, repo)
+ if !ok {
+ return
+ }
+ ref := s.pickRef(dir, repo, "")
+ p := s.page(r, fmt.Sprintf("%s · #%d %s", repo.Name, issue.Number, issue.Title))
+ p.Active = "repo"
+ p.Data = s.repoCommon(r, repo, dir, ref)
+ p.Data["Tab"] = "issues"
+ p.Data["Issue"] = issue
+ s.render(w, r, "issue", p)
+}
+
+// handleIssueStatus 关闭 / 重新打开议题(仓库创建者或管理员)。
+func (s *Server) handleIssueStatus(w http.ResponseWriter, r *http.Request) {
+ repo, _, ok := s.loadRepo(w, r)
+ if !ok {
+ return
+ }
+ issue, ok := s.loadIssue(w, r, repo)
+ if !ok {
+ return
+ }
+ u := userFrom(r.Context())
+ if !canManageRepo(u, repo) {
+ s.renderError(w, r, http.StatusForbidden, "只有项目创建者或管理员可以操作议题")
+ return
+ }
+ if !s.checkCSRF(r) {
+ s.renderError(w, r, http.StatusForbidden, "表单已过期,请重试")
+ return
+ }
+ status := store.IssueClosed
+ if issue.Status == store.IssueClosed {
+ status = store.IssueOpen
+ }
+ if err := s.st.SetIssueStatus(repo.ID, issue.Number, status); err != nil {
+ s.renderError(w, r, http.StatusInternalServerError, "操作失败:"+err.Error())
+ return
+ }
+ if status == store.IssueClosed {
+ setFlash(w, fmt.Sprintf("议题 #%d 已关闭", issue.Number))
+ } else {
+ setFlash(w, fmt.Sprintf("议题 #%d 已重新打开", issue.Number))
+ }
+ http.Redirect(w, r, fmt.Sprintf("/%s/issues/%d", repo.Name, issue.Number), http.StatusFound)
+}
+
+// handleIssueDelete 删除议题(仓库创建者或管理员)。
+func (s *Server) handleIssueDelete(w http.ResponseWriter, r *http.Request) {
+ repo, _, ok := s.loadRepo(w, r)
+ if !ok {
+ return
+ }
+ issue, ok := s.loadIssue(w, r, repo)
+ if !ok {
+ return
+ }
+ u := userFrom(r.Context())
+ if !canManageRepo(u, repo) {
+ s.renderError(w, r, http.StatusForbidden, "只有项目创建者或管理员可以删除议题")
+ return
+ }
+ if !s.checkCSRF(r) {
+ s.renderError(w, r, http.StatusForbidden, "表单已过期,请重试")
+ return
+ }
+ if err := s.st.DeleteIssue(issue.ID); err != nil {
+ s.renderError(w, r, http.StatusInternalServerError, "删除失败:"+err.Error())
+ return
+ }
+ setFlash(w, fmt.Sprintf("议题 #%d 已删除", issue.Number))
+ http.Redirect(w, r, "/"+repo.Name+"/issues", http.StatusFound)
+}
+
+// handleIssueCaptcha 输出验证码图片,并写入承载验证码 id 的 Cookie。
+// 每次请求都生成新验证码并重置 Cookie,页面里的「换一张」因此天然可用。
+func (s *Server) handleIssueCaptcha(w http.ResponseWriter, r *http.Request) {
+ id, err := s.captchas.New()
+ if err != nil {
+ http.Error(w, "生成验证码失败", http.StatusInternalServerError)
+ return
+ }
+ http.SetCookie(w, &http.Cookie{
+ Name: CaptchaCookieName,
+ Value: id,
+ Path: "/",
+ HttpOnly: true,
+ SameSite: http.SameSiteLaxMode,
+ MaxAge: int(captchaTTL.Seconds()),
+ })
+ w.Header().Set("Content-Type", "image/png")
+ w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate")
+ w.WriteHeader(http.StatusOK)
+ png, err := s.captchas.PNG(id)
+ if err != nil {
+ return
+ }
+ _, _ = w.Write(png)
+}
\ No newline at end of file
diff --git a/internal/server/issues_test.go b/internal/server/issues_test.go
new file mode 100644
index 0000000..a00ae5f
--- /dev/null
+++ b/internal/server/issues_test.go
@@ -0,0 +1,290 @@
+package server
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+
+ "gitcat/internal/store"
+)
+
+// getCaptchaID 走真实接口请求一张验证码图,返回 Cookie 里的 id 与对应明文。
+func getCaptchaID(t *testing.T, srv *Server, repo string) string {
+ t.Helper()
+ r := httptest.NewRequest(http.MethodGet, "/"+repo+"/issues/captcha.png", nil)
+ w := httptest.NewRecorder()
+ srv.Handler().ServeHTTP(w, r)
+ if w.Code != http.StatusOK {
+ t.Fatalf("验证码接口返回 %d", w.Code)
+ }
+ if ct := w.Header().Get("Content-Type"); ct != "image/png" {
+ t.Fatalf("验证码 Content-Type = %q,期望 image/png", ct)
+ }
+ for _, c := range w.Result().Cookies() {
+ if c.Name == CaptchaCookieName {
+ return c.Value
+ }
+ }
+ t.Fatal("验证码响应未设置 Cookie")
+ return ""
+}
+
+// postIssue 模拟表单提交。
+func postIssue(srv *Server, repo string, form url.Values, cookie *http.Cookie, csrf string) *httptest.ResponseRecorder {
+ form.Set("csrf", csrf)
+ r := httptest.NewRequest(http.MethodPost, "/"+repo+"/issues/new", strings.NewReader(form.Encode()))
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ if cookie != nil {
+ r.AddCookie(cookie)
+ }
+ w := httptest.NewRecorder()
+ srv.Handler().ServeHTTP(w, r)
+ return w
+}
+
+func TestIssuesPageRender(t *testing.T) {
+ srv, st, _, _ := newTestServer(t)
+ dir := makeRepo(t, srv, st, "issuetab", nil)
+ commitFiles(t, dir, "first", map[string]string{"a.go": "package a\n"})
+
+ page := getPage(srv, "/issuetab")
+ if !strings.Contains(page, `href="/issuetab/issues"`) {
+ t.Error("仓库 Tab 缺少议题入口")
+ }
+ if page := getPage(srv, "/issuetab/issues"); !strings.Contains(page, "还没有议题") {
+ t.Error("空列表应渲染空状态")
+ }
+ if page := getPage(srv, "/issuetab/issues"); !strings.Contains(page, "还没有议题") {
+ t.Error("议题列表页应可访问")
+ }
+ if page := getPage(srv, "/issuetab/issues/new"); !strings.Contains(page, "captcha.png") {
+ t.Error("游客表单应包含验证码图片")
+ }
+}
+
+// TestIssueGuestFlow 是本功能的硬性要求:游客必须过 5 位数字验证码才能提交。
+func TestIssueGuestFlow(t *testing.T) {
+ srv, st, _, _ := newTestServer(t)
+ dir := makeRepo(t, srv, st, "visitor", nil)
+ commitFiles(t, dir, "first", map[string]string{"a.go": "package a\n"})
+
+ form := url.Values{"title": {"游客报告的问题"}, "content": {"复现步骤……"}, "nickname": {"路 人 甲"}}
+ id := getCaptchaID(t, srv, "visitor")
+
+ // 1) 没带验证码 Cookie → 拒绝
+ w := postIssue(srv, "visitor", cloneForm(form), nil, "")
+ if w.Code != http.StatusFound {
+ t.Fatalf("无验证码提交应重定向回表单,实际 %d", w.Code)
+ }
+ if f := flashOf(w); !strings.Contains(f, "验证码") {
+ t.Errorf("应提示验证码错误,实际 flash=%q", f)
+ }
+
+ // 2) 错误验证码 → 拒绝(正确码同时被作废,所以重新取一张)
+ id = getCaptchaID(t, srv, "visitor")
+ w = postIssue(srv, "visitor", cloneForm(form), &http.Cookie{Name: CaptchaCookieName, Value: id}, "")
+ if !strings.Contains(flashOf(w), "验证码") {
+ t.Errorf("错误验证码应被拒绝,实际 flash=%q", flashOf(w))
+ }
+
+ // 3) 正确验证码 → 创建成功,作者为游客快照
+ id = getCaptchaID(t, srv, "visitor")
+ code, _ := srv.captchas.Code(id)
+ form.Set("captcha", code)
+ w = postIssue(srv, "visitor", cloneForm(form), &http.Cookie{Name: CaptchaCookieName, Value: id}, "")
+ if w.Code != http.StatusFound || !strings.Contains(w.Header().Get("Location"), "/visitor/issues") {
+ t.Fatalf("正确验证码应创建成功并跳转列表,实际 %d -> %s", w.Code, w.Header().Get("Location"))
+ }
+ issue, err := st.IssueByNumber(mustRepoID(t, st, "visitor"), 1)
+ if err != nil {
+ t.Fatalf("议题未落库: %v", err)
+ }
+ if issue.AuthorUsername != "guest" || issue.UserID != nil {
+ t.Errorf("游客议题作者快照错误: %q user_id=%v", issue.AuthorUsername, issue.UserID)
+ }
+ if issue.AuthorDisplay != "路 人 甲" {
+ t.Errorf("游客昵称 = %q", issue.AuthorDisplay)
+ }
+
+ // 4) 验证码一次性:同一 id 第二次提交(即使码正确)必须失败
+ w = postIssue(srv, "visitor", cloneForm(form), &http.Cookie{Name: CaptchaCookieName, Value: id}, "")
+ if !strings.Contains(flashOf(w), "验证码") {
+ t.Errorf("验证码应一次性,重放应被拒,实际 flash=%q", flashOf(w))
+ }
+
+ // 5) 列表与详情页可见
+ page := getPage(srv, "/visitor/issues")
+ if !strings.Contains(page, "游客报告的问题") || !strings.Contains(page, "路 人 甲") {
+ t.Error("列表页应显示游客议题")
+ }
+ if page := getPage(srv, "/visitor/issues/1"); !strings.Contains(page, "复现步骤") || !strings.Contains(page, "#1") {
+ t.Error("详情页应显示议题内容与编号")
+ }
+ // 详情页 Markdown 被转义为安全 HTML
+ if page := getPage(srv, "/visitor/issues/1"); strings.Contains(page, "<script>alert") {
+ t.Error("议题内容中的 HTML 不应原样输出")
+ }
+}
+
+// TestIssueLoggedInFlow 登录成员免验证码、走 CSRF。
+func TestIssueLoggedInFlow(t *testing.T) {
+ srv, st, alice, _ := newTestServer(t)
+ dir := makeRepo(t, srv, st, "member", alice)
+ commitFiles(t, dir, "first", map[string]string{"a.go": "package a\n"})
+
+ const sid, csrf = "issue-session", "issue-csrf"
+ if err := st.CreateSession(sid, alice.ID, csrf, 3600e9, "127.0.0.1", "test"); err != nil {
+ t.Fatalf("建会话失败: %v", err)
+ }
+ cookie := &http.Cookie{Name: SessionCookieName, Value: sid}
+
+ // 缺 CSRF → 400(fail 走页面渲染)
+ form := url.Values{"title": {"成员的问题"}}
+ if w := postIssue(srv, "member", cloneForm(form), cookie, ""); w.Code != http.StatusBadRequest {
+ t.Fatalf("缺 CSRF 应 400,实际 %d", w.Code)
+ }
+
+ // 正确 CSRF → 成功
+ w := postIssue(srv, "member", cloneForm(form), cookie, csrf)
+ if w.Code != http.StatusFound {
+ t.Fatalf("带 CSRF 提交应成功,实际 %d:%s", w.Code, w.Body.String())
+ }
+ issue, err := st.IssueByNumber(mustRepoID(t, st, "member"), 1)
+ if err != nil {
+ t.Fatalf("议题未落库: %v", err)
+ }
+ if issue.AuthorUsername != "alice" || issue.UserID == nil {
+ t.Errorf("成员议题作者应为 alice: %q", issue.AuthorUsername)
+ }
+ // 无验证码字段也要求不校验验证码 Cookie —— 登录用户完全不需要验证码
+}
+
+// TestIssueManagePermissions 关闭 / 重开 / 删除仅限仓库创建者与管理员。
+func TestIssueManagePermissions(t *testing.T) {
+ srv, st, alice, bob := newTestServer(t)
+ dir := makeRepo(t, srv, st, "manage", alice)
+ commitFiles(t, dir, "first", map[string]string{"a.go": "package a\n"})
+ if _, err := st.CreateIssue(mustRepoID(t, st, "manage"), nil, "guest", "访客", "待处理", ""); err != nil {
+ t.Fatalf("造议题失败: %v", err)
+ }
+
+ bobSid, bobCsrf := "bob-session", "bob-csrf"
+ if err := st.CreateSession(bobSid, bob.ID, bobCsrf, 3600e9, "127.0.0.1", "test"); err != nil {
+ t.Fatalf("建会话失败: %v", err)
+ }
+
+ postStatus := func(user *store.User, csrf string) *httptest.ResponseRecorder {
+ r := httptest.NewRequest(http.MethodPost, "/manage/issues/1/status", strings.NewReader(url.Values{"csrf": {csrf}}.Encode()))
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ if user != nil {
+ sid := user.Username + "-sess"
+ if err := st.CreateSession(sid, user.ID, csrf, 3600e9, "127.0.0.1", "test"); err != nil {
+ t.Fatalf("建会话失败: %v", err)
+ }
+ r.AddCookie(&http.Cookie{Name: SessionCookieName, Value: sid})
+ }
+ w := httptest.NewRecorder()
+ srv.Handler().ServeHTTP(w, r)
+ return w
+ }
+
+ // 游客 → 403
+ if w := postStatus(nil, ""); w.Code != http.StatusForbidden {
+ t.Errorf("游客关闭议题应 403,实际 %d", w.Code)
+ }
+ // 无关成员 → 403
+ if w := postStatus(bob, bobCsrf); w.Code != http.StatusForbidden {
+ t.Errorf("无关成员关闭议题应 403,实际 %d", w.Code)
+ }
+ // 管理员 → 成功关闭
+ if w := postStatus(alice, "alice-sess-csrf"); w.Code != http.StatusFound {
+ t.Fatalf("管理员关闭议题应成功,实际 %d", w.Code)
+ }
+ issue, _ := st.IssueByNumber(mustRepoID(t, st, "manage"), 1)
+ if issue.Status != store.IssueClosed {
+ t.Errorf("议题状态 = %q,期望 closed", issue.Status)
+ }
+
+ // 删除同理:无关成员 403,管理员成功
+ del := func(user *store.User, csrf string) *httptest.ResponseRecorder {
+ r := httptest.NewRequest(http.MethodPost, "/manage/issues/1/delete", strings.NewReader(url.Values{"csrf": {csrf}}.Encode()))
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ if user != nil {
+ sid := user.Username + "-sess"
+ _ = st.CreateSession(sid, user.ID, csrf, 3600e9, "127.0.0.1", "test")
+ r.AddCookie(&http.Cookie{Name: SessionCookieName, Value: sid})
+ }
+ w := httptest.NewRecorder()
+ srv.Handler().ServeHTTP(w, r)
+ return w
+ }
+ if w := del(bob, bobCsrf); w.Code != http.StatusForbidden {
+ t.Errorf("无关成员删除议题应 403,实际 %d", w.Code)
+ }
+ if w := del(alice, "alice-sess-csrf"); w.Code != http.StatusFound {
+ t.Errorf("管理员删除议题应成功,实际 %d", w.Code)
+ }
+ if _, err := st.IssueByNumber(mustRepoID(t, st, "manage"), 1); err == nil {
+ t.Error("议题删除后不应能再查到")
+ }
+}
+
+// TestIssueValidation 标题 / 内容长度校验。
+func TestIssueValidation(t *testing.T) {
+ srv, st, alice, _ := newTestServer(t)
+ dir := makeRepo(t, srv, st, "valid", alice)
+ commitFiles(t, dir, "first", map[string]string{"a.go": "package a\n"})
+ const csrf = "valid-csrf"
+ _ = st.CreateSession("valid-sess", alice.ID, csrf, 3600e9, "127.0.0.1", "test")
+ cookie := &http.Cookie{Name: SessionCookieName, Value: "valid-sess"}
+
+ long := strings.Repeat("标", maxIssueTitleRunes+1)
+ if w := postIssue(srv, "valid", url.Values{"title": {long}}, cookie, csrf); w.Code != http.StatusBadRequest {
+ t.Errorf("超长标题应 400,实际 %d", w.Code)
+ }
+ empty := url.Values{"title": {" "}}
+ if w := postIssue(srv, "valid", empty, cookie, csrf); w.Code != http.StatusBadRequest {
+ t.Errorf("空标题应 400,实际 %d", w.Code)
+ }
+ longBody := strings.Repeat("内容", maxIssueContentRunes/2+10)
+ if w := postIssue(srv, "valid", url.Values{"title": {"ok"}, "content": {longBody}}, cookie, csrf); w.Code != http.StatusBadRequest {
+ t.Errorf("超长内容应 400,实际 %d", w.Code)
+ }
+}
+
+// ---------------------------------------------------------------- 小工具
+
+func cloneForm(src url.Values) url.Values {
+ dst := url.Values{}
+ for k, vs := range src {
+ dst[k] = append([]string(nil), vs...)
+ }
+ return dst
+}
+
+func mustRepoID(t *testing.T, st interface {
+ RepoByName(string) (*store.Repo, error)
+}, name string) int64 {
+ t.Helper()
+ r, err := st.RepoByName(name)
+ if err != nil {
+ t.Fatalf("读取仓库 %s 失败: %v", name, err)
+ }
+ return r.ID
+}
+
+// flashOf 从重定向响应里取出 flash Cookie 的值(urlencoded)。
+func flashOf(w *httptest.ResponseRecorder) string {
+ for _, c := range w.Result().Cookies() {
+ if c.Name == "gitcat_flash" {
+ v, err := url.QueryUnescape(c.Value)
+ if err != nil {
+ return c.Value
+ }
+ return v
+ }
+ }
+ return ""
+}
\ No newline at end of file
diff --git a/internal/server/repo.go b/internal/server/repo.go
index 7f62676..ef415e5 100644
--- a/internal/server/repo.go
+++ b/internal/server/repo.go
@@ -145,6 +145,8 @@ func (s *Server) repoCommon(r *http.Request, repo *store.Repo, dir string, ref s
// 发行版数量:仓库 Tab 角标。读取失败按 0 展示,不阻断页面。
data["ReleaseCount"] = s.st.ReleaseCount(repo.ID)
+ // 开放议题数量:仓库 Tab 角标。
+ data["IssueCount"] = s.st.IssueCount(repo.ID)
// 最新发行版:主页侧栏卡片。取不到(无发行版)时模板按空渲染。
if rels, err := s.st.ReleasesByRepo(repo.ID, 1); err == nil && len(rels) > 0 {
data["LatestRelease"] = rels[0]
diff --git a/internal/server/server.go b/internal/server/server.go
index f48c5f0..6c27871 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -28,6 +28,7 @@ import (
"github.com/yuin/goldmark/renderer/html"
"gitcat/internal/ai"
+ "gitcat/internal/captcha"
"gitcat/internal/gitx"
"gitcat/internal/store"
"gitcat/webroot"
@@ -61,6 +62,7 @@ type Server struct {
md goldmark.Markdown
upgrading atomic.Bool // 防止并发的升级 / 重启请求叠加
guests *guestLimiter
+ captchas *captcha.Store
}
// New 构造服务器。
@@ -84,6 +86,7 @@ func New(cfg Config, st *store.Store) (*Server, error) {
goldmark.WithRendererOptions(html.WithHardWraps()),
),
guests: newGuestLimiter(),
+ captchas: captcha.NewStore(captchaTTL),
}
if err := s.buildTemplates(); err != nil {
return nil, err
@@ -185,6 +188,7 @@ func (s *Server) buildTemplates() error {
"error", "install", "login", "home", "new_project",
"repo_home", "repo_commits", "repo_commit", "repo_blob", "repo_branches", "repo_activity", "repo_settings",
"repo_releases", "repo_release", "repo_release_new",
+ "issues", "issue_new", "issue",
"profile",
"admin_dashboard", "admin_users", "admin_user", "admin_repos", "admin_repo", "admin_ai", "admin_settings", "admin_activity", "admin_upgrade",
}
@@ -277,6 +281,14 @@ func (s *Server) routes() {
m.HandleFunc("GET /{repo}/commit/{sha}", s.handleRepoCommit)
m.HandleFunc("GET /{repo}/branches", s.handleRepoBranches)
m.HandleFunc("GET /{repo}/activity", s.handleRepoActivity)
+ // 议题:游客可看可提(需图片验证码),管理权操作走 CSRF
+ m.HandleFunc("GET /{repo}/issues", s.handleIssuesList)
+ m.HandleFunc("GET /{repo}/issues/new", s.handleIssueNewPage)
+ m.HandleFunc("POST /{repo}/issues/new", s.handleIssueCreate)
+ m.HandleFunc("GET /{repo}/issues/captcha.png", s.handleIssueCaptcha)
+ m.HandleFunc("GET /{repo}/issues/{number}", s.handleIssueDetail)
+ m.HandleFunc("POST /{repo}/issues/{number}/status", s.handleIssueStatus)
+ m.HandleFunc("POST /{repo}/issues/{number}/delete", s.handleIssueDelete)
// AI 项目助手:前端以 fetch 提交 JSON,故单独走一个 JSON 接口。
m.HandleFunc("POST /{repo}/assistant", s.handleAssistantChat)
m.HandleFunc("GET /{repo}/settings", s.handleRepoSettingsPage)
@@ -343,6 +355,14 @@ func (s *Server) Handler() http.Handler {
h = s.withInstallCheck(h)
h = s.withSecurityHeaders(h)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // 尾斜杠规范化(就地剥离,不重定向):nginx 等反代会把无斜杠路径
+ // 当磁盘目录 301 成带斜杠,而 mux 的叶子模式(/{repo} 等)不匹配
+ // 尾斜杠路径。在这里统一剥掉,无论反代怎么跳都能正常落地,也避免
+ // 与反代的加斜杠重定向打成循环。
+ if p := r.URL.Path; len(p) > 1 && strings.HasSuffix(p, "/") {
+ r.URL.Path = strings.TrimRight(p, "/")
+ r.URL.RawPath = ""
+ }
// 静态资源:/static/...
if strings.HasPrefix(r.URL.Path, "/static/") {
s.withSecurityHeaders(s.static).ServeHTTP(w, r)
diff --git a/internal/server/slash_test.go b/internal/server/slash_test.go
new file mode 100644
index 0000000..ab25ca0
--- /dev/null
+++ b/internal/server/slash_test.go
@@ -0,0 +1,38 @@
+package server
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+// TestTrailingSlashTolerated 反代(nginx)会把无斜杠路径当磁盘目录 301 成
+// 带斜杠,gitcat 必须对尾斜杠宽容:就地剥离后正常渲染,而不是返回 Go mux
+// 的默认 404。这是仓库主页"点进去 404"的回归测试。
+func TestTrailingSlashTolerated(t *testing.T) {
+ srv, st, alice, _ := newTestServer(t)
+ dir := makeRepo(t, srv, st, "slash", alice)
+ commitFiles(t, dir, "first", map[string]string{"README.md": "# demo\n"})
+
+ cases := []struct {
+ path, want string
+ }{
+ {"/slash/", "README.md"}, // 仓库主页
+ {"/slash/issues/", "还没有议题"}, // 议题列表
+ {"/slash/commits/main/", "first"}, // 提交历史
+ {"/slash/blob/main/README.md/", "# demo"}, // 文件页
+ }
+ for _, c := range cases {
+ r := httptest.NewRequest(http.MethodGet, c.path, nil)
+ w := httptest.NewRecorder()
+ srv.Handler().ServeHTTP(w, r)
+ if w.Code != http.StatusOK {
+ t.Errorf("GET %s 返回 %d,期望 200", c.path, w.Code)
+ continue
+ }
+ if !strings.Contains(w.Body.String(), c.want) {
+ t.Errorf("GET %s 页面缺少 %q", c.path, c.want)
+ }
+ }
+}
\ No newline at end of file
diff --git a/internal/store/issues.go b/internal/store/issues.go
new file mode 100644
index 0000000..20ae2ae
--- /dev/null
+++ b/internal/store/issues.go
@@ -0,0 +1,207 @@
+// 议题(Issues):项目的问题反馈与任务追踪。
+//
+// 编号按仓库独立递增(#1、#2……),与全局自增 id 互不影响。作者以快照
+// 形式留存(与推送 / 发行版一致),删号后仍可展示。游客也可以提交议题,
+// 此时 user_id 为空、author_username 固定为 guest。
+package store
+
+import (
+ "database/sql"
+ "errors"
+ "strings"
+ "time"
+)
+
+// 议题状态。
+const (
+ IssueOpen = "open"
+ IssueClosed = "closed"
+)
+
+// issuesSchema 是议题功能引入的表与索引,随 migration v3 执行。
+var issuesSchema = []string{
+ `CREATE TABLE IF NOT EXISTS issues (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
+ number INTEGER NOT NULL,
+ user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
+ author_username TEXT NOT NULL DEFAULT '',
+ author_display TEXT NOT NULL DEFAULT '',
+ title TEXT NOT NULL,
+ content TEXT NOT NULL DEFAULT '',
+ status TEXT NOT NULL DEFAULT 'open',
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ closed_at TEXT NOT NULL DEFAULT '',
+ UNIQUE(repo_id, number)
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_issues_repo ON issues(repo_id, status, id DESC)`,
+}
+
+// Issue 表示一个议题。
+type Issue struct {
+ ID int64
+ RepoID int64
+ RepoName string
+ Number int64
+ UserID *int64
+ AuthorUsername string
+ AuthorDisplay string
+ Title string
+ Content string
+ Status string
+ CreatedAt time.Time
+ UpdatedAt time.Time
+ ClosedAt time.Time
+}
+
+// IsGuest 判断议题是否由游客提交。
+func (i *Issue) IsGuest() bool { return i.UserID == nil }
+
+// StatusText 返回状态的中文展示。
+func (i *Issue) StatusText() string {
+ if i.Status == IssueClosed {
+ return "已关闭"
+ }
+ return "开放中"
+}
+
+const issueCols = `i.id, i.repo_id, COALESCE(r.name, ''), i.number, i.user_id,
+ i.author_username, i.author_display, i.title, i.content, i.status,
+ i.created_at, i.updated_at, i.closed_at`
+
+func scanIssue(scan func(dest ...any) error) (*Issue, error) {
+ var it Issue
+ var userID sql.NullInt64
+ var created, updated, closed string
+ if err := scan(&it.ID, &it.RepoID, &it.RepoName, &it.Number, &it.UserID,
+ &it.AuthorUsername, &it.AuthorDisplay, &it.Title, &it.Content, &it.Status,
+ &created, &updated, &closed); err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, ErrNotFound
+ }
+ return nil, err
+ }
+ if userID.Valid {
+ id := userID.Int64
+ it.UserID = &id
+ }
+ it.CreatedAt = parseTime(created)
+ it.UpdatedAt = parseTime(updated)
+ it.ClosedAt = parseTime(closed)
+ return &it, nil
+}
+
+// CreateIssue 新建议题,编号取该仓库当前最大编号 + 1。
+// Store 是单连接串行写入,子查询取号不会竞争。
+func (s *Store) CreateIssue(repoID int64, userID *int64, authorUsername, authorDisplay, title, content string) (*Issue, error) {
+ ts := nowString()
+ res, err := s.db.Exec(`INSERT INTO issues(repo_id, number, user_id, author_username, author_display, title, content, status, created_at, updated_at)
+ VALUES(?, (SELECT COALESCE(MAX(number), 0) + 1 FROM issues WHERE repo_id = ?), ?, ?, ?, ?, ?, ?, ?, ?)`,
+ repoID, repoID, userID, authorUsername, authorDisplay, title, content, IssueOpen, ts, ts)
+ if err != nil {
+ return nil, err
+ }
+ id, _ := res.LastInsertId()
+ return s.IssueByID(id)
+}
+
+// IssueByID 按主键查询议题。
+func (s *Store) IssueByID(id int64) (*Issue, error) {
+ return scanIssue(s.db.QueryRow(`SELECT `+issueCols+` FROM issues i
+ LEFT JOIN repos r ON r.id = i.repo_id WHERE i.id = ?`, id).Scan)
+}
+
+// IssueByNumber 按仓库内编号查询议题。
+func (s *Store) IssueByNumber(repoID int64, number int64) (*Issue, error) {
+ return scanIssue(s.db.QueryRow(`SELECT `+issueCols+` FROM issues i
+ LEFT JOIN repos r ON r.id = i.repo_id WHERE i.repo_id = ? AND i.number = ?`, repoID, number).Scan)
+}
+
+// IssuesByRepo 返回议题列表。status 为空表示全部;新的在前。
+func (s *Store) IssuesByRepo(repoID int64, status string, limit, offset int) ([]*Issue, error) {
+ query := `SELECT ` + issueCols + ` FROM issues i
+ LEFT JOIN repos r ON r.id = i.repo_id WHERE i.repo_id = ?`
+ args := []any{repoID}
+ if status == IssueOpen || status == IssueClosed {
+ query += ` AND i.status = ?`
+ args = append(args, status)
+ }
+ query += ` ORDER BY i.id DESC LIMIT ? OFFSET ?`
+ args = append(args, limit, offset)
+ rows, err := s.db.Query(query, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []*Issue
+ for rows.Next() {
+ it, err := scanIssue(rows.Scan)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, it)
+ }
+ return out, rows.Err()
+}
+
+// IssueCounts 返回仓库的开放 / 已关闭议题数量。
+func (s *Store) IssueCounts(repoID int64) (open, closed int) {
+ var o, c sql.NullInt64
+ if err := s.db.QueryRow(`SELECT
+ SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END),
+ SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END)
+ FROM issues WHERE repo_id = ?`, repoID).Scan(&o, &c); err != nil {
+ return 0, 0
+ }
+ if o.Valid {
+ open = int(o.Int64)
+ }
+ if c.Valid {
+ closed = int(c.Int64)
+ }
+ return open, closed
+}
+
+// IssueCount 返回仓库的开放议题数量(Tab 角标用)。
+func (s *Store) IssueCount(repoID int64) int {
+ open, _ := s.IssueCounts(repoID)
+ return open
+}
+
+// SetIssueStatus 关闭 / 重新打开议题。
+func (s *Store) SetIssueStatus(repoID, number int64, status string) error {
+ if status != IssueOpen && status != IssueClosed {
+ return errors.New("未知的议题状态")
+ }
+ closedAt := ""
+ if status == IssueClosed {
+ closedAt = nowString()
+ }
+ _, err := s.db.Exec(`UPDATE issues SET status = ?, closed_at = ?, updated_at = ?
+ WHERE repo_id = ? AND number = ?`, status, closedAt, nowString(), repoID, number)
+ return err
+}
+
+// DeleteIssue 删除议题记录。
+func (s *Store) DeleteIssue(id int64) error {
+ _, err := s.db.Exec(`DELETE FROM issues WHERE id = ?`, id)
+ return err
+}
+
+// SanitizeNickname 清理游客昵称:去空白与控制字符、限长。
+func SanitizeNickname(name string, max int) string {
+ var b strings.Builder
+ for _, r := range strings.TrimSpace(name) {
+ if r < 0x20 || r == 0x7f {
+ continue
+ }
+ b.WriteRune(r)
+ }
+ out := strings.TrimSpace(b.String())
+ r := []rune(out)
+ if len(r) > max {
+ out = string(r[:max])
+ }
+ return out
+}
\ No newline at end of file
diff --git a/internal/store/issues_test.go b/internal/store/issues_test.go
new file mode 100644
index 0000000..5940709
--- /dev/null
+++ b/internal/store/issues_test.go
@@ -0,0 +1,184 @@
+package store
+
+import (
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// testOpenStore 打开一个临时数据库。
+func testOpenStore(t *testing.T) *Store {
+ t.Helper()
+ st, err := Open(filepath.Join(t.TempDir(), "gitcat.db"))
+ if err != nil {
+ t.Fatalf("打开测试库失败: %v", err)
+ }
+ t.Cleanup(func() { st.Close() })
+ return st
+}
+
+// testCreateRepoRow 建一个带 owner 的仓库记录(不建磁盘目录)。
+func testCreateRepoRow(t *testing.T, s *Store, name string) *Repo {
+ t.Helper()
+ owner, err := s.CreateUser("owner-"+name, "Owner", "", "x", false)
+ if err != nil {
+ if !strings.Contains(err.Error(), "已存在") {
+ t.Fatalf("建用户失败: %v", err)
+ }
+ owner, err = s.UserByUsername("owner-" + name)
+ if err != nil {
+ t.Fatalf("读取用户失败: %v", err)
+ }
+ }
+ r, err := s.CreateRepo(name, "", owner.ID)
+ if err != nil {
+ t.Fatalf("建仓库失败: %v", err)
+ }
+ return r
+}
+
+func TestIssueNumberSequencePerRepo(t *testing.T) {
+ s := testOpenStore(t)
+ r1 := testCreateRepoRow(t, s, "alpha")
+ r2 := testCreateRepoRow(t, s, "beta")
+
+ i1, err := s.CreateIssue(r1.ID, nil, "guest", "访客", "第一个问题", "")
+ if err != nil {
+ t.Fatalf("CreateIssue 失败: %v", err)
+ }
+ if i1.Number != 1 {
+ t.Errorf("alpha 第一条编号 = %d,期望 1", i1.Number)
+ }
+ i2, err := s.CreateIssue(r1.ID, nil, "guest", "访客", "第二个问题", "")
+ if err != nil {
+ t.Fatalf("CreateIssue 失败: %v", err)
+ }
+ if i2.Number != 2 {
+ t.Errorf("alpha 第二条编号 = %d,期望 2", i2.Number)
+ }
+ // 另一个仓库独立编号
+ i3, err := s.CreateIssue(r2.ID, nil, "guest", "访客", "beta 的问题", "")
+ if err != nil {
+ t.Fatalf("CreateIssue 失败: %v", err)
+ }
+ if i3.Number != 1 {
+ t.Errorf("beta 编号应独立递增,实际 %d", i3.Number)
+ }
+
+ // 删除也不影响后续编号(编号不可复用)
+ byNum, err := s.IssueByNumber(r1.ID, 1)
+ if err != nil {
+ t.Fatalf("IssueByNumber 失败: %v", err)
+ }
+ if err := s.DeleteIssue(byNum.ID); err != nil {
+ t.Fatalf("DeleteIssue 失败: %v", err)
+ }
+ i4, err := s.CreateIssue(r1.ID, nil, "guest", "访客", "第四个问题", "")
+ if err != nil {
+ t.Fatalf("CreateIssue 失败: %v", err)
+ }
+ if i4.Number != 3 {
+ t.Errorf("删除后新编号 = %d,期望 3(不复用)", i4.Number)
+ }
+ if _, err := s.IssueByNumber(r1.ID, 1); err == nil {
+ t.Error("已删除议题不应能再查到")
+ }
+}
+
+func TestIssueStatusAndCounts(t *testing.T) {
+ s := testOpenStore(t)
+ r := testCreateRepoRow(t, s, "status")
+ for _, title := range []string{"a", "b", "c"} {
+ if _, err := s.CreateIssue(r.ID, nil, "guest", "访客", title, ""); err != nil {
+ t.Fatalf("CreateIssue 失败: %v", err)
+ }
+ }
+
+ open, closed := s.IssueCounts(r.ID)
+ if open != 3 || closed != 0 {
+ t.Fatalf("初始计数 open=%d closed=%d,期望 3/0", open, closed)
+ }
+
+ if err := s.SetIssueStatus(r.ID, 2, IssueClosed); err != nil {
+ t.Fatalf("SetIssueStatus 失败: %v", err)
+ }
+ it, err := s.IssueByNumber(r.ID, 2)
+ if err != nil {
+ t.Fatalf("IssueByNumber 失败: %v", err)
+ }
+ if it.Status != IssueClosed || it.ClosedAt.IsZero() {
+ t.Errorf("关闭后 status=%q closed_at=%v", it.Status, it.ClosedAt)
+ }
+ open, closed = s.IssueCounts(r.ID)
+ if open != 2 || closed != 1 {
+ t.Errorf("关闭后计数 open=%d closed=%d,期望 2/1", open, closed)
+ }
+
+ if err := s.SetIssueStatus(r.ID, 2, IssueOpen); err != nil {
+ t.Fatalf("重新打开失败: %v", err)
+ }
+ it, _ = s.IssueByNumber(r.ID, 2)
+ if it.Status != IssueOpen || !it.ClosedAt.IsZero() {
+ t.Errorf("重开后 status=%q closed_at=%v,应清空关闭时间", it.Status, it.ClosedAt)
+ }
+
+ // 非法状态拒绝
+ if err := s.SetIssueStatus(r.ID, 2, "weird"); err == nil {
+ t.Error("未知状态应被拒绝")
+ }
+
+ // 再次关闭 #2,检查列表按状态过滤(此时 open=2 / closed=1)
+ if err := s.SetIssueStatus(r.ID, 2, IssueClosed); err != nil {
+ t.Fatalf("关闭失败: %v", err)
+ }
+ openList, err := s.IssuesByRepo(r.ID, IssueOpen, 10, 0)
+ if err != nil {
+ t.Fatalf("IssuesByRepo 失败: %v", err)
+ }
+ if len(openList) != 2 {
+ t.Errorf("开放列表应有 2 条,实际 %d", len(openList))
+ }
+ all, err := s.IssuesByRepo(r.ID, "", 10, 0)
+ if err != nil {
+ t.Fatalf("IssuesByRepo 失败: %v", err)
+ }
+ if len(all) != 3 || all[0].Number != 3 {
+ t.Errorf("全部列表应有 3 条且新的在前,实际 %d 条首条编号 %d", len(all), all[0].Number)
+ }
+}
+
+func TestIssueRepoCascadeAndBadge(t *testing.T) {
+ s := testOpenStore(t)
+ r := testCreateRepoRow(t, s, "cascade")
+ if _, err := s.CreateIssue(r.ID, nil, "guest", "访客", "问题", ""); err != nil {
+ t.Fatalf("CreateIssue 失败: %v", err)
+ }
+ if n := s.IssueCount(r.ID); n != 1 {
+ t.Fatalf("角标应为 1,实际 %d", n)
+ }
+ if err := s.DeleteRepo(r.ID); err != nil {
+ t.Fatalf("DeleteRepo 失败: %v", err)
+ }
+ open, closed := s.IssueCounts(r.ID)
+ if open != 0 || closed != 0 {
+ t.Errorf("仓库删除后议题应级联清空,实际 open=%d closed=%d", open, closed)
+ }
+}
+
+func TestSanitizeNickname(t *testing.T) {
+ cases := []struct{ in, want string }{
+ {" 小明 ", "小明"},
+ {"line1\nline2", "line1line2"},
+ {"\x00\x07控制字符", "控制字符"},
+ {"", ""},
+ }
+ for _, c := range cases {
+ if got := SanitizeNickname(c.in, 30); got != c.want {
+ t.Errorf("SanitizeNickname(%q) = %q,期望 %q", c.in, got, c.want)
+ }
+ }
+ long := strings.Repeat("好", 40)
+ if got := SanitizeNickname(long, 30); len([]rune(got)) != 30 {
+ t.Errorf("超长昵称应截断到 30,实际 %d", len([]rune(got)))
+ }
+}
\ No newline at end of file
diff --git a/internal/store/store.go b/internal/store/store.go
index 07c0066..b2580f2 100644
--- a/internal/store/store.go
+++ b/internal/store/store.go
@@ -131,7 +131,7 @@ var schema = []string{
// 版本 1 = 最原始的 5 张表(无 schema_meta),用于识别旧版数据库。
// SchemaVersion 是当前二进制支持的最新数据库版本。
-const SchemaVersion = 2
+const SchemaVersion = 3
// execer 让迁移既能跑在事务里(*sql.Tx)也能直接跑在连接上(*sql.DB)。
type execer interface {
@@ -161,6 +161,18 @@ var migrations = []migration{
return nil
},
},
+ {
+ version: 3,
+ name: "议题表",
+ run: func(e execer) error {
+ for _, stmt := range issuesSchema {
+ if _, err := e.Exec(stmt); err != nil {
+ return err
+ }
+ }
+ return nil
+ },
+ },
}
const schemaMetaTable = `CREATE TABLE IF NOT EXISTS schema_meta (
diff --git a/webroot/static/style.css b/webroot/static/style.css
index 51dee47..3511757 100644
--- a/webroot/static/style.css
+++ b/webroot/static/style.css
@@ -644,6 +644,45 @@ legend { font-weight: 700; font-size: .95rem; margin-bottom: 12px; display: flex
.profile-stats { display: flex; gap: 16px; align-items: center; font-size: .88rem; color: var(--ink-2); flex-wrap: wrap; }
.avatar-form { border-top: 1px solid var(--line-2); padding-top: 16px; }
+/* ---------------------------------------------------------- 议题 Issues */
+/* 议题 Tab 上的角标读的是开放数量;列表过滤、状态标签与验证码输入都在这里 */
+
+.issue-filter {
+ display: flex; gap: 14px; padding-bottom: 12px; margin-bottom: 6px;
+ border-bottom: 1px solid var(--line-2); font-size: .92rem;
+}
+.issue-filter a { color: var(--ink-3); text-decoration: none; padding: 3px 8px; border-radius: 8px; }
+.issue-filter a strong { color: var(--ink); }
+.issue-filter a:hover { background: var(--mint-50); color: var(--ink); }
+.issue-filter a.on { color: var(--green-700); background: var(--mint-100); font-weight: 700; }
+.issue-filter a.on strong { color: var(--green-700); }
+
+.issue-list { list-style: none; margin: 0; padding: 0; }
+.issue-list li {
+ display: flex; align-items: flex-start; gap: 11px;
+ padding: 13px 4px; border-bottom: 1px solid var(--line-2);
+}
+.issue-list li:last-child { border-bottom: none; }
+.issue-ico { flex: none; margin-top: 2px; color: var(--green-600); }
+.issue-ico.closed { color: var(--ink-3); }
+.issue-main { flex: 1; min-width: 0; }
+.issue-title { font-weight: 700; color: var(--ink); text-decoration: none; overflow-wrap: anywhere; }
+a.issue-title:hover { color: var(--green-700); }
+.issue-num { color: var(--ink-3); font-weight: 600; margin-left: 5px; font-size: .88rem; }
+.issue-meta { font-size: .82rem; margin-top: 3px; }
+.tag-open { background: var(--mint-100); color: var(--green-700); }
+.tag-closed { background: #eef2f5; color: var(--ink-3); }
+.issue-body { border-top: 1px solid var(--line-2); padding-top: 14px; }
+.issue-foot { border-top: 1px solid var(--line-2); padding-top: 10px; font-size: .82rem; }
+.issue-actions { margin-top: 14px; }
+
+.captcha-row { display: flex; align-items: center; gap: 10px; }
+.captcha-img {
+ border-radius: 8px; border: 1px solid var(--line); cursor: pointer;
+ display: block; flex: none;
+}
+.captcha-row input { flex: 1; min-width: 120px; max-width: 220px; }
+
/* ---------------------------------------------------------- 错误页 */
.empty-hero { text-align: center; padding: 60px 20px; }
@@ -880,6 +919,16 @@ a.release-name:hover { color: var(--green-700); }
}
.ai-suggests { display: flex; flex-direction: column; gap: 6px; margin-top: 10px; }
+
+/* 流式回答:原始文本渐进渲染,结束后替换为 Markdown */
+.ai-status { display: none; font-size: .82rem; color: var(--ink-3); margin-bottom: .4em; }
+.ai-raw { white-space: pre-wrap; overflow-wrap: anywhere; font-size: .9rem; line-height: 1.65; }
+.ai-raw.streaming::after {
+ content: "▍"; color: var(--green-600); margin-left: 1px;
+ animation: ai-cursor 1s steps(2) infinite;
+}
+@keyframes ai-cursor { 0%, 100% { opacity: 1; } 50% { opacity: 0; } }
+.ai-raw.streaming:empty::after { content: ""; }
.ai-suggests button {
font: inherit; font-size: .84rem; text-align: left; cursor: pointer;
padding: 7px 10px; border-radius: 10px; border: 1px dashed var(--mint-300);
diff --git a/webroot/templates/issue.html b/webroot/templates/issue.html
new file mode 100644
index 0000000..df3a5d6
--- /dev/null
+++ b/webroot/templates/issue.html
@@ -0,0 +1,50 @@
+{{define "content"}}
+{{$repo := .Data.Repo}}
+{{$issue := .Data.Issue}}
+<header class="repo-head compact">
+ <div class="repo-title">
+ <span class="repo-icon lg" aria-hidden="true">
+ <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="8.5"/><circle cx="12" cy="12" r="3.6"/><path d="M12 3.5v4.9M12 15.6v4.9M3.5 12h4.9M15.6 12h4.9"/></svg>
+ </span>
+ <div>
+ <h1>{{$issue.Title}} <span class="muted">#{{$issue.Number}}</span></h1>
+ <p class="repo-sub">
+ {{if eq $issue.Status "closed"}}<span class="tag tag-closed">已关闭</span>{{else}}<span class="tag tag-open">开放中</span>{{end}}
+ <a class="quiet" href="/{{$repo.Name}}/issues">{{$repo.Name}} / 议题</a>
+ · {{$issue.AuthorDisplay}}{{if $issue.IsGuest}}(游客){{end}} · 于 <span title="{{datetime $issue.CreatedAt}}">{{datetime $issue.CreatedAt}}</span> 提交
+ </p>
+ </div>
+ </div>
+</header>
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "issues" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount "IssueCount" .Data.IssueCount)}}
+
+<div class="col-main" style="max-width: 860px;">
+ <div class="card">
+ {{if $issue.Content}}
+ <div class="md-body issue-body">{{md $issue.Content}}</div>
+ {{else}}
+ <p class="muted">提交者没有附上详细描述。</p>
+ {{end}}
+ <div class="issue-foot muted">
+ {{if $issue.ClosedAt}}<span>关闭于 {{datetime $issue.ClosedAt}}</span> · {{end}}<span>更新于 {{timeago $issue.UpdatedAt}}</span>
+ </div>
+
+ {{if .Data.CanManage}}
+ <div class="row-actions issue-actions">
+ <form method="post" action="/{{$repo.Name}}/issues/{{$issue.Number}}/status">
+ <input type="hidden" name="csrf" value="{{.CSRF}}">
+ {{if eq $issue.Status "open"}}
+ <button class="btn btn-ghost" type="submit">关闭议题</button>
+ {{else}}
+ <button class="btn btn-ghost" type="submit">重新打开</button>
+ {{end}}
+ </form>
+ <form method="post" action="/{{$repo.Name}}/issues/{{$issue.Number}}/delete" data-confirm="确定删除议题 #{{$issue.Number}} 吗?该操作不可恢复。">
+ <input type="hidden" name="csrf" value="{{.CSRF}}">
+ <button class="btn btn-danger" type="submit">删除</button>
+ </form>
+ </div>
+ {{end}}
+ </div>
+</div>
+{{end}}
\ No newline at end of file
diff --git a/webroot/templates/issue_new.html b/webroot/templates/issue_new.html
new file mode 100644
index 0000000..68bd0bf
--- /dev/null
+++ b/webroot/templates/issue_new.html
@@ -0,0 +1,62 @@
+{{define "content"}}
+{{$repo := .Data.Repo}}
+<header class="repo-head compact">
+ <div class="repo-title">
+ <span class="repo-icon lg" aria-hidden="true">
+ <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="8.5"/><circle cx="12" cy="12" r="3.6"/><path d="M12 3.5v4.9M12 15.6v4.9M3.5 12h4.9M15.6 12h4.9"/></svg>
+ </span>
+ <div><h1>提交议题</h1></div>
+ </div>
+</header>
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "issues" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount "IssueCount" .Data.IssueCount)}}
+
+<div class="col-main" style="max-width: 780px;">
+ <div class="card">
+ {{if .Error}}<div class="flash err" role="alert"><span class="flash-ico">!</span><span>{{.Error}}</span><button class="flash-x" type="button" aria-label="关闭">×</button></div>{{end}}
+ <form method="post" action="/{{$repo.Name}}/issues/new" autocomplete="off">
+ {{if .User}}<input type="hidden" name="csrf" value="{{.CSRF}}">{{end}}
+ <label class="field">
+ <span>标题 <em class="muted">必填,最多 120 字</em></span>
+ <input type="text" name="title" value="{{.Data.Title}}" maxlength="120" placeholder="一句话概括问题或建议" required>
+ </label>
+ <label class="field">
+ <span>详细描述 <em class="muted">选填,支持 Markdown,最多 5000 字</em></span>
+ <textarea name="content" rows="8" maxlength="5000" placeholder="复现步骤、期望行为、实际行为、相关版本信息……">{{.Data.Content}}</textarea>
+ </label>
+
+ {{if not .User}}
+ <label class="field">
+ <span>称呼 <em class="muted">选填,最多 30 字</em></span>
+ <input type="text" name="nickname" maxlength="30" placeholder="访客">
+ </label>
+ <div class="field">
+ <span>验证码 <em class="muted">图片中的 5 位数字</em></span>
+ <div class="captcha-row">
+ <img class="captcha-img" id="captcha-img" src="/{{$repo.Name}}/issues/captcha.png" alt="验证码图片" width="150" height="52">
+ <button type="button" class="btn btn-ghost btn-mini" id="captcha-refresh" title="看不清?换一张">换一张</button>
+ <input type="text" name="captcha" maxlength="8" inputmode="numeric" pattern="[0-9 ]*" placeholder="输入 5 位数字" required>
+ </div>
+ <em class="field-hint">未登录用户提交前需完成验证;<a href="/login">登录</a>后免验证码。</em>
+ </div>
+ {{end}}
+
+ <div class="row-actions">
+ <button class="btn btn-primary" type="submit">提交议题</button>
+ <a class="btn btn-ghost" href="/{{$repo.Name}}/issues">取消</a>
+ </div>
+ </form>
+ </div>
+</div>
+<script>
+(function () {
+ var img = document.getElementById('captcha-img');
+ var btn = document.getElementById('captcha-refresh');
+ if (!img || !btn) return;
+ function refresh() {
+ img.src = '/{{$repo.Name}}/issues/captcha.png?t=' + Date.now();
+ }
+ btn.addEventListener('click', refresh);
+ img.addEventListener('click', refresh);
+})();
+</script>
+{{end}}
\ No newline at end of file
diff --git a/webroot/templates/issues.html b/webroot/templates/issues.html
new file mode 100644
index 0000000..b3789aa
--- /dev/null
+++ b/webroot/templates/issues.html
@@ -0,0 +1,61 @@
+{{define "content"}}
+{{$repo := .Data.Repo}}
+<header class="repo-head compact">
+ <div class="repo-title">
+ <span class="repo-icon lg" aria-hidden="true">
+ <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="8.5"/><circle cx="12" cy="12" r="3.6"/><path d="M12 3.5v4.9M12 15.6v4.9M3.5 12h4.9M15.6 12h4.9"/></svg>
+ </span>
+ <div><h1>议题</h1></div>
+ </div>
+ <div class="repo-actions">
+ <a class="btn btn-primary" href="/{{$repo.Name}}/issues/new">提交议题</a>
+ </div>
+</header>
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "issues" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount "IssueCount" .Data.IssueCount)}}
+
+<div class="col-main" style="max-width: none;">
+ <div class="card">
+ <div class="issue-filter">
+ <a class="{{if eq .Data.Status ""}}on{{end}}" href="/{{$repo.Name}}/issues"><strong>{{num .Data.OpenCount}}</strong> 开放中</a>
+ <a class="{{if eq .Data.Status "closed"}}on{{end}}" href="/{{$repo.Name}}/issues?status=closed"><strong>{{num .Data.ClosedCount}}</strong> 已关闭</a>
+ </div>
+
+ {{if .Data.Issues}}
+ <ul class="issue-list">
+ {{range .Data.Issues}}
+ <li>
+ <span class="issue-ico {{if eq .Status "closed"}}closed{{end}}" aria-hidden="true">
+ {{if eq .Status "closed"}}
+ <svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="m8.5 12.5 2.5 2.5 4.5-5.5"/></svg>
+ {{else}}
+ <svg viewBox="0 0 24 24" width="17" height="17" fill="currentColor" stroke="none"><circle cx="12" cy="12" r="6.5"/></svg>
+ {{end}}
+ </span>
+ <div class="issue-main">
+ <a class="issue-title" href="/{{$repo.Name}}/issues/{{.Number}}">{{.Title}}</a>
+ <span class="issue-num">#{{.Number}}</span>
+ <div class="issue-meta muted">
+ {{.AuthorDisplay}}{{if .IsGuest}}(游客){{end}} · {{if eq .Status "closed"}}于 {{timeago .ClosedAt}} 关闭 · {{end}}{{timeago .CreatedAt}}
+ </div>
+ </div>
+ {{if eq .Status "open"}}<span class="tag tag-open">开放中</span>{{else}}<span class="tag tag-closed">已关闭</span>{{end}}
+ </li>
+ {{end}}
+ </ul>
+ {{if or .Data.HasPrev .Data.HasNext}}
+ <div class="pager">
+ {{if .Data.HasPrev}}<a class="btn btn-ghost btn-mini" href="/{{$repo.Name}}/issues?{{if .Data.Status}}status={{.Data.Status}}&{{end}}page={{add .Data.Page -1}}">上一页</a>{{end}}
+ <span class="muted">第 {{.Data.Page}} 页</span>
+ {{if .Data.HasNext}}<a class="btn btn-ghost btn-mini" href="/{{$repo.Name}}/issues?{{if .Data.Status}}status={{.Data.Status}}&{{end}}page={{add .Data.Page 1}}">下一页</a>{{end}}
+ </div>
+ {{end}}
+ {{else}}
+ <div class="empty-hero" style="padding: 40px 10px;">
+ <h1 style="font-size:1.3rem;">还没有议题</h1>
+ <p class="muted">发现问题或有改进建议?提交一个议题,让作者知道。</p>
+ <a class="btn btn-primary" href="/{{$repo.Name}}/issues/new" style="margin-top:12px;">提交第一个议题</a>
+ </div>
+ {{end}}
+ </div>
+</div>
+{{end}}
\ No newline at end of file
diff --git a/webroot/templates/layout.html b/webroot/templates/layout.html
index 486c1ee..2ec8ee2 100644
--- a/webroot/templates/layout.html
+++ b/webroot/templates/layout.html
@@ -46,6 +46,7 @@
{{define "repotabs"}}
<nav class="repotabs">
<a class="{{if eq .Tab "code"}}on{{end}}" href="/{{.Repo.Name}}{{if .Ref}}?ref={{.Ref}}{{end}}">代码</a>
+ <a class="{{if eq .Tab "issues"}}on{{end}}" href="/{{.Repo.Name}}/issues">议题 <span class="cnt">{{.IssueCount}}</span></a>
<a class="{{if eq .Tab "commits"}}on{{end}}" href="/{{.Repo.Name}}/commits/{{.Ref}}">提交 <span class="cnt">{{.CommitCount}}</span></a>
<a class="{{if eq .Tab "branches"}}on{{end}}" href="/{{.Repo.Name}}/branches">分支 <span class="cnt">{{.BranchCount}}</span></a>
<a class="{{if eq .Tab "releases"}}on{{end}}" href="/{{.Repo.Name}}/releases">发行版 <span class="cnt">{{.ReleaseCount}}</span></a>
diff --git a/webroot/templates/repo_activity.html b/webroot/templates/repo_activity.html
index 4637630..202c2c8 100644
--- a/webroot/templates/repo_activity.html
+++ b/webroot/templates/repo_activity.html
@@ -8,7 +8,7 @@
<div><h1>{{$repo.Name}}</h1></div>
</div>
</header>
-{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "activity" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount)}}
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "activity" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount "IssueCount" .Data.IssueCount)}}
<div class="repo-grid">
<div class="repo-main">
diff --git a/webroot/templates/repo_blob.html b/webroot/templates/repo_blob.html
index 75448da..ec5b283 100644
--- a/webroot/templates/repo_blob.html
+++ b/webroot/templates/repo_blob.html
@@ -8,7 +8,7 @@
<div><h1>{{$repo.Name}}</h1></div>
</div>
</header>
-{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "code" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount)}}
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "code" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount "IssueCount" .Data.IssueCount)}}
<div class="crumb-bar">
<a class="crumb" href="/{{$repo.Name}}/tree/{{.Data.Ref}}">{{$repo.Name}}</a><span class="sep">/</span>
diff --git a/webroot/templates/repo_branches.html b/webroot/templates/repo_branches.html
index ab7c8b6..6f889ec 100644
--- a/webroot/templates/repo_branches.html
+++ b/webroot/templates/repo_branches.html
@@ -8,7 +8,7 @@
<div><h1>{{$repo.Name}}</h1></div>
</div>
</header>
-{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "branches" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount)}}
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "branches" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount "IssueCount" .Data.IssueCount)}}
<div class="split">
<div class="col-main">
diff --git a/webroot/templates/repo_commits.html b/webroot/templates/repo_commits.html
index 8899ce4..46d039e 100644
--- a/webroot/templates/repo_commits.html
+++ b/webroot/templates/repo_commits.html
@@ -8,7 +8,7 @@
<div><h1>{{$repo.Name}}</h1></div>
</div>
</header>
-{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "commits" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount)}}
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "commits" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount "IssueCount" .Data.IssueCount)}}
<div class="repo-grid">
<div class="repo-main">
diff --git a/webroot/templates/repo_home.html b/webroot/templates/repo_home.html
index 49e0fab..59457e9 100644
--- a/webroot/templates/repo_home.html
+++ b/webroot/templates/repo_home.html
@@ -19,7 +19,7 @@
</div>
</header>
-{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "code" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount)}}
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "code" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount "IssueCount" .Data.IssueCount)}}
<div class="repo-grid">
<div class="repo-main">
diff --git a/webroot/templates/repo_release.html b/webroot/templates/repo_release.html
index 0e99f9e..46dc989 100644
--- a/webroot/templates/repo_release.html
+++ b/webroot/templates/repo_release.html
@@ -9,7 +9,7 @@
<div><h1><a class="quiet" href="/{{$repo.Name}}/releases">发行版</a> · {{$rel.Title}}</h1></div>
</div>
</header>
-{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "releases" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount)}}
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "releases" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount "IssueCount" .Data.IssueCount)}}
<div class="repo-grid">
<div class="repo-main">
diff --git a/webroot/templates/repo_releases.html b/webroot/templates/repo_releases.html
index bd9a515..48f6fb6 100644
--- a/webroot/templates/repo_releases.html
+++ b/webroot/templates/repo_releases.html
@@ -8,7 +8,7 @@
<div><h1>{{$repo.Name}}</h1></div>
</div>
</header>
-{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "releases" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount)}}
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "releases" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount "IssueCount" .Data.IssueCount)}}
<div class="section-head">
<h2>发行版</h2>
diff --git a/webroot/templates/repo_settings.html b/webroot/templates/repo_settings.html
index 2422689..171e9f9 100644
--- a/webroot/templates/repo_settings.html
+++ b/webroot/templates/repo_settings.html
@@ -8,7 +8,7 @@
<div><h1>{{$repo.Name}}</h1></div>
</div>
</header>
-{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "settings" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount)}}
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "settings" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount "IssueCount" .Data.IssueCount)}}
<div class="split">
<div class="col-main">