部分缓存代码结构目录优化

This commit is contained in:
xing 2023-01-19 21:02:39 +08:00
parent 6bde2bcfd3
commit 285a8077ea
8 changed files with 254 additions and 226 deletions

View File

@ -4,10 +4,9 @@ import (
"bytes" "bytes"
"errors" "errors"
"fmt" "fmt"
"github.com/fthvgb1/wp-go/cache"
"github.com/fthvgb1/wp-go/helper" "github.com/fthvgb1/wp-go/helper"
"github.com/fthvgb1/wp-go/internal/mail" "github.com/fthvgb1/wp-go/internal/mail"
cache2 "github.com/fthvgb1/wp-go/internal/pkg/cache" "github.com/fthvgb1/wp-go/internal/pkg/cache"
"github.com/fthvgb1/wp-go/internal/pkg/config" "github.com/fthvgb1/wp-go/internal/pkg/config"
"github.com/fthvgb1/wp-go/internal/pkg/logs" "github.com/fthvgb1/wp-go/internal/pkg/logs"
"github.com/fthvgb1/wp-go/internal/wpconfig" "github.com/fthvgb1/wp-go/internal/wpconfig"
@ -20,8 +19,6 @@ import (
"time" "time"
) )
var commentCache = cache.NewMapCacheByFn[string, string](nil, 15*time.Minute)
func PostComment(c *gin.Context) { func PostComment(c *gin.Context) {
cli := &http.Client{ cli := &http.Client{
Timeout: time.Second * 3, Timeout: time.Second * 3,
@ -99,7 +96,7 @@ func PostComment(c *gin.Context) {
logs.ErrPrintln(err, "获取文档id", i) logs.ErrPrintln(err, "获取文档id", i)
return return
} }
post, err := cache2.GetPostById(cc, id) post, err := cache.GetPostById(cc, id)
if err != nil { if err != nil {
logs.ErrPrintln(err, "获取文档", id) logs.ErrPrintln(err, "获取文档", id)
return return
@ -114,7 +111,7 @@ func PostComment(c *gin.Context) {
err = er err = er
return return
} }
commentCache.Set(up.RawQuery, string(s)) cache.NewCommentCache().Set(up.RawQuery, string(s))
c.Redirect(http.StatusFound, res.Header.Get("Location")) c.Redirect(http.StatusFound, res.Header.Get("Location"))
return return
} }

View File

@ -3,7 +3,7 @@ package actions
import ( import (
"fmt" "fmt"
"github.com/fthvgb1/wp-go/helper" "github.com/fthvgb1/wp-go/helper"
cache2 "github.com/fthvgb1/wp-go/internal/pkg/cache" "github.com/fthvgb1/wp-go/internal/pkg/cache"
"github.com/fthvgb1/wp-go/internal/pkg/logs" "github.com/fthvgb1/wp-go/internal/pkg/logs"
"github.com/fthvgb1/wp-go/internal/pkg/models" "github.com/fthvgb1/wp-go/internal/pkg/models"
"github.com/fthvgb1/wp-go/internal/plugins" "github.com/fthvgb1/wp-go/internal/plugins"
@ -28,10 +28,10 @@ func Detail(c *gin.Context) {
hh := detailHandler{ hh := detailHandler{
c, c,
} }
recent := cache2.RecentPosts(c, 5) recent := cache.RecentPosts(c, 5)
archive := cache2.Archives(c) archive := cache.Archives(c)
categoryItems := cache2.Categories(c) categoryItems := cache.Categories(c)
recentComments := cache2.RecentComments(c, 5) recentComments := cache.RecentComments(c, 5)
var h = gin.H{ var h = gin.H{
"title": wpconfig.Options.Value("blogname"), "title": wpconfig.Options.Value("blogname"),
"options": wpconfig.Options, "options": wpconfig.Options,
@ -62,12 +62,12 @@ func Detail(c *gin.Context) {
} }
} }
ID := uint64(Id) ID := uint64(Id)
maxId, err := cache2.GetMaxPostId(c) maxId, err := cache.GetMaxPostId(c)
logs.ErrPrintln(err, "get max post id") logs.ErrPrintln(err, "get max post id")
if ID > maxId || err != nil { if ID > maxId || err != nil {
return return
} }
post, err := cache2.GetPostById(c, ID) post, err := cache.GetPostById(c, ID)
if post.Id == 0 || err != nil { if post.Id == 0 || err != nil {
return return
} }
@ -76,12 +76,12 @@ func Detail(c *gin.Context) {
if post.CommentCount > 0 || post.CommentStatus == "open" { if post.CommentCount > 0 || post.CommentStatus == "open" {
showComment = true showComment = true
} }
user := cache2.GetUserById(c, post.PostAuthor) user := cache.GetUserById(c, post.PostAuthor)
plugins.PasswordProjectTitle(&post) plugins.PasswordProjectTitle(&post)
if post.PostPassword != "" && pw != post.PostPassword { if post.PostPassword != "" && pw != post.PostPassword {
plugins.PasswdProjectContent(&post) plugins.PasswdProjectContent(&post)
showComment = false showComment = false
} else if s, ok := commentCache.Get(c.Request.URL.RawQuery); ok && s != "" && (post.PostPassword == "" || post.PostPassword != "" && pw == post.PostPassword) { } else if s, ok := cache.NewCommentCache().Get(c.Request.URL.RawQuery); ok && s != "" && (post.PostPassword == "" || post.PostPassword != "" && pw == post.PostPassword) {
c.Writer.WriteHeader(http.StatusOK) c.Writer.WriteHeader(http.StatusOK)
c.Writer.Header().Set("Content-Type", "text/html; charset=utf-8") c.Writer.Header().Set("Content-Type", "text/html; charset=utf-8")
_, err = c.Writer.WriteString(s) _, err = c.Writer.WriteString(s)
@ -89,10 +89,10 @@ func Detail(c *gin.Context) {
return return
} }
plugins.ApplyPlugin(plugins.NewPostPlugin(c, plugins.Detail), &post) plugins.ApplyPlugin(plugins.NewPostPlugin(c, plugins.Detail), &post)
comments, err := cache2.PostComments(c, post.Id) comments, err := cache.PostComments(c, post.Id)
logs.ErrPrintln(err, "get post comment", post.Id) logs.ErrPrintln(err, "get post comment", post.Id)
commentss := treeComments(comments) commentss := treeComments(comments)
prev, next, err := cache2.GetContextPost(c, post.Id, post.PostDate) prev, next, err := cache.GetContextPost(c, post.Id, post.PostDate)
logs.ErrPrintln(err, "get pre and next post", post.Id, post.PostDate) logs.ErrPrintln(err, "get pre and next post", post.Id, post.PostDate)
h["title"] = fmt.Sprintf("%s-%s", post.PostTitle, wpconfig.Options.Value("blogname")) h["title"] = fmt.Sprintf("%s-%s", post.PostTitle, wpconfig.Options.Value("blogname"))
h["post"] = post h["post"] = post

View File

@ -1,51 +1,14 @@
package actions package actions
import ( import (
"fmt"
"github.com/fthvgb1/wp-go/cache"
"github.com/fthvgb1/wp-go/helper" "github.com/fthvgb1/wp-go/helper"
cache2 "github.com/fthvgb1/wp-go/internal/pkg/cache" "github.com/fthvgb1/wp-go/internal/pkg/cache"
"github.com/fthvgb1/wp-go/internal/pkg/logs"
"github.com/fthvgb1/wp-go/internal/pkg/models"
"github.com/fthvgb1/wp-go/internal/plugins"
"github.com/fthvgb1/wp-go/internal/wpconfig"
"github.com/fthvgb1/wp-go/plugin/digest"
"github.com/fthvgb1/wp-go/rss2"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"net/http" "net/http"
"strconv"
"strings"
"time" "time"
) )
var feedCache = cache.NewSliceCache(feed, time.Hour)
var postFeedCache = cache.NewMapCacheByFn[string, string](postFeed, time.Hour)
var tmp = "Mon, 02 Jan 2006 15:04:05 GMT" var tmp = "Mon, 02 Jan 2006 15:04:05 GMT"
var timeFormat = "Mon, 02 Jan 2006 15:04:05 +0000"
var templateRss rss2.Rss2
var commentsFeedCache = cache.NewSliceCache(commentsFeed, time.Hour)
func InitFeed() {
templateRss = rss2.Rss2{
Title: wpconfig.Options.Value("blogname"),
AtomLink: fmt.Sprintf("%s/feed", wpconfig.Options.Value("home")),
Link: wpconfig.Options.Value("siteurl"),
Description: wpconfig.Options.Value("blogdescription"),
Language: "zh-CN",
UpdatePeriod: "hourly",
UpdateFrequency: 1,
Generator: wpconfig.Options.Value("home"),
}
}
func ClearCache() {
postFeedCache.ClearExpired()
commentCache.ClearExpired()
}
func FlushCache() {
postFeedCache.Flush()
commentCache.Flush()
}
func isCacheExpired(c *gin.Context, lastTime time.Time) bool { func isCacheExpired(c *gin.Context, lastTime time.Time) bool {
eTag := helper.StringMd5(lastTime.Format(tmp)) eTag := helper.StringMd5(lastTime.Format(tmp))
@ -62,66 +25,20 @@ func isCacheExpired(c *gin.Context, lastTime time.Time) bool {
} }
func Feed(c *gin.Context) { func Feed(c *gin.Context) {
if !isCacheExpired(c, feedCache.GetLastSetTime()) { if !isCacheExpired(c, cache.FeedCache().GetLastSetTime()) {
c.Status(http.StatusNotModified) c.Status(http.StatusNotModified)
} else { } else {
r, err := feedCache.GetCache(c, time.Second, c) r, err := cache.FeedCache().GetCache(c, time.Second, c)
if err != nil { if err != nil {
c.Status(http.StatusInternalServerError) c.Status(http.StatusInternalServerError)
c.Abort() c.Abort()
c.Error(err) c.Error(err)
return return
} }
setFeed(r[0], c, feedCache.GetLastSetTime()) setFeed(r[0], c, cache.FeedCache().GetLastSetTime())
} }
} }
func feed(arg ...any) (xml []string, err error) {
c := arg[0].(*gin.Context)
r := cache2.RecentPosts(c, 10)
ids := helper.SliceMap(r, func(t models.Posts) uint64 {
return t.Id
})
posts, err := cache2.GetPostsByIds(c, ids)
if err != nil {
return
}
rs := templateRss
rs.LastBuildDate = time.Now().Format(timeFormat)
rs.Items = helper.SliceMap(posts, func(t models.Posts) rss2.Item {
desc := "无法提供摘要。这是一篇受保护的文章。"
plugins.PasswordProjectTitle(&t)
if t.PostPassword != "" {
plugins.PasswdProjectContent(&t)
} else {
desc = digest.Raw(t.PostContent, 55, fmt.Sprintf("/p/%d", t.Id))
}
l := ""
if t.CommentStatus == "open" && t.CommentCount > 0 {
l = fmt.Sprintf("%s/p/%d#comments", wpconfig.Options.Value("siteurl"), t.Id)
} else if t.CommentStatus == "open" && t.CommentCount == 0 {
l = fmt.Sprintf("%s/p/%d#respond", wpconfig.Options.Value("siteurl"), t.Id)
}
user := cache2.GetUserById(c, t.PostAuthor)
return rss2.Item{
Title: t.PostTitle,
Creator: user.DisplayName,
Guid: t.Guid,
SlashComments: int(t.CommentCount),
Content: t.PostContent,
Category: strings.Join(t.Categories, "、"),
CommentLink: l,
CommentRss: fmt.Sprintf("%s/p/%d/feed", wpconfig.Options.Value("siteurl"), t.Id),
Link: fmt.Sprintf("%s/p/%d", wpconfig.Options.Value("siteurl"), t.Id),
Description: desc,
PubDate: t.PostDateGmt.Format(timeFormat),
}
})
xml = []string{rs.GetXML()}
return
}
func setFeed(s string, c *gin.Context, t time.Time) { func setFeed(s string, c *gin.Context, t time.Time) {
lastTimeGMT := t.Format(tmp) lastTimeGMT := t.Format(tmp)
eTag := helper.StringMd5(lastTimeGMT) eTag := helper.StringMd5(lastTimeGMT)
@ -133,134 +50,31 @@ func setFeed(s string, c *gin.Context, t time.Time) {
func PostFeed(c *gin.Context) { func PostFeed(c *gin.Context) {
id := c.Param("id") id := c.Param("id")
if !isCacheExpired(c, postFeedCache.GetLastSetTime(id)) { if !isCacheExpired(c, cache.PostFeedCache().GetLastSetTime(id)) {
c.Status(http.StatusNotModified) c.Status(http.StatusNotModified)
} else { } else {
s, err := postFeedCache.GetCache(c, id, time.Second, c, id) s, err := cache.PostFeedCache().GetCache(c, id, time.Second, c, id)
if err != nil { if err != nil {
c.Status(http.StatusInternalServerError) c.Status(http.StatusInternalServerError)
c.Abort() c.Abort()
c.Error(err) c.Error(err)
return return
} }
setFeed(s, c, postFeedCache.GetLastSetTime(id)) setFeed(s, c, cache.PostFeedCache().GetLastSetTime(id))
} }
} }
func postFeed(arg ...any) (x string, err error) {
c := arg[0].(*gin.Context)
id := arg[1].(string)
Id := 0
if id != "" {
Id, err = strconv.Atoi(id)
if err != nil {
return
}
}
ID := uint64(Id)
maxId, err := cache2.GetMaxPostId(c)
logs.ErrPrintln(err, "get max post id")
if ID > maxId || err != nil {
return
}
post, err := cache2.GetPostById(c, ID)
if post.Id == 0 || err != nil {
return
}
plugins.PasswordProjectTitle(&post)
comments, err := cache2.PostComments(c, post.Id)
if err != nil {
return
}
rs := templateRss
rs.Title = fmt.Sprintf("《%s》的评论", post.PostTitle)
rs.AtomLink = fmt.Sprintf("%s/p/%d/feed", wpconfig.Options.Value("siteurl"), post.Id)
rs.Link = fmt.Sprintf("%s/p/%d", wpconfig.Options.Value("siteurl"), post.Id)
rs.LastBuildDate = time.Now().Format(timeFormat)
if post.PostPassword != "" {
if len(comments) > 0 {
plugins.PasswdProjectContent(&post)
t := comments[len(comments)-1]
rs.Items = []rss2.Item{
{
Title: fmt.Sprintf("评价者:%s", t.CommentAuthor),
Link: fmt.Sprintf("%s/p/%d#comment-%d", wpconfig.Options.Value("siteurl"), post.Id, t.CommentId),
Creator: t.CommentAuthor,
PubDate: t.CommentDateGmt.Format(timeFormat),
Guid: fmt.Sprintf("%s#comment-%d", post.Guid, t.CommentId),
Description: "评论受保护:要查看请输入密码。",
Content: post.PostContent,
},
}
}
} else {
rs.Items = helper.SliceMap(comments, func(t models.Comments) rss2.Item {
return rss2.Item{
Title: fmt.Sprintf("评价者:%s", t.CommentAuthor),
Link: fmt.Sprintf("%s/p/%d#comment-%d", wpconfig.Options.Value("siteurl"), post.Id, t.CommentId),
Creator: t.CommentAuthor,
PubDate: t.CommentDateGmt.Format(timeFormat),
Guid: fmt.Sprintf("%s#comment-%d", post.Guid, t.CommentId),
Content: t.CommentContent,
}
})
}
x = rs.GetXML()
return
}
func CommentsFeed(c *gin.Context) { func CommentsFeed(c *gin.Context) {
if !isCacheExpired(c, commentsFeedCache.GetLastSetTime()) { if !isCacheExpired(c, cache.CommentsFeedCache().GetLastSetTime()) {
c.Status(http.StatusNotModified) c.Status(http.StatusNotModified)
} else { } else {
r, err := commentsFeedCache.GetCache(c, time.Second, c) r, err := cache.CommentsFeedCache().GetCache(c, time.Second, c)
if err != nil { if err != nil {
c.Status(http.StatusInternalServerError) c.Status(http.StatusInternalServerError)
c.Abort() c.Abort()
c.Error(err) c.Error(err)
return return
} }
setFeed(r[0], c, commentsFeedCache.GetLastSetTime()) setFeed(r[0], c, cache.CommentsFeedCache().GetLastSetTime())
} }
} }
func commentsFeed(args ...any) (r []string, err error) {
c := args[0].(*gin.Context)
commens := cache2.RecentComments(c, 10)
rs := templateRss
rs.Title = fmt.Sprintf("\"%s\"的评论", wpconfig.Options.Value("blogname"))
rs.LastBuildDate = time.Now().Format(timeFormat)
rs.AtomLink = fmt.Sprintf("%s/comments/feed", wpconfig.Options.Value("siteurl"))
com, err := cache2.GetCommentByIds(c, helper.SliceMap(commens, func(t models.Comments) uint64 {
return t.CommentId
}))
if nil != err {
return []string{}, err
}
rs.Items = helper.SliceMap(com, func(t models.Comments) rss2.Item {
post, _ := cache2.GetPostById(c, t.CommentPostId)
plugins.PasswordProjectTitle(&post)
desc := "评论受保护:要查看请输入密码。"
content := t.CommentContent
if post.PostPassword != "" {
plugins.PasswdProjectContent(&post)
content = post.PostContent
} else {
desc = digest.ClearHtml(t.CommentContent)
content = desc
}
return rss2.Item{
Title: fmt.Sprintf("%s对《%s》的评论", t.CommentAuthor, post.PostTitle),
Link: fmt.Sprintf("%s/p/%d#comment-%d", wpconfig.Options.Value("siteurl"), post.Id, t.CommentId),
Creator: t.CommentAuthor,
Description: desc,
PubDate: t.CommentDateGmt.Format(timeFormat),
Guid: fmt.Sprintf("%s#commment-%d", post.Guid, t.CommentId),
Content: content,
}
})
r = []string{rs.GetXML()}
return
}

View File

@ -3,7 +3,7 @@ package actions
import ( import (
"fmt" "fmt"
"github.com/fthvgb1/wp-go/helper" "github.com/fthvgb1/wp-go/helper"
cache2 "github.com/fthvgb1/wp-go/internal/pkg/cache" "github.com/fthvgb1/wp-go/internal/pkg/cache"
dao "github.com/fthvgb1/wp-go/internal/pkg/dao" dao "github.com/fthvgb1/wp-go/internal/pkg/dao"
"github.com/fthvgb1/wp-go/internal/pkg/logs" "github.com/fthvgb1/wp-go/internal/pkg/logs"
"github.com/fthvgb1/wp-go/internal/pkg/models" "github.com/fthvgb1/wp-go/internal/pkg/models"
@ -116,7 +116,7 @@ func (h *indexHandle) parseParams() (err error) {
h.category = category h.category = category
username := h.c.Param("author") username := h.c.Param("author")
if username != "" { if username != "" {
user, er := cache2.GetUserByName(h.c, username) user, er := cache.GetUserByName(h.c, username)
if er != nil { if er != nil {
err = er err = er
return return
@ -183,10 +183,10 @@ func Index(c *gin.Context) {
var postIds []models.Posts var postIds []models.Posts
var totalRaw int var totalRaw int
var err error var err error
archive := cache2.Archives(c) archive := cache.Archives(c)
recent := cache2.RecentPosts(c, 5) recent := cache.RecentPosts(c, 5)
categoryItems := cache2.Categories(c) categoryItems := cache.Categories(c)
recentComments := cache2.RecentComments(c, 5) recentComments := cache.RecentComments(c, 5)
ginH := gin.H{ ginH := gin.H{
"options": wpconfig.Options, "options": wpconfig.Options,
"recentPosts": recent, "recentPosts": recent,
@ -212,14 +212,14 @@ func Index(c *gin.Context) {
} }
ginH["title"] = h.getTitle() ginH["title"] = h.getTitle()
if c.Param("month") != "" { if c.Param("month") != "" {
postIds, totalRaw, err = cache2.GetMonthPostIds(c, c.Param("year"), c.Param("month"), h.page, h.pageSize, h.order) postIds, totalRaw, err = cache.GetMonthPostIds(c, c.Param("year"), c.Param("month"), h.page, h.pageSize, h.order)
if err != nil { if err != nil {
return return
} }
} else if h.search != "" { } else if h.search != "" {
postIds, totalRaw, err = cache2.SearchPost(c, h.getSearchKey(), c, h.where, h.page, h.pageSize, model.SqlBuilder{{h.orderBy, h.order}}, h.join, h.postType, h.status) postIds, totalRaw, err = cache.SearchPost(c, h.getSearchKey(), c, h.where, h.page, h.pageSize, model.SqlBuilder{{h.orderBy, h.order}}, h.join, h.postType, h.status)
} else { } else {
postIds, totalRaw, err = cache2.PostLists(c, h.getSearchKey(), c, h.where, h.page, h.pageSize, model.SqlBuilder{{h.orderBy, h.order}}, h.join, h.postType, h.status) postIds, totalRaw, err = cache.PostLists(c, h.getSearchKey(), c, h.where, h.page, h.pageSize, model.SqlBuilder{{h.orderBy, h.order}}, h.join, h.postType, h.status)
} }
if err != nil { if err != nil {
logs.ErrPrintln(err, "获取数据错误") logs.ErrPrintln(err, "获取数据错误")

View File

@ -3,7 +3,6 @@ package main
import ( import (
"flag" "flag"
"fmt" "fmt"
"github.com/fthvgb1/wp-go/internal/actions"
"github.com/fthvgb1/wp-go/internal/cmd/route" "github.com/fthvgb1/wp-go/internal/cmd/route"
"github.com/fthvgb1/wp-go/internal/mail" "github.com/fthvgb1/wp-go/internal/mail"
"github.com/fthvgb1/wp-go/internal/pkg/cache" "github.com/fthvgb1/wp-go/internal/pkg/cache"
@ -44,7 +43,6 @@ func init() {
if err != nil { if err != nil {
panic(err) panic(err)
} }
actions.InitFeed()
cache.InitActionsCommonCache() cache.InitActionsCommonCache()
plugins.InitDigestCache() plugins.InitDigestCache()
theme.InitThemeAndTemplateFuncMap() theme.InitThemeAndTemplateFuncMap()
@ -80,7 +78,6 @@ func cronClearCache() {
case <-t.C: case <-t.C:
cache.ClearCache() cache.ClearCache()
plugins.ClearDigestCache() plugins.ClearDigestCache()
actions.ClearCache()
} }
} }
} }
@ -94,7 +91,6 @@ func flushCache() {
}() }()
cache.FlushCache() cache.FlushCache()
plugins.FlushCache() plugins.FlushCache()
actions.FlushCache()
log.Println("all cache flushed") log.Println("all cache flushed")
} }

View File

@ -30,6 +30,14 @@ var usersCache *cache.MapCache[uint64, models.Users]
var usersNameCache *cache.MapCache[string, models.Users] var usersNameCache *cache.MapCache[string, models.Users]
var commentsCache *cache.MapCache[uint64, models.Comments] var commentsCache *cache.MapCache[uint64, models.Comments]
var feedCache *cache.SliceCache[string]
var postFeedCache *cache.MapCache[string, string]
var commentsFeedCache *cache.SliceCache[string]
var newCommentCache *cache.MapCache[string, string]
func InitActionsCommonCache() { func InitActionsCommonCache() {
c := config.Conf.Load() c := config.Conf.Load()
archivesCaches = &Arch{ archivesCaches = &Arch{
@ -64,6 +72,16 @@ func InitActionsCommonCache() {
usersNameCache = cache.NewMapCacheByFn[string, models.Users](common.GetUserByName, c.UserInfoCacheTime) usersNameCache = cache.NewMapCacheByFn[string, models.Users](common.GetUserByName, c.UserInfoCacheTime)
commentsCache = cache.NewMapCacheByBatchFn[uint64, models.Comments](common.GetCommentByIds, c.CommentsCacheTime) commentsCache = cache.NewMapCacheByBatchFn[uint64, models.Comments](common.GetCommentByIds, c.CommentsCacheTime)
feedCache = cache.NewSliceCache(feed, time.Hour)
postFeedCache = cache.NewMapCacheByFn[string, string](postFeed, time.Hour)
commentsFeedCache = cache.NewSliceCache(commentsFeed, time.Hour)
newCommentCache = cache.NewMapCacheByFn[string, string](nil, 15*time.Minute)
InitFeed()
} }
func ClearCache() { func ClearCache() {
@ -76,6 +94,8 @@ func ClearCache() {
usersCache.ClearExpired() usersCache.ClearExpired()
commentsCache.ClearExpired() commentsCache.ClearExpired()
usersNameCache.ClearExpired() usersNameCache.ClearExpired()
postFeedCache.ClearExpired()
newCommentCache.ClearExpired()
} }
func FlushCache() { func FlushCache() {
searchPostIdsCache.Flush() searchPostIdsCache.Flush()
@ -87,6 +107,8 @@ func FlushCache() {
usersCache.Flush() usersCache.Flush()
commentsCache.Flush() commentsCache.Flush()
usersCache.Flush() usersCache.Flush()
postFeedCache.Flush()
newCommentCache.Flush()
} }
func Archives(ctx context.Context) (r []models.PostArchive) { func Archives(ctx context.Context) (r []models.PostArchive) {

View File

@ -2,6 +2,7 @@ package cache
import ( import (
"context" "context"
"github.com/fthvgb1/wp-go/cache"
"github.com/fthvgb1/wp-go/internal/pkg/logs" "github.com/fthvgb1/wp-go/internal/pkg/logs"
"github.com/fthvgb1/wp-go/internal/pkg/models" "github.com/fthvgb1/wp-go/internal/pkg/models"
"time" "time"
@ -31,3 +32,7 @@ func GetCommentById(ctx context.Context, id uint64) (models.Comments, error) {
func GetCommentByIds(ctx context.Context, ids []uint64) ([]models.Comments, error) { func GetCommentByIds(ctx context.Context, ids []uint64) ([]models.Comments, error) {
return commentsCache.GetCacheBatch(ctx, ids, time.Second, ctx, ids) return commentsCache.GetCacheBatch(ctx, ids, time.Second, ctx, ids)
} }
func NewCommentCache() *cache.MapCache[string, string] {
return newCommentCache
}

194
internal/pkg/cache/feed.go vendored Normal file
View File

@ -0,0 +1,194 @@
package cache
import (
"fmt"
"github.com/fthvgb1/wp-go/cache"
"github.com/fthvgb1/wp-go/helper"
"github.com/fthvgb1/wp-go/internal/pkg/logs"
"github.com/fthvgb1/wp-go/internal/pkg/models"
"github.com/fthvgb1/wp-go/internal/plugins"
"github.com/fthvgb1/wp-go/internal/wpconfig"
"github.com/fthvgb1/wp-go/plugin/digest"
"github.com/fthvgb1/wp-go/rss2"
"github.com/gin-gonic/gin"
"strconv"
"strings"
"time"
)
var timeFormat = "Mon, 02 Jan 2006 15:04:05 +0000"
var templateRss rss2.Rss2
func InitFeed() {
templateRss = rss2.Rss2{
Title: wpconfig.Options.Value("blogname"),
AtomLink: fmt.Sprintf("%s/feed", wpconfig.Options.Value("home")),
Link: wpconfig.Options.Value("siteurl"),
Description: wpconfig.Options.Value("blogdescription"),
Language: "zh-CN",
UpdatePeriod: "hourly",
UpdateFrequency: 1,
Generator: wpconfig.Options.Value("home"),
}
}
func CommentsFeedCache() *cache.SliceCache[string] {
return commentsFeedCache
}
func FeedCache() *cache.SliceCache[string] {
return feedCache
}
func PostFeedCache() *cache.MapCache[string, string] {
return postFeedCache
}
func feed(arg ...any) (xml []string, err error) {
c := arg[0].(*gin.Context)
r := RecentPosts(c, 10)
ids := helper.SliceMap(r, func(t models.Posts) uint64 {
return t.Id
})
posts, err := GetPostsByIds(c, ids)
if err != nil {
return
}
rs := templateRss
rs.LastBuildDate = time.Now().Format(timeFormat)
rs.Items = helper.SliceMap(posts, func(t models.Posts) rss2.Item {
desc := "无法提供摘要。这是一篇受保护的文章。"
plugins.PasswordProjectTitle(&t)
if t.PostPassword != "" {
plugins.PasswdProjectContent(&t)
} else {
desc = digest.Raw(t.PostContent, 55, fmt.Sprintf("/p/%d", t.Id))
}
l := ""
if t.CommentStatus == "open" && t.CommentCount > 0 {
l = fmt.Sprintf("%s/p/%d#comments", wpconfig.Options.Value("siteurl"), t.Id)
} else if t.CommentStatus == "open" && t.CommentCount == 0 {
l = fmt.Sprintf("%s/p/%d#respond", wpconfig.Options.Value("siteurl"), t.Id)
}
user := GetUserById(c, t.PostAuthor)
return rss2.Item{
Title: t.PostTitle,
Creator: user.DisplayName,
Guid: t.Guid,
SlashComments: int(t.CommentCount),
Content: t.PostContent,
Category: strings.Join(t.Categories, "、"),
CommentLink: l,
CommentRss: fmt.Sprintf("%s/p/%d/feed", wpconfig.Options.Value("siteurl"), t.Id),
Link: fmt.Sprintf("%s/p/%d", wpconfig.Options.Value("siteurl"), t.Id),
Description: desc,
PubDate: t.PostDateGmt.Format(timeFormat),
}
})
xml = []string{rs.GetXML()}
return
}
func postFeed(arg ...any) (x string, err error) {
c := arg[0].(*gin.Context)
id := arg[1].(string)
Id := 0
if id != "" {
Id, err = strconv.Atoi(id)
if err != nil {
return
}
}
ID := uint64(Id)
maxId, err := GetMaxPostId(c)
logs.ErrPrintln(err, "get max post id")
if ID > maxId || err != nil {
return
}
post, err := GetPostById(c, ID)
if post.Id == 0 || err != nil {
return
}
plugins.PasswordProjectTitle(&post)
comments, err := PostComments(c, post.Id)
if err != nil {
return
}
rs := templateRss
rs.Title = fmt.Sprintf("《%s》的评论", post.PostTitle)
rs.AtomLink = fmt.Sprintf("%s/p/%d/feed", wpconfig.Options.Value("siteurl"), post.Id)
rs.Link = fmt.Sprintf("%s/p/%d", wpconfig.Options.Value("siteurl"), post.Id)
rs.LastBuildDate = time.Now().Format(timeFormat)
if post.PostPassword != "" {
if len(comments) > 0 {
plugins.PasswdProjectContent(&post)
t := comments[len(comments)-1]
rs.Items = []rss2.Item{
{
Title: fmt.Sprintf("评价者:%s", t.CommentAuthor),
Link: fmt.Sprintf("%s/p/%d#comment-%d", wpconfig.Options.Value("siteurl"), post.Id, t.CommentId),
Creator: t.CommentAuthor,
PubDate: t.CommentDateGmt.Format(timeFormat),
Guid: fmt.Sprintf("%s#comment-%d", post.Guid, t.CommentId),
Description: "评论受保护:要查看请输入密码。",
Content: post.PostContent,
},
}
}
} else {
rs.Items = helper.SliceMap(comments, func(t models.Comments) rss2.Item {
return rss2.Item{
Title: fmt.Sprintf("评价者:%s", t.CommentAuthor),
Link: fmt.Sprintf("%s/p/%d#comment-%d", wpconfig.Options.Value("siteurl"), post.Id, t.CommentId),
Creator: t.CommentAuthor,
PubDate: t.CommentDateGmt.Format(timeFormat),
Guid: fmt.Sprintf("%s#comment-%d", post.Guid, t.CommentId),
Content: t.CommentContent,
}
})
}
x = rs.GetXML()
return
}
func commentsFeed(args ...any) (r []string, err error) {
c := args[0].(*gin.Context)
commens := RecentComments(c, 10)
rs := templateRss
rs.Title = fmt.Sprintf("\"%s\"的评论", wpconfig.Options.Value("blogname"))
rs.LastBuildDate = time.Now().Format(timeFormat)
rs.AtomLink = fmt.Sprintf("%s/comments/feed", wpconfig.Options.Value("siteurl"))
com, err := GetCommentByIds(c, helper.SliceMap(commens, func(t models.Comments) uint64 {
return t.CommentId
}))
if nil != err {
return []string{}, err
}
rs.Items = helper.SliceMap(com, func(t models.Comments) rss2.Item {
post, _ := GetPostById(c, t.CommentPostId)
plugins.PasswordProjectTitle(&post)
desc := "评论受保护:要查看请输入密码。"
content := t.CommentContent
if post.PostPassword != "" {
plugins.PasswdProjectContent(&post)
content = post.PostContent
} else {
desc = digest.ClearHtml(t.CommentContent)
content = desc
}
return rss2.Item{
Title: fmt.Sprintf("%s对《%s》的评论", t.CommentAuthor, post.PostTitle),
Link: fmt.Sprintf("%s/p/%d#comment-%d", wpconfig.Options.Value("siteurl"), post.Id, t.CommentId),
Creator: t.CommentAuthor,
Description: desc,
PubDate: t.CommentDateGmt.Format(timeFormat),
Guid: fmt.Sprintf("%s#commment-%d", post.Guid, t.CommentId),
Content: content,
}
})
r = []string{rs.GetXML()}
return
}