feat: 增加友链申请、独立页面、投票/悬赏/抽奖帖与侧栏签到,并统一开发数据目录

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-27 06:23:54 +08:00
parent df19752a1e
commit 2208af7070
80 changed files with 9620 additions and 641 deletions

View File

@@ -70,12 +70,16 @@ func (h *Handlers) APIHealth(c *gin.Context) {
// APIStats 论坛概览统计
func (h *Handlers) APIStats(c *gin.Context) {
var userCount, postCount, boardCount int64
var userCount, postCount, boardCount, commentCount int64
model.DB.Model(&model.User{}).Count(&userCount)
model.DB.Model(&model.Post{}).Where("status = ?", model.ContentStatusPublished).Count(&postCount)
model.DB.Model(&model.Board{}).Count(&boardCount)
model.DB.Model(&model.Comment{}).Where("status = ?", model.ContentStatusPublished).Count(&commentCount)
c.JSON(http.StatusOK, gin.H{
"users": userCount, "posts": postCount, "boards": boardCount,
"users": userCount,
"posts": postCount,
"boards": boardCount,
"comments": commentCount,
})
}
@@ -147,6 +151,7 @@ func (h *Handlers) APIAdminDashboard(c *gin.Context) {
pendingPosts, _ := h.Post.PendingPostCount()
pendingComments, _ := h.Comment.PendingCommentCount()
pendingReports, _ := h.Report.PendingCount()
pendingFriendLinks, _ := h.FriendLinkApply.PendingCount()
recentPosts, _, _ := h.Post.List(service.PostListQuery{
Page: 1, Size: 8, ViewerIsAdmin: true, Status: "all",
})
@@ -159,6 +164,7 @@ func (h *Handlers) APIAdminDashboard(c *gin.Context) {
"pending_posts": pendingPosts,
"pending_comments": pendingComments,
"pending_reports": pendingReports,
"pending_friend_links": pendingFriendLinks,
"recent_posts": recentPosts,
})
}
@@ -575,7 +581,9 @@ func (h *Handlers) APIAdminSettings(c *gin.Context) {
// APISiteBranding 前台公开的站点品牌配置
func (h *Handlers) APISiteBranding(c *gin.Context) {
c.JSON(http.StatusOK, h.Settings.SiteBranding())
brand := h.Settings.SiteBranding()
brand.SiteURL = h.publicBaseURL(c)
c.JSON(http.StatusOK, brand)
}
// APIAdminUpdateBranding 更新站点品牌文案
@@ -1039,7 +1047,7 @@ func (h *Handlers) APIPostDetail(c *gin.Context) {
editReason = h.Post.UserEditBlockReason(post, uid, isAdmin)
}
isEdited := post.UpdatedAt.Sub(post.CreatedAt) > time.Minute
c.JSON(http.StatusOK, gin.H{
resp := gin.H{
"post": post,
"comment_count": len(comments),
"liked": h.Post.IsLiked(uid, uint(id)),
@@ -1049,7 +1057,26 @@ func (h *Handlers) APIPostDetail(c *gin.Context) {
"edit_block_reason": editReason,
"is_edited": isEdited,
"post_edit_window_hours": h.Settings.PostEditWindowHours(),
})
}
if post.PostType == model.PostTypePoll {
if poll, err := service.GetPollView(uint(id), uid); err == nil {
resp["poll"] = poll
}
}
if post.PostType == model.PostTypeLottery {
if lottery, err := service.GetPostLotteryView(post); err == nil && lottery != nil {
resp["lottery"] = lottery
}
}
if post.PostType == model.PostTypeBounty && post.BountyStatus == model.BountyStatusOpen && post.BountyPoints > 0 {
canRefund, blockReason := service.CanRefundBounty(post, isAdmin)
resp["bounty_can_refund"] = canRefund
resp["bounty_refund_block_reason"] = blockReason
if n, err := service.CountEligibleBountyReplies(model.DB, post.ID, post.UserID); err == nil {
resp["bounty_eligible_reply_count"] = n
}
}
c.JSON(http.StatusOK, resp)
}
// APIPostComments 楼层列表

View File

@@ -39,6 +39,16 @@ func (h *Handlers) APIMePoints(c *gin.Context) {
})
}
// APIMeCheckInGet 今日签到状态
func (h *Handlers) APIMeCheckInGet(c *gin.Context) {
st, err := h.Points.GetCheckInStatus(h.currentUserID(c))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"check_in": st})
}
// APIMeCheckIn 每日签到
func (h *Handlers) APIMeCheckIn(c *gin.Context) {
st, err := h.Points.CheckIn(h.currentUserID(c))

244
handler/friend_link.go Normal file
View File

@@ -0,0 +1,244 @@
package handler
import (
"fmt"
"net/http"
"strconv"
"strings"
"git.iioio.com/freefire/jiang13-forum/service"
"github.com/gin-gonic/gin"
)
// APIApplyFriendLink 提交友情链接申请
func (h *Handlers) APIApplyFriendLink(c *gin.Context) {
uid := h.currentUserID(c)
if uid == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
return
}
var req struct {
Name string `json:"name"`
URL string `json:"url"`
Logo string `json:"logo"`
LinkOnHomepage bool `json:"link_on_homepage"`
ReciprocalPageURL string `json:"reciprocal_page_url"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
return
}
result, err := h.FriendLinkApply.Create(service.FriendLinkApplyInput{
UserID: uid,
Name: req.Name,
URL: req.URL,
Logo: req.Logo,
LinkOnHomepage: req.LinkOnHomepage,
ReciprocalPageURL: req.ReciprocalPageURL,
OurSiteURL: h.publicBaseURL(c),
})
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
resp := gin.H{
"message": friendLinkApplySubmittedMessage(h.Settings.FriendLinkReciprocalCheckEnabled(), false),
"apply": result.Apply,
}
c.JSON(http.StatusOK, resp)
}
// APIUploadFriendLinkLogo 上传友链申请 LOGO
func (h *Handlers) APIUploadFriendLinkLogo(c *gin.Context) {
uid := h.currentUserID(c)
if uid == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
return
}
file, err := c.FormFile("logo")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请选择 LOGO 图片"})
return
}
maxBytes := int64(h.Settings.AvatarMaxMB()) * 1024 * 1024
if file.Size > maxBytes {
c.JSON(http.StatusBadRequest, gin.H{"error": "图片文件过大"})
return
}
url, err := service.SaveUploadedImage(
h.Store,
file,
service.UploadCategorySite,
fmt.Sprintf("fl_%d", uid),
)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "LOGO 已上传", "url": url})
}
// APIAdminFriendLinkApplies 管理员友链申请列表
func (h *Handlers) APIAdminFriendLinkApplies(c *gin.Context) {
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
size, _ := strconv.Atoi(c.DefaultQuery("size", "20"))
status := strings.TrimSpace(c.DefaultQuery("status", "pending"))
list, total, err := h.FriendLinkApply.ListAdmin(service.FriendLinkApplyListQuery{
Page: page, Size: size, Status: status,
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
pending, _ := h.FriendLinkApply.PendingCount()
c.JSON(http.StatusOK, gin.H{
"applies": list,
"total": total,
"page": page,
"pending_count": pending,
"reciprocal_check_enabled": h.Settings.FriendLinkReciprocalCheckEnabled(),
})
}
// APIAdminUpdateFriendLinkSettings 更新友链回链检测开关
func (h *Handlers) APIAdminUpdateFriendLinkSettings(c *gin.Context) {
var req struct {
ReciprocalCheckEnabled *bool `json:"reciprocal_check_enabled"`
}
if err := c.ShouldBindJSON(&req); err != nil || req.ReciprocalCheckEnabled == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
return
}
if err := h.Settings.SetFriendLinkReciprocalCheckEnabled(*req.ReciprocalCheckEnabled); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
enabled := *req.ReciprocalCheckEnabled
msg := "已开启回链检测"
if !enabled {
msg = "已关闭回链检测"
}
c.JSON(http.StatusOK, gin.H{
"message": msg,
"reciprocal_check_enabled": enabled,
})
}
// APIAdminApproveFriendLinkApply 通过友链申请
func (h *Handlers) APIAdminApproveFriendLinkApply(c *gin.Context) {
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
apply, err := h.FriendLinkApply.Approve(uint(id))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "已通过并加入友情链接", "apply": apply})
}
// APIAdminRejectFriendLinkApply 拒绝友链申请
func (h *Handlers) APIAdminRejectFriendLinkApply(c *gin.Context) {
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
var req struct {
Note string `json:"note"`
}
_ = c.ShouldBindJSON(&req)
apply, err := h.FriendLinkApply.Reject(uint(id), req.Note)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "已拒绝申请", "apply": apply})
}
// APIMyFriendLinkApplies 当前用户的友链申请列表
func (h *Handlers) APIMyFriendLinkApplies(c *gin.Context) {
uid := h.currentUserID(c)
if uid == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
return
}
list, err := h.FriendLinkApply.ListMine(uid)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"applies": list})
}
// APICancelFriendLinkApply 撤销待审友链申请
func (h *Handlers) APICancelFriendLinkApply(c *gin.Context) {
uid := h.currentUserID(c)
if uid == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
return
}
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
if err := h.FriendLinkApply.Cancel(uid, uint(id)); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "已撤销申请"})
}
// APIUpdateFriendLinkApply 修改并重新提交友链申请
func (h *Handlers) APIUpdateFriendLinkApply(c *gin.Context) {
uid := h.currentUserID(c)
if uid == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
return
}
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
var req struct {
Name string `json:"name"`
URL string `json:"url"`
Logo string `json:"logo"`
LinkOnHomepage bool `json:"link_on_homepage"`
ReciprocalPageURL string `json:"reciprocal_page_url"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
return
}
result, err := h.FriendLinkApply.Update(uid, uint(id), service.FriendLinkApplyInput{
UserID: uid,
Name: req.Name,
URL: req.URL,
Logo: req.Logo,
LinkOnHomepage: req.LinkOnHomepage,
ReciprocalPageURL: req.ReciprocalPageURL,
OurSiteURL: h.publicBaseURL(c),
})
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
resp := gin.H{
"message": friendLinkApplySubmittedMessage(h.Settings.FriendLinkReciprocalCheckEnabled(), true),
"apply": result.Apply,
}
c.JSON(http.StatusOK, resp)
}
// APIAdminRecheckFriendLinkApply 管理员重新检测回链
func (h *Handlers) APIAdminRecheckFriendLinkApply(c *gin.Context) {
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
apply, err := h.FriendLinkApply.RecheckReciprocal(uint(id), h.publicBaseURL(c))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "已开始重新检测回链", "apply": apply})
}
func friendLinkApplySubmittedMessage(checkEnabled, isUpdate bool) string {
if isUpdate {
if checkEnabled {
return "申请已更新,回链检测将在后台进行"
}
return "申请已更新"
}
if checkEnabled {
return "申请已提交,回链检测将在后台进行"
}
return "申请已提交"
}

View File

@@ -38,6 +38,8 @@ type Handlers struct {
Gitea *service.GiteaService
Points *service.PointsService
Badge *service.BadgeService
SitePage *service.SitePageService
FriendLinkApply *service.FriendLinkApplyService
}
func (h *Handlers) setAuthCookie(c *gin.Context, token string) {
@@ -419,6 +421,18 @@ func (h *Handlers) APICreatePost(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
extras := service.ParsePostExtrasFromForm(
c.PostForm("poll_options"),
c.PostForm("bounty_points"),
c.PostForm("lottery_winner_count"),
)
if post.PostType == model.PostTypePoll || post.PostType == model.PostTypeBounty || post.PostType == model.PostTypeLottery {
if err := service.FinalizeSpecialPostCreate(post, h.currentUserID(c), extras); err != nil {
_ = h.Post.Delete(h.currentUserID(c), post.ID, true)
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
}
msg := "发帖成功"
if post.Status == model.ContentStatusPending {
msg = "已提交审核,通过后将公开显示"

View File

@@ -2,6 +2,8 @@ package handler
import (
"encoding/json"
"fmt"
"html"
"net/http"
"regexp"
"strconv"
@@ -15,8 +17,7 @@ import (
)
var (
seoPostEditRe = regexp.MustCompile(`^/post/(\d+)/edit/?$`)
seoBoardPathRe = regexp.MustCompile(`^/board/(\d+)/?$`)
seoPostEditRe = regexp.MustCompile(`^/post/(\d+)/edit/?$`)
)
const (
@@ -58,15 +59,17 @@ func (h *Handlers) SitemapXML(c *gin.Context) {
}
now := time.Now().UTC()
permalink := h.Settings.Permalink()
urls := []service.SitemapURL{
{Loc: base + "/", LastMod: now, ChangeFreq: "hourly", Priority: "1.0"},
{Loc: base + "/projects", LastMod: now, ChangeFreq: "daily", Priority: "0.6"},
{Loc: base + "/links", LastMod: now, ChangeFreq: "weekly", Priority: "0.6"},
}
if boards, err := h.Board.List(); err == nil {
for _, board := range boards {
urls = append(urls, service.SitemapURL{
Loc: base + service.QueryBoardHome(board.ID),
Loc: base + service.QueryBoardHome(board.ID, permalink),
LastMod: board.UpdatedAt.UTC(),
ChangeFreq: "daily",
Priority: "0.7",
@@ -74,8 +77,7 @@ func (h *Handlers) SitemapXML(c *gin.Context) {
}
}
permalink := h.Settings.Permalink()
if posts, err := h.Post.ListSitemap(seoSitemapLimit); err == nil {
if posts, e1 := h.Post.ListSitemap(seoSitemapLimit); e1 == nil {
for _, p := range posts {
lm := p.UpdatedAt
if lm.IsZero() {
@@ -90,7 +92,7 @@ func (h *Handlers) SitemapXML(c *gin.Context) {
}
}
if users, err := h.User.ListSitemap(seoSitemapLimit); err == nil {
if users, e2 := h.User.ListSitemap(seoSitemapLimit); e2 == nil {
for _, u := range users {
urls = append(urls, service.SitemapURL{
Loc: base + permalink.UserPath(u.ID),
@@ -101,6 +103,21 @@ func (h *Handlers) SitemapXML(c *gin.Context) {
}
}
if pages, e3 := h.SitePage.ListSitemap(seoSitemapLimit); e3 == nil {
for _, p := range pages {
lm := p.UpdatedAt
if lm.IsZero() {
lm = p.CreatedAt
}
urls = append(urls, service.SitemapURL{
Loc: base + permalink.PagePath(p.Slug),
LastMod: lm.UTC(),
ChangeFreq: "monthly",
Priority: "0.5",
})
}
}
var b strings.Builder
b.WriteString(`<?xml version="1.0" encoding="UTF-8"?>`)
b.WriteString(`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">`)
@@ -137,11 +154,6 @@ func (h *Handlers) SitemapXML(c *gin.Context) {
func (h *Handlers) ServePublicSPA(c *gin.Context) {
path := c.Request.URL.Path
if m := seoBoardPathRe.FindStringSubmatch(path); len(m) == 2 {
c.Redirect(http.StatusMovedPermanently, "/?board="+m[1])
return
}
brand := h.Settings.SiteBranding()
base := h.publicBaseURL(c)
siteName := strings.TrimSpace(brand.Name)
@@ -152,11 +164,59 @@ func (h *Handlers) ServePublicSPA(c *gin.Context) {
siteKeywords := brand.MetaKeywords()
permalink := h.Settings.Permalink()
// 旧版 /?board=id → 规范板块路径
if path == "/" || path == "" {
if boardID, err := strconv.ParseUint(c.Query("board"), 10, 64); err == nil && boardID > 0 {
target := service.QueryBoardHome(uint(boardID), permalink)
if q := c.Request.URL.RawQuery; q != "" {
// 保留 sort/keyword 等 query去掉 board
vals := c.Request.URL.Query()
vals.Del("board")
if rest := vals.Encode(); rest != "" {
target += "?" + rest
}
}
c.Redirect(http.StatusMovedPermanently, target)
return
}
}
isBot := service.IsSEOCrawler(c.Request.UserAgent())
if isBot {
c.Header("Vary", "User-Agent")
}
// 板块首页(含可选伪静态后缀)
if bm := permalink.MatchBoardPath(path); bm.OK {
if bm.NeedsCanonicalRedirect(path) {
c.Redirect(http.StatusMovedPermanently, bm.Canonical+preserveQueryExceptBoard(c))
return
}
board, err := h.Board.GetByID(bm.ID)
if err != nil {
h.serveNotFound(c, base, siteName, siteKeywords, path, isBot)
return
}
desc := strings.TrimSpace(board.Description)
if desc == "" {
desc = brand.MetaDescription()
}
meta := attachSiteSEO(&embed_static.SPAPageMeta{
Title: pageTitle(board.Name, siteName),
Description: service.TruncateRunes(desc, seoDescMax),
Keywords: service.JoinSEOKeywords(board.Name, siteKeywords),
Canonical: service.AbsoluteURL(base, bm.Canonical),
OGType: "website",
OGImage: defaultImage,
}, siteName, siteKeywords)
if isBot {
c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(h.botBoardHTML(meta, *board)))
return
}
embed_static.ServeSPAWithMeta(c, meta)
return
}
// 帖子详情(含可选伪静态后缀)
if pm := permalink.MatchPostPath(path); pm.OK {
if pm.NeedsCanonicalRedirect(path) {
@@ -196,6 +256,35 @@ func (h *Handlers) ServePublicSPA(c *gin.Context) {
return
}
// 自定义单页
if pg := permalink.MatchPagePath(path); pg.OK {
if strings.TrimSuffix(path, "/") != strings.TrimSuffix(pg.Canonical, "/") {
c.Redirect(http.StatusMovedPermanently, pg.Canonical)
return
}
page, err := h.SitePage.GetBySlug(pg.Slug, h.isAdmin(c))
if err != nil {
h.serveNotFound(c, base, siteName, siteKeywords, path, isBot)
return
}
desc := service.ExcerptFromHTML(page.Content, seoDescMax)
meta := attachSiteSEO(&embed_static.SPAPageMeta{
Title: pageTitle(page.Title, siteName),
Description: desc,
Keywords: service.JoinSEOKeywords(page.Title, siteKeywords),
Canonical: service.AbsoluteURL(base, pg.Canonical),
OGType: "article",
OGImage: defaultImage,
}, siteName, siteKeywords)
if isBot {
body := fmt.Sprintf(`<h1>%s</h1><div>%s</div>`, html.EscapeString(page.Title), page.Content)
c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(renderBotHTML(meta, body)))
return
}
embed_static.ServeSPAWithMeta(c, meta)
return
}
// 未知路径 → 404
if !isKnownPublicPath(path) {
h.serveNotFound(c, base, siteName, siteKeywords, path, isBot)
@@ -246,12 +335,19 @@ func attachSiteSEO(meta *embed_static.SPAPageMeta, siteName, keywords string) *e
func isKnownPublicPath(path string) bool {
switch path {
case "/", "/login", "/register", "/compose", "/profile", "/favorites", "/projects", "/boards":
case "/", "/login", "/register", "/compose", "/profile", "/favorites", "/projects", "/links", "/boards":
return true
}
if seoPostEditRe.MatchString(path) {
return true
}
permalink := service.PermalinkConfig{}
if permalink.MatchBoardPath(path).OK {
return true
}
if permalink.MatchPagePath(path).OK {
return true
}
return false
}
@@ -284,7 +380,7 @@ func (h *Handlers) buildSPAPageMeta(c *gin.Context, path string, brand service.S
}
meta.Title = pageTitle(board.Name, siteName)
meta.Description = service.TruncateRunes(desc, seoDescMax)
meta.Canonical = service.AbsoluteURL(base, service.QueryBoardHome(board.ID))
meta.Canonical = service.AbsoluteURL(base, service.QueryBoardHome(board.ID, h.Settings.Permalink()))
meta.Keywords = service.JoinSEOKeywords(board.Name, siteKeywords)
return meta
}
@@ -307,6 +403,12 @@ func (h *Handlers) buildSPAPageMeta(c *gin.Context, path string, brand service.S
meta.Keywords = service.JoinSEOKeywords("项目", siteKeywords)
}
if path == "/links" {
meta.Title = pageTitle("友情链接", siteName)
meta.Description = service.TruncateRunes(siteName+" 的友情链接与申请入口", seoDescMax)
meta.Keywords = service.JoinSEOKeywords("友情链接", siteKeywords)
}
return meta
}
@@ -436,12 +538,13 @@ func pathWithQuery(c *gin.Context) string {
if path == "" {
path = "/"
}
permalink := service.PermalinkConfig{} // 由调用方在 buildSPAPageMeta 中单独处理 board
if q := c.Request.URL.RawQuery; q != "" {
// 首页排序/搜索不作为 canonical板块筛选保留
if path == "/" {
board := c.Query("board")
if board != "" {
return service.QueryBoardHome(uint(parseUintOrZero(board)))
_ = permalink
return service.LegacyQueryBoardHome(uint(parseUintOrZero(board)))
}
return "/"
}
@@ -450,6 +553,15 @@ func pathWithQuery(c *gin.Context) string {
return path
}
func preserveQueryExceptBoard(c *gin.Context) string {
vals := c.Request.URL.Query()
vals.Del("board")
if rest := vals.Encode(); rest != "" {
return "?" + rest
}
return ""
}
func parseUintOrZero(s string) uint64 {
n, _ := strconv.ParseUint(s, 10, 64)
return n

View File

@@ -87,6 +87,18 @@ func writeEscapedMeta(b *strings.Builder, attr, key, content string) {
b.WriteString("<meta " + attr + "=\"" + html.EscapeString(key) + "\" content=\"" + html.EscapeString(content) + "\"/>")
}
func (h *Handlers) botBoardHTML(meta *embed_static.SPAPageMeta, board model.Board) string {
desc := strings.TrimSpace(board.Description)
if desc == "" {
desc = meta.Description
}
body := fmt.Sprintf(`<h1>%s</h1><p class="meta">%s</p>`,
html.EscapeString(board.Name),
html.EscapeString(desc),
)
return renderBotHTML(meta, body)
}
func (h *Handlers) botHomeHTML(meta *embed_static.SPAPageMeta, brand service.SiteBranding) string {
name := strings.TrimSpace(brand.Name)
if name == "" {

158
handler/special.go Normal file
View File

@@ -0,0 +1,158 @@
package handler
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"git.iioio.com/freefire/jiang13-forum/model"
"git.iioio.com/freefire/jiang13-forum/service"
)
// APIPages 已发布单页摘要列表
func (h *Handlers) APIPages(c *gin.Context) {
pages, err := h.SitePage.ListPublished()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if pages == nil {
pages = []service.SitePageSummary{}
}
c.JSON(http.StatusOK, gin.H{"pages": pages})
}
// APIPageDetail 单页详情
func (h *Handlers) APIPageDetail(c *gin.Context) {
slug := c.Param("slug")
allowDraft := h.isAdmin(c)
page, err := h.SitePage.GetBySlug(slug, allowDraft)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "页面不存在"})
return
}
c.JSON(http.StatusOK, gin.H{"page": page})
}
// APIAdminPages 管理端单页列表
func (h *Handlers) APIAdminPages(c *gin.Context) {
pages, err := h.SitePage.ListAll()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if pages == nil {
pages = []model.SitePage{}
}
c.JSON(http.StatusOK, gin.H{"pages": pages})
}
// APIAdminCreatePage 创建单页
func (h *Handlers) APIAdminCreatePage(c *gin.Context) {
var in service.SitePageInput
if err := c.ShouldBindJSON(&in); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求格式无效"})
return
}
page, err := h.SitePage.Create(in)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "单页已创建", "page": page})
}
// APIAdminUpdatePage 更新单页
func (h *Handlers) APIAdminUpdatePage(c *gin.Context) {
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
var in service.SitePageInput
if err := c.ShouldBindJSON(&in); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求格式无效"})
return
}
if err := h.SitePage.Update(uint(id), in); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "单页已更新"})
}
// APIAdminDeletePage 删除单页
func (h *Handlers) APIAdminDeletePage(c *gin.Context) {
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
if err := h.SitePage.Delete(uint(id)); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "单页已删除"})
}
// APIPollVote 投票
func (h *Handlers) APIPollVote(c *gin.Context) {
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
var body struct {
OptionIDs []uint `json:"option_ids"`
}
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求格式无效"})
return
}
if err := service.VotePoll(uint(id), h.currentUserID(c), body.OptionIDs); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
poll, _ := service.GetPollView(uint(id), h.currentUserID(c))
c.JSON(http.StatusOK, gin.H{"message": "投票成功", "poll": poll})
}
// APIPollClose 结束投票
func (h *Handlers) APIPollClose(c *gin.Context) {
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
post, err := h.Post.FindByID(uint(id))
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "帖子不存在"})
return
}
if err := service.ClosePoll(uint(id), h.currentUserID(c), h.isAdmin(c), post.UserID); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
poll, _ := service.GetPollView(uint(id), h.currentUserID(c))
c.JSON(http.StatusOK, gin.H{"message": "投票已结束", "poll": poll})
}
// APIBountyAward 采纳悬赏
func (h *Handlers) APIBountyAward(c *gin.Context) {
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
commentID, _ := strconv.ParseUint(c.PostForm("comment_id"), 10, 64)
if commentID == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "请选择评论"})
return
}
if err := service.AwardBounty(uint(id), h.currentUserID(c), h.isAdmin(c), uint(commentID)); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "悬赏已发放"})
}
// APIBountyRefund 退回悬赏
func (h *Handlers) APIBountyRefund(c *gin.Context) {
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
if err := service.RefundBounty(uint(id), h.currentUserID(c), h.isAdmin(c)); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "悬赏已退回"})
}
// APILotteryDraw 帖内抽奖开奖
func (h *Handlers) APILotteryDraw(c *gin.Context) {
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
view, err := service.DrawPostLottery(uint(id), h.currentUserID(c), h.isAdmin(c))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "开奖完成", "lottery": view})
}