This commit is contained in:
xing 2022-11-05 22:40:02 +08:00
parent 0a8065b18c
commit 97c15d30aa
20 changed files with 397 additions and 123 deletions

View File

@ -68,7 +68,7 @@ func PostComment(c *gin.Context) {
logs.ErrPrintln(err, "获取文档", id)
return
}
su := fmt.Sprintf("%s: %s[%s]发表了评论对文档[%v]的评论", wp.Options["siteurl"], author, m, post.PostTitle)
su := fmt.Sprintf("%s: %s[%s]发表了评论对文档[%v]的评论", wp.Option["siteurl"], author, m, post.PostTitle)
err = mail.SendMail([]string{config.Conf.Mail.User}, su, comment)
logs.ErrPrintln(err, "发送邮件")
}()

View File

@ -10,7 +10,7 @@ import (
"time"
)
func RecentComments(ctx context.Context, n int) (r []wp.WpComments) {
func RecentComments(ctx context.Context, n int) (r []wp.Comments) {
r, err := recentCommentsCaches.GetCache(ctx, time.Second)
if len(r) > n {
r = r[0:n]
@ -18,8 +18,8 @@ func RecentComments(ctx context.Context, n int) (r []wp.WpComments) {
logs.ErrPrintln(err, "get recent comment")
return
}
func recentComments(...any) (r []wp.WpComments, err error) {
return models.Find[wp.WpComments](models.SqlBuilder{
func recentComments(...any) (r []wp.Comments, err error) {
return models.Find[wp.Comments](models.SqlBuilder{
{"comment_approved", "1"},
{"post_status", "publish"},
}, "comment_ID,comment_author,comment_post_ID,post_title", "", models.SqlBuilder{{"comment_date_gmt", "desc"}}, models.SqlBuilder{
@ -27,7 +27,7 @@ func recentComments(...any) (r []wp.WpComments, err error) {
}, nil, 10)
}
func PostComments(ctx context.Context, Id uint64) ([]wp.WpComments, error) {
func PostComments(ctx context.Context, Id uint64) ([]wp.Comments, error) {
ids, err := postCommentCaches.GetCache(ctx, Id, time.Second, Id)
if err != nil {
return nil, err
@ -37,7 +37,7 @@ func PostComments(ctx context.Context, Id uint64) ([]wp.WpComments, error) {
func postComments(args ...any) ([]uint64, error) {
postId := args[0].(uint64)
r, err := models.Find[wp.WpComments](models.SqlBuilder{
r, err := models.Find[wp.Comments](models.SqlBuilder{
{"comment_approved", "1"},
{"comment_post_ID", "=", strconv.FormatUint(postId, 10), "int"},
}, "comment_ID", "", models.SqlBuilder{
@ -47,29 +47,29 @@ func postComments(args ...any) ([]uint64, error) {
if err != nil {
return nil, err
}
return helper.SliceMap(r, func(t wp.WpComments) uint64 {
return helper.SliceMap(r, func(t wp.Comments) uint64 {
return t.CommentId
}), err
}
func GetCommentById(ctx context.Context, id uint64) (wp.WpComments, error) {
func GetCommentById(ctx context.Context, id uint64) (wp.Comments, error) {
return commentsCache.GetCache(ctx, id, time.Second, id)
}
func GetCommentByIds(ctx context.Context, ids []uint64) ([]wp.WpComments, error) {
func GetCommentByIds(ctx context.Context, ids []uint64) ([]wp.Comments, error) {
return commentsCache.GetCacheBatch(ctx, ids, time.Second, ids)
}
func getCommentByIds(args ...any) (map[uint64]wp.WpComments, error) {
func getCommentByIds(args ...any) (map[uint64]wp.Comments, error) {
ids := args[0].([]uint64)
m := make(map[uint64]wp.WpComments)
r, err := models.SimpleFind[wp.WpComments](models.SqlBuilder{
m := make(map[uint64]wp.Comments)
r, err := models.SimpleFind[wp.Comments](models.SqlBuilder{
{"comment_ID", "in", ""}, {"comment_approved", "1"},
}, "*", helper.SliceMap(ids, helper.ToAny[uint64]))
if err != nil {
return m, err
}
return helper.SimpleSliceToMap(r, func(t wp.WpComments) uint64 {
return helper.SimpleSliceToMap(r, func(t wp.Comments) uint64 {
return t.CommentId
}), err
}

View File

@ -15,17 +15,17 @@ import (
var postContextCache *cache.MapCache[uint64, PostContext]
var archivesCaches *Arch
var categoryCaches *cache.SliceCache[wp.WpTermsMy]
var recentPostsCaches *cache.SliceCache[wp.WpPosts]
var recentCommentsCaches *cache.SliceCache[wp.WpComments]
var recentPostsCaches *cache.SliceCache[wp.Posts]
var recentCommentsCaches *cache.SliceCache[wp.Comments]
var postCommentCaches *cache.MapCache[uint64, []uint64]
var postsCache *cache.MapCache[uint64, wp.WpPosts]
var postsCache *cache.MapCache[uint64, wp.Posts]
var monthPostsCache *cache.MapCache[string, []uint64]
var postListIdsCache *cache.MapCache[string, PostIds]
var searchPostIdsCache *cache.MapCache[string, PostIds]
var maxPostIdCache *cache.SliceCache[uint64]
var TotalRaw int
var usersCache *cache.MapCache[uint64, wp.WpUsers]
var commentsCache *cache.MapCache[uint64, wp.WpComments]
var usersCache *cache.MapCache[uint64, wp.Users]
var commentsCache *cache.MapCache[uint64, wp.Comments]
func InitActionsCommonCache() {
archivesCaches = &Arch{
@ -41,21 +41,21 @@ func InitActionsCommonCache() {
postContextCache = cache.NewMapCacheByFn[uint64, PostContext](getPostContext, config.Conf.ContextPostCacheTime)
postsCache = cache.NewMapCacheByBatchFn[uint64, wp.WpPosts](getPostsByIds, config.Conf.PostDataCacheTime)
postsCache = cache.NewMapCacheByBatchFn[uint64, wp.Posts](getPostsByIds, config.Conf.PostDataCacheTime)
categoryCaches = cache.NewSliceCache[wp.WpTermsMy](categories, config.Conf.CategoryCacheTime)
recentPostsCaches = cache.NewSliceCache[wp.WpPosts](recentPosts, config.Conf.RecentPostCacheTime)
recentPostsCaches = cache.NewSliceCache[wp.Posts](recentPosts, config.Conf.RecentPostCacheTime)
recentCommentsCaches = cache.NewSliceCache[wp.WpComments](recentComments, config.Conf.RecentCommentsCacheTime)
recentCommentsCaches = cache.NewSliceCache[wp.Comments](recentComments, config.Conf.RecentCommentsCacheTime)
postCommentCaches = cache.NewMapCacheByFn[uint64, []uint64](postComments, config.Conf.PostCommentsCacheTime)
maxPostIdCache = cache.NewSliceCache[uint64](getMaxPostId, config.Conf.MaxPostIdCacheTime)
usersCache = cache.NewMapCacheByBatchFn[uint64, wp.WpUsers](getUsers, config.Conf.UserInfoCacheTime)
usersCache = cache.NewMapCacheByBatchFn[uint64, wp.Users](getUsers, config.Conf.UserInfoCacheTime)
commentsCache = cache.NewMapCacheByBatchFn[uint64, wp.WpComments](getCommentByIds, config.Conf.CommentsCacheTime)
commentsCache = cache.NewMapCacheByBatchFn[uint64, wp.Comments](getCommentByIds, config.Conf.CommentsCacheTime)
}
func ClearCache() {
@ -99,8 +99,8 @@ func (c *Arch) getArchiveCache() []wp.PostArchive {
}
type PostContext struct {
prev wp.WpPosts
next wp.WpPosts
prev wp.Posts
next wp.Posts
}
func archives() ([]wp.PostArchive, error) {
@ -133,20 +133,20 @@ func categories(...any) (terms []wp.WpTermsMy, err error) {
if v, ok := wp.Terms[terms[i].WpTerms.TermId]; ok {
terms[i].WpTerms = v
}
if v, ok := wp.TermTaxonomy[terms[i].WpTerms.TermId]; ok {
terms[i].WpTermTaxonomy = v
if v, ok := wp.TermTaxonomies[terms[i].WpTerms.TermId]; ok {
terms[i].TermTaxonomy = v
}
}
return
}
func PasswordProjectTitle(post *wp.WpPosts) {
func PasswordProjectTitle(post *wp.Posts) {
if post.PostPassword != "" {
post.PostTitle = fmt.Sprintf("密码保护:%s", post.PostTitle)
}
}
func PasswdProjectContent(post *wp.WpPosts) {
func PasswdProjectContent(post *wp.Posts) {
if post.PostContent != "" {
format := `
<form action="/login" class="post-password-form" method="post">

View File

@ -13,15 +13,15 @@ import (
"time"
)
func GetPostById(ctx context.Context, id uint64) (wp.WpPosts, error) {
func GetPostById(ctx context.Context, id uint64) (wp.Posts, error) {
return postsCache.GetCache(ctx, id, time.Second, id)
}
func GetPostsByIds(ctx context.Context, ids []uint64) ([]wp.WpPosts, error) {
func GetPostsByIds(ctx context.Context, ids []uint64) ([]wp.Posts, error) {
return postsCache.GetCacheBatch(ctx, ids, time.Second, ids)
}
func SearchPost(ctx context.Context, key string, args ...any) (r []wp.WpPosts, total int, err error) {
func SearchPost(ctx context.Context, key string, args ...any) (r []wp.Posts, total int, err error) {
ids, err := searchPostIdsCache.GetCache(ctx, key, time.Second, args...)
if err != nil {
return
@ -31,11 +31,11 @@ func SearchPost(ctx context.Context, key string, args ...any) (r []wp.WpPosts, t
return
}
func getPostsByIds(ids ...any) (m map[uint64]wp.WpPosts, err error) {
m = make(map[uint64]wp.WpPosts)
func getPostsByIds(ids ...any) (m map[uint64]wp.Posts, err error) {
m = make(map[uint64]wp.Posts)
id := ids[0].([]uint64)
arg := helper.SliceMap(id, helper.ToAny[uint64])
rawPosts, err := models.Find[wp.WpPosts](models.SqlBuilder{{
rawPosts, err := models.Find[wp.Posts](models.SqlBuilder{{
"Id", "in", "",
}}, "a.*,ifnull(d.name,'') category_name,ifnull(taxonomy,'') `taxonomy`", "", nil, models.SqlBuilder{{
"a", "left join", "wp_term_relationships b", "a.Id=b.object_id",
@ -47,7 +47,7 @@ func getPostsByIds(ids ...any) (m map[uint64]wp.WpPosts, err error) {
if err != nil {
return m, err
}
postsMap := make(map[uint64]wp.WpPosts)
postsMap := make(map[uint64]wp.Posts)
for i, post := range rawPosts {
v, ok := postsMap[post.Id]
if !ok {
@ -80,7 +80,7 @@ func getPostsByIds(ids ...any) (m map[uint64]wp.WpPosts, err error) {
return
}
func PostLists(ctx context.Context, key string, args ...any) (r []wp.WpPosts, total int, err error) {
func PostLists(ctx context.Context, key string, args ...any) (r []wp.Posts, total int, err error) {
ids, err := postListIdsCache.GetCache(ctx, key, time.Second, args...)
if err != nil {
return
@ -98,7 +98,7 @@ func searchPostIds(args ...any) (ids PostIds, err error) {
join := args[4].(models.SqlBuilder)
postType := args[5].([]any)
postStatus := args[6].([]any)
res, total, err := models.SimplePagination[wp.WpPosts](where, "ID", "", page, limit, order, join, nil, postType, postStatus)
res, total, err := models.SimplePagination[wp.Posts](where, "ID", "", page, limit, order, join, nil, postType, postStatus)
for _, posts := range res {
ids.Ids = append(ids.Ids, posts.Id)
}
@ -110,7 +110,7 @@ func searchPostIds(args ...any) (ids PostIds, err error) {
}
func getMaxPostId(...any) ([]uint64, error) {
r, err := models.SimpleFind[wp.WpPosts](models.SqlBuilder{{"post_type", "post"}, {"post_status", "publish"}}, "max(ID) ID")
r, err := models.SimpleFind[wp.Posts](models.SqlBuilder{{"post_type", "post"}, {"post_status", "publish"}}, "max(ID) ID")
var id uint64
if len(r) > 0 {
id = r[0].Id
@ -123,7 +123,7 @@ func GetMaxPostId(ctx *gin.Context) (uint64, error) {
return Id[0], err
}
func RecentPosts(ctx context.Context, n int) (r []wp.WpPosts) {
func RecentPosts(ctx context.Context, n int) (r []wp.Posts) {
r, err := recentPostsCaches.GetCache(ctx, time.Second)
if n < len(r) {
r = r[:n]
@ -131,8 +131,8 @@ func RecentPosts(ctx context.Context, n int) (r []wp.WpPosts) {
logs.ErrPrintln(err, "get recent post")
return
}
func recentPosts(...any) (r []wp.WpPosts, err error) {
r, err = models.Find[wp.WpPosts](models.SqlBuilder{{
func recentPosts(...any) (r []wp.Posts, err error) {
r, err = models.Find[wp.Posts](models.SqlBuilder{{
"post_type", "post",
}, {"post_status", "publish"}}, "ID,post_title,post_password", "", models.SqlBuilder{{"post_date", "desc"}}, nil, nil, 10)
for i, post := range r {
@ -143,10 +143,10 @@ func recentPosts(...any) (r []wp.WpPosts, err error) {
return
}
func GetContextPost(ctx context.Context, id uint64, date time.Time) (prev, next wp.WpPosts, err error) {
func GetContextPost(ctx context.Context, id uint64, date time.Time) (prev, next wp.Posts, err error) {
postCtx, err := postContextCache.GetCache(ctx, id, time.Second, date)
if err != nil {
return wp.WpPosts{}, wp.WpPosts{}, err
return wp.Posts{}, wp.Posts{}, err
}
prev = postCtx.prev
next = postCtx.next
@ -155,7 +155,7 @@ func GetContextPost(ctx context.Context, id uint64, date time.Time) (prev, next
func getPostContext(arg ...any) (r PostContext, err error) {
t := arg[0].(time.Time)
next, err := models.FirstOne[wp.WpPosts](models.SqlBuilder{
next, err := models.FirstOne[wp.Posts](models.SqlBuilder{
{"post_date", ">", t.Format("2006-01-02 15:04:05")},
{"post_status", "in", ""},
{"post_type", "post"},
@ -166,7 +166,7 @@ func getPostContext(arg ...any) (r PostContext, err error) {
if err != nil {
return
}
prev, err := models.FirstOne[wp.WpPosts](models.SqlBuilder{
prev, err := models.FirstOne[wp.Posts](models.SqlBuilder{
{"post_date", "<", t.Format("2006-01-02 15:04:05")},
{"post_status", "in", ""},
{"post_type", "post"},
@ -184,7 +184,7 @@ func getPostContext(arg ...any) (r PostContext, err error) {
return
}
func GetMonthPostIds(ctx context.Context, year, month string, page, limit int, order string) (r []wp.WpPosts, total int, err error) {
func GetMonthPostIds(ctx context.Context, year, month string, page, limit int, order string) (r []wp.Posts, total int, err error) {
res, err := monthPostsCache.GetCache(ctx, fmt.Sprintf("%s%s", year, month), time.Second, year, month)
if err != nil {
return
@ -208,7 +208,7 @@ func monthPost(args ...any) (r []uint64, err error) {
}
postType := []any{"post"}
status := []any{"publish"}
ids, err := models.Find[wp.WpPosts](where, "ID", "", models.SqlBuilder{{"Id", "asc"}}, nil, nil, 0, postType, status)
ids, err := models.Find[wp.Posts](where, "ID", "", models.SqlBuilder{{"Id", "asc"}}, nil, nil, 0, postType, status)
if err != nil {
return
}

View File

@ -8,16 +8,16 @@ import (
"time"
)
func getUsers(...any) (m map[uint64]wp.WpUsers, err error) {
m = make(map[uint64]wp.WpUsers)
r, err := models.SimpleFind[wp.WpUsers](nil, "*")
func getUsers(...any) (m map[uint64]wp.Users, err error) {
m = make(map[uint64]wp.Users)
r, err := models.SimpleFind[wp.Users](nil, "*")
for _, user := range r {
m[user.Id] = user
}
return
}
func GetUser(ctx *gin.Context, uid uint64) wp.WpUsers {
func GetUser(ctx *gin.Context, uid uint64) wp.Users {
r, err := usersCache.GetCache(ctx, uid, time.Second, uid)
logs.ErrPrintln(err, "get user", uid)
return r

View File

@ -32,8 +32,8 @@ func Detail(c *gin.Context) {
categoryItems := common.Categories(c)
recentComments := common.RecentComments(c, 5)
var h = gin.H{
"title": wp.Options["blogname"],
"options": wp.Options,
"title": wp.Option["blogname"],
"options": wp.Option,
"recentPosts": recent,
"archives": archive,
"categories": categoryItems,
@ -81,11 +81,11 @@ func Detail(c *gin.Context) {
commentss := treeComments(comments)
prev, next, err := common.GetContextPost(c, post.Id, post.PostDate)
logs.ErrPrintln(err, "get pre and next post", post.Id, post.PostDate)
h["title"] = fmt.Sprintf("%s-%s", post.PostTitle, wp.Options["blogname"])
h["title"] = fmt.Sprintf("%s-%s", post.PostTitle, wp.Option["blogname"])
h["post"] = post
h["showComment"] = showComment
h["prev"] = prev
depth := wp.Options["thread_comments_depth"]
depth := wp.Option["thread_comments_depth"]
d, err := strconv.Atoi(depth)
if err != nil {
logs.ErrPrintln(err, "get comment depth")
@ -96,7 +96,7 @@ func Detail(c *gin.Context) {
}
type Comment struct {
wp.WpComments
wp.Comments
Children []*Comment
}
@ -131,7 +131,7 @@ func (d detailHandler) formatComment(comments Comments, depth, maxDepth int) (ht
p = "parent"
fl = true
}
s.WriteString(d.formatLi(comment.WpComments, depth, eo, p))
s.WriteString(d.formatLi(comment.Comments, depth, eo, p))
if fl {
depth++
s.WriteString(`<ol class="children">`)
@ -163,16 +163,16 @@ func findComments(comments Comments) Comments {
return r
}
func treeComments(comments []wp.WpComments) Comments {
func treeComments(comments []wp.Comments) Comments {
var r = map[uint64]*Comment{
0: {
WpComments: wp.WpComments{},
Comments: wp.Comments{},
},
}
var top []*Comment
for _, comment := range comments {
c := Comment{
WpComments: comment,
Comments: comment,
Children: []*Comment{},
}
r[comment.CommentId] = &c
@ -190,7 +190,7 @@ func treeComments(comments []wp.WpComments) Comments {
return top
}
func (d detailHandler) formatLi(comments wp.WpComments, depth int, eo, parent string) string {
func (d detailHandler) formatLi(comments wp.Comments, depth int, eo, parent string) string {
li := `
<li id="comment-{{CommentId}}" class="comment {{eo}} thread-even depth-{{Depth}} {{parent}}">
<article id="div-comment-{{CommentId}}" class="comment-body">
@ -262,7 +262,7 @@ func gravatar(c *gin.Context, email string) (u string) {
q := url.Values{}
q.Add("s", "112")
q.Add("d", "mm")
q.Add("r", strings.ToLower(wp.Options["avatar_rating"]))
q.Add("r", strings.ToLower(wp.Option["avatar_rating"]))
u = fmt.Sprintf("%s?%s", u, q.Encode())
return
}

View File

@ -25,14 +25,14 @@ var commentsFeedCache = cache.NewSliceCache(commentsFeed, time.Hour)
func InitFeed() {
templateRss = rss2.Rss2{
Title: wp.Options["blogname"],
AtomLink: fmt.Sprintf("%s/feed", wp.Options["home"]),
Link: wp.Options["siteurl"],
Description: wp.Options["blogdescription"],
Title: wp.Option["blogname"],
AtomLink: fmt.Sprintf("%s/feed", wp.Option["home"]),
Link: wp.Option["siteurl"],
Description: wp.Option["blogdescription"],
Language: "zh-CN",
UpdatePeriod: "hourly",
UpdateFrequency: 1,
Generator: wp.Options["home"],
Generator: wp.Option["home"],
}
}
@ -72,7 +72,7 @@ func Feed(c *gin.Context) {
func feed(arg ...any) (xml []string, err error) {
c := arg[0].(*gin.Context)
r := common.RecentPosts(c, 10)
ids := helper.SliceMap(r, func(t wp.WpPosts) uint64 {
ids := helper.SliceMap(r, func(t wp.Posts) uint64 {
return t.Id
})
posts, err := common.GetPostsByIds(c, ids)
@ -81,7 +81,7 @@ func feed(arg ...any) (xml []string, err error) {
}
rs := templateRss
rs.LastBuildDate = time.Now().Format(timeFormat)
rs.Items = helper.SliceMap(posts, func(t wp.WpPosts) rss2.Item {
rs.Items = helper.SliceMap(posts, func(t wp.Posts) rss2.Item {
desc := "无法提供摘要。这是一篇受保护的文章。"
common.PasswordProjectTitle(&t)
if t.PostPassword != "" {
@ -91,9 +91,9 @@ func feed(arg ...any) (xml []string, err error) {
}
l := ""
if t.CommentStatus == "open" && t.CommentCount > 0 {
l = fmt.Sprintf("%s/p/%d#comments", wp.Options["siteurl"], t.Id)
l = fmt.Sprintf("%s/p/%d#comments", wp.Option["siteurl"], t.Id)
} else if t.CommentStatus == "open" && t.CommentCount == 0 {
l = fmt.Sprintf("%s/p/%d#respond", wp.Options["siteurl"], t.Id)
l = fmt.Sprintf("%s/p/%d#respond", wp.Option["siteurl"], t.Id)
}
user := common.GetUser(c, t.PostAuthor)
@ -105,8 +105,8 @@ func feed(arg ...any) (xml []string, err error) {
Content: t.PostContent,
Category: strings.Join(t.Categories, "、"),
CommentLink: l,
CommentRss: fmt.Sprintf("%s/p/%d/feed", wp.Options["siteurl"], t.Id),
Link: fmt.Sprintf("%s/p/%d", wp.Options["siteurl"], t.Id),
CommentRss: fmt.Sprintf("%s/p/%d/feed", wp.Option["siteurl"], t.Id),
Link: fmt.Sprintf("%s/p/%d", wp.Option["siteurl"], t.Id),
Description: desc,
PubDate: t.PostDateGmt.Format(timeFormat),
}
@ -168,8 +168,8 @@ func postFeed(arg ...any) (x string, err error) {
rs := templateRss
rs.Title = fmt.Sprintf("《%s》的评论", post.PostTitle)
rs.AtomLink = fmt.Sprintf("%s/p/%d/feed", wp.Options["siteurl"], post.Id)
rs.Link = fmt.Sprintf("%s/p/%d", wp.Options["siteurl"], post.Id)
rs.AtomLink = fmt.Sprintf("%s/p/%d/feed", wp.Option["siteurl"], post.Id)
rs.Link = fmt.Sprintf("%s/p/%d", wp.Option["siteurl"], post.Id)
rs.LastBuildDate = time.Now().Format(timeFormat)
if post.PostPassword != "" {
if len(comments) > 0 {
@ -178,7 +178,7 @@ func postFeed(arg ...any) (x string, err error) {
rs.Items = []rss2.Item{
{
Title: fmt.Sprintf("评价者:%s", t.CommentAuthor),
Link: fmt.Sprintf("%s/p/%d#comment-%d", wp.Options["siteurl"], post.Id, t.CommentId),
Link: fmt.Sprintf("%s/p/%d#comment-%d", wp.Option["siteurl"], post.Id, t.CommentId),
Creator: t.CommentAuthor,
PubDate: t.CommentDateGmt.Format(timeFormat),
Guid: fmt.Sprintf("%s#comment-%d", post.Guid, t.CommentId),
@ -188,10 +188,10 @@ func postFeed(arg ...any) (x string, err error) {
}
}
} else {
rs.Items = helper.SliceMap(comments, func(t wp.WpComments) rss2.Item {
rs.Items = helper.SliceMap(comments, func(t wp.Comments) rss2.Item {
return rss2.Item{
Title: fmt.Sprintf("评价者:%s", t.CommentAuthor),
Link: fmt.Sprintf("%s/p/%d#comment-%d", wp.Options["siteurl"], post.Id, t.CommentId),
Link: fmt.Sprintf("%s/p/%d#comment-%d", wp.Option["siteurl"], post.Id, t.CommentId),
Creator: t.CommentAuthor,
PubDate: t.CommentDateGmt.Format(timeFormat),
Guid: fmt.Sprintf("%s#comment-%d", post.Guid, t.CommentId),
@ -223,16 +223,16 @@ func commentsFeed(args ...any) (r []string, err error) {
c := args[0].(*gin.Context)
commens := common.RecentComments(c, 10)
rs := templateRss
rs.Title = fmt.Sprintf("\"%s\"的评论", wp.Options["blogname"])
rs.Title = fmt.Sprintf("\"%s\"的评论", wp.Option["blogname"])
rs.LastBuildDate = time.Now().Format(timeFormat)
rs.AtomLink = fmt.Sprintf("%s/comments/feed", wp.Options["siteurl"])
com, err := common.GetCommentByIds(c, helper.SliceMap(commens, func(t wp.WpComments) uint64 {
rs.AtomLink = fmt.Sprintf("%s/comments/feed", wp.Option["siteurl"])
com, err := common.GetCommentByIds(c, helper.SliceMap(commens, func(t wp.Comments) uint64 {
return t.CommentId
}))
if nil != err {
return []string{}, err
}
rs.Items = helper.SliceMap(com, func(t wp.WpComments) rss2.Item {
rs.Items = helper.SliceMap(com, func(t wp.Comments) rss2.Item {
post, _ := common.GetPostById(c, t.CommentPostId)
common.PasswordProjectTitle(&post)
desc := "评论受保护:要查看请输入密码。"
@ -246,7 +246,7 @@ func commentsFeed(args ...any) (r []string, err error) {
}
return rss2.Item{
Title: fmt.Sprintf("%s对《%s》的评论", t.CommentAuthor, post.PostTitle),
Link: fmt.Sprintf("%s/p/%d#comment-%d", wp.Options["siteurl"], post.Id, t.CommentId),
Link: fmt.Sprintf("%s/p/%d#comment-%d", wp.Option["siteurl"], post.Id, t.CommentId),
Creator: t.CommentAuthor,
Description: desc,
PubDate: t.CommentDateGmt.Format(timeFormat),

View File

@ -40,7 +40,7 @@ type indexHandle struct {
}
func newIndexHandle(ctx *gin.Context) *indexHandle {
size := wp.Options["posts_per_page"]
size := wp.Option["posts_per_page"]
si, _ := strconv.Atoi(size)
return &indexHandle{
c: ctx,
@ -48,8 +48,8 @@ func newIndexHandle(ctx *gin.Context) *indexHandle {
page: 1,
pageSize: si,
paginationStep: 1,
titleL: wp.Options["blogname"],
titleR: wp.Options["blogdescription"],
titleL: wp.Option["blogname"],
titleR: wp.Option["blogdescription"],
where: models.SqlBuilder{
{"post_type", "in", ""},
{"post_status", "in", ""},
@ -93,7 +93,7 @@ func (h *indexHandle) parseParams() {
})
ss := fmt.Sprintf("%s年%s月", year, strings.TrimLeft(month, "0"))
h.header = fmt.Sprintf("月度归档: <span>%s</span>", ss)
h.setTitleLR(ss, wp.Options["blogname"])
h.setTitleLR(ss, wp.Option["blogname"])
h.scene = plugins.Archive
}
category := h.c.Param("category")
@ -120,7 +120,7 @@ func (h *indexHandle) parseParams() {
}, []string{
"left join", "wp_terms d", "c.term_id=d.term_id",
})
h.setTitleLR(category, wp.Options["blogname"])
h.setTitleLR(category, wp.Option["blogname"])
h.scene = plugins.Category
}
s := h.c.Query("s")
@ -133,7 +133,7 @@ func (h *indexHandle) parseParams() {
}, []string{"post_password", ""})
h.postType = append(h.postType, "page", "attachment")
h.header = fmt.Sprintf("%s的搜索结果", s)
h.setTitleLR(helper.StrJoin(`"`, s, `"`, "的搜索结果"), wp.Options["blogname"])
h.setTitleLR(helper.StrJoin(`"`, s, `"`, "的搜索结果"), wp.Option["blogname"])
h.search = s
h.scene = plugins.Search
}
@ -150,7 +150,7 @@ func (h *indexHandle) parseParams() {
h.page = 1
}
if h.page > 1 && (h.category != "" || h.search != "" || month != "") {
h.setTitleLR(fmt.Sprintf("%s-第%d页", h.titleL, h.page), wp.Options["blogname"])
h.setTitleLR(fmt.Sprintf("%s-第%d页", h.titleL, h.page), wp.Option["blogname"])
}
}
@ -167,7 +167,7 @@ func Index(c *gin.Context) {
categoryItems := common.Categories(c)
recentComments := common.RecentComments(c, 5)
ginH := gin.H{
"options": wp.Options,
"options": wp.Option,
"recentPosts": recent,
"archives": archive,
"categories": categoryItems,
@ -176,7 +176,7 @@ func Index(c *gin.Context) {
"title": h.getTitle(),
"recentComments": recentComments,
}
var postIds []wp.WpPosts
var postIds []wp.Posts
var totalRaw int
var err error
if c.Param("month") != "" {

View File

@ -33,7 +33,7 @@ func Login(c *gin.Context) {
c.Error(err)
return
}
cohash := fmt.Sprintf("wp-postpass_%s", helper.StringMd5(wp.Options["siteurl"]))
cohash := fmt.Sprintf("wp-postpass_%s", helper.StringMd5(wp.Option["siteurl"]))
c.SetCookie(cohash, pass, 24*3600, "/", "", false, false)
c.Redirect(http.StatusFound, ref)

View File

@ -43,7 +43,7 @@ func RecoverAndSendMail(w io.Writer) func(ctx *gin.Context) {
er := mail.SendMail(
[]string{config.Conf.Mail.User},
fmt.Sprintf("%s%s %s 发生错误", fmt.Sprintf(wp.Options["siteurl"]), c.FullPath(), time.Now().Format(time.RFC1123Z)), content)
fmt.Sprintf("%s%s %s 发生错误", fmt.Sprintf(wp.Option["siteurl"]), c.FullPath(), time.Now().Format(time.RFC1123Z)), content)
if er != nil {
logs.ErrPrintln(er, "recover send mail fail", fmt.Sprintf("%v", err))

274
models/query_test.go Normal file
View File

@ -0,0 +1,274 @@
package models
import (
"github/fthvgb1/wp-go/config"
"github/fthvgb1/wp-go/db"
"github/fthvgb1/wp-go/models/wp"
"reflect"
"testing"
)
func init() {
config.InitConfig("../config.yaml")
db.InitDb()
}
func TestFind(t *testing.T) {
type args struct {
where ParseWhere
fields string
group string
order SqlBuilder
join SqlBuilder
having SqlBuilder
limit int
in [][]any
}
tests := []struct {
name string
args args
wantR []wp.Posts
wantErr bool
}{
{},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotR, err := Find[wp.Posts](tt.args.where, tt.args.fields, tt.args.group, tt.args.order, tt.args.join, tt.args.having, tt.args.limit, tt.args.in...)
if (err != nil) != tt.wantErr {
t.Errorf("Find() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(gotR, tt.wantR) {
t.Errorf("Find() gotR = %v, want %v", gotR, tt.wantR)
}
})
}
}
func TestFindOneById(t *testing.T) {
type args struct {
id int
}
r, err := Get[wp.Posts]("select * from "+wp.Posts{}.Table()+" where ID=?", 1)
if err != nil {
panic(err)
}
tests := []struct {
name string
args args
want wp.Posts
wantErr bool
}{
{
name: "t1",
args: args{
1,
},
want: r,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := FindOneById[wp.Posts](tt.args.id)
if (err != nil) != tt.wantErr {
t.Errorf("FindOneById() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("FindOneById() got = %v, want %v", got, tt.want)
}
})
}
}
func TestFirstOne(t *testing.T) {
type args struct {
where ParseWhere
fields string
order SqlBuilder
in [][]any
}
r, err := Get[wp.Posts]("select * from " + wp.Posts{}.Table() + " where post_status='publish' order by ID desc")
if err != nil {
panic(err)
}
tests := []struct {
name string
args args
want wp.Posts
wantErr bool
}{
{
name: "t1",
args: args{
where: SqlBuilder{{"post_status", "publish"}},
fields: "*",
order: SqlBuilder{{"ID", "desc"}},
in: nil,
},
wantErr: false,
want: r,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := FirstOne[wp.Posts](tt.args.where, tt.args.fields, tt.args.order, tt.args.in...)
if (err != nil) != tt.wantErr {
t.Errorf("FirstOne() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("FirstOne() got = %v, want %v", got, tt.want)
}
})
}
}
func TestGet(t *testing.T) {
type args struct {
sql string
params []any
}
tests := []struct {
name string
args args
wantR wp.Posts
wantErr bool
}{
{},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotR, err := Get[wp.Posts](tt.args.sql, tt.args.params...)
if (err != nil) != tt.wantErr {
t.Errorf("Get() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(gotR, tt.wantR) {
t.Errorf("Get() gotR = %v, want %v", gotR, tt.wantR)
}
})
}
}
func TestLastOne(t *testing.T) {
type args struct {
where ParseWhere
fields string
in [][]any
}
tests := []struct {
name string
args args
want wp.Posts
wantErr bool
}{
{},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := LastOne[wp.Posts](tt.args.where, tt.args.fields, tt.args.in...)
if (err != nil) != tt.wantErr {
t.Errorf("LastOne() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("LastOne() got = %v, want %v", got, tt.want)
}
})
}
}
func TestSelect(t *testing.T) {
type args struct {
sql string
params []any
}
tests := []struct {
name string
args args
want []wp.Posts
wantErr bool
}{
{},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Select[wp.Posts](tt.args.sql, tt.args.params...)
if (err != nil) != tt.wantErr {
t.Errorf("Select() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Select() got = %v, want %v", got, tt.want)
}
})
}
}
func TestSimpleFind(t *testing.T) {
type args struct {
where ParseWhere
fields string
in [][]any
}
tests := []struct {
name string
args args
want []wp.Posts
wantErr bool
}{
{},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := SimpleFind[wp.Posts](tt.args.where, tt.args.fields, tt.args.in...)
if (err != nil) != tt.wantErr {
t.Errorf("SimpleFind() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("SimpleFind() got = %v, want %v", got, tt.want)
}
})
}
}
func TestSimplePagination(t *testing.T) {
type args struct {
where ParseWhere
fields string
group string
page int
pageSize int
order SqlBuilder
join SqlBuilder
having SqlBuilder
in [][]any
}
tests := []struct {
name string
args args
wantR []wp.Posts
wantTotal int
wantErr bool
}{
{},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotR, gotTotal, err := SimplePagination[wp.Posts](tt.args.where, tt.args.fields, tt.args.group, tt.args.page, tt.args.pageSize, tt.args.order, tt.args.join, tt.args.having, tt.args.in...)
if (err != nil) != tt.wantErr {
t.Errorf("SimplePagination() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(gotR, tt.wantR) {
t.Errorf("SimplePagination() gotR = %v, want %v", gotR, tt.wantR)
}
if gotTotal != tt.wantTotal {
t.Errorf("SimplePagination() gotTotal = %v, want %v", gotTotal, tt.wantTotal)
}
})
}
}

View File

@ -2,23 +2,23 @@ package wp
import "github/fthvgb1/wp-go/models"
var Options = make(map[string]string)
var Option = make(map[string]string)
var Terms = map[uint64]WpTerms{}
var TermTaxonomy = map[uint64]WpTermTaxonomy{}
var TermTaxonomies = map[uint64]TermTaxonomy{}
func InitOptions() error {
ops, err := models.SimpleFind[WpOptions](models.SqlBuilder{{"autoload", "yes"}}, "option_name, option_value")
ops, err := models.SimpleFind[Options](models.SqlBuilder{{"autoload", "yes"}}, "option_name, option_value")
if err != nil {
return err
}
if len(ops) == 0 {
ops, err = models.SimpleFind[WpOptions](nil, "option_name, option_value")
ops, err = models.SimpleFind[Options](nil, "option_name, option_value")
if err != nil {
return err
}
}
for _, options := range ops {
Options[options.OptionName] = options.OptionValue
Option[options.OptionName] = options.OptionValue
}
return nil
}
@ -31,12 +31,12 @@ func InitTerms() (err error) {
for _, wpTerms := range terms {
Terms[wpTerms.TermId] = wpTerms
}
termTax, err := models.SimpleFind[WpTermTaxonomy](nil, "*")
termTax, err := models.SimpleFind[TermTaxonomy](nil, "*")
if err != nil {
return err
}
for _, taxonomy := range termTax {
TermTaxonomy[taxonomy.TermTaxonomyId] = taxonomy
TermTaxonomies[taxonomy.TermTaxonomyId] = taxonomy
}
return
}

View File

@ -2,7 +2,7 @@ package wp
import "time"
type WpComments struct {
type Comments struct {
CommentId uint64 `gorm:"column:comment_ID" db:"comment_ID" json:"comment_ID" form:"comment_ID"`
CommentPostId uint64 `gorm:"column:comment_post_ID" db:"comment_post_ID" json:"comment_post_ID" form:"comment_post_ID"`
CommentAuthor string `gorm:"column:comment_author" db:"comment_author" json:"comment_author" form:"comment_author"`
@ -22,10 +22,10 @@ type WpComments struct {
PostTitle string `db:"post_title"`
}
func (w WpComments) PrimaryKey() string {
func (w Comments) PrimaryKey() string {
return "comment_ID"
}
func (w WpComments) Table() string {
func (w Comments) Table() string {
return "wp_comments"
}

View File

@ -1,16 +1,16 @@
package wp
type WpOptions struct {
type Options struct {
OptionId uint64 `gorm:"column:option_id" db:"option_id" json:"option_id" form:"option_id"`
OptionName string `gorm:"column:option_name" db:"option_name" json:"option_name" form:"option_name"`
OptionValue string `gorm:"column:option_value" db:"option_value" json:"option_value" form:"option_value"`
Autoload string `gorm:"column:autoload" db:"autoload" json:"autoload" form:"autoload"`
}
func (w WpOptions) PrimaryKey() string {
func (w Options) PrimaryKey() string {
return "option_id"
}
func (w WpOptions) Table() string {
func (w Options) Table() string {
return "wp_options"
}

View File

@ -2,7 +2,7 @@ package wp
import "time"
type WpPosts struct {
type Posts struct {
Id uint64 `gorm:"column:ID" db:"ID" json:"ID" form:"ID"`
PostAuthor uint64 `gorm:"column:post_author" db:"post_author" json:"post_author" form:"post_author"`
PostDate time.Time `gorm:"column:post_date" db:"post_date" json:"post_date" form:"post_date"`
@ -36,11 +36,11 @@ type WpPosts struct {
TagsHtml string
}
func (w WpPosts) PrimaryKey() string {
func (w Posts) PrimaryKey() string {
return "ID"
}
func (w WpPosts) Table() string {
func (w Posts) Table() string {
return "wp_posts"
}

View File

@ -1,6 +1,6 @@
package wp
type WpTermTaxonomy struct {
type TermTaxonomy struct {
TermTaxonomyId uint64 `gorm:"column:term_taxonomy_id" db:"term_taxonomy_id" json:"term_taxonomy_id" form:"term_taxonomy_id"`
TermId uint64 `gorm:"column:term_id" db:"term_id" json:"term_id" form:"term_id"`
Taxonomy string `gorm:"column:taxonomy" db:"taxonomy" json:"taxonomy" form:"taxonomy"`
@ -9,10 +9,10 @@ type WpTermTaxonomy struct {
Count int64 `gorm:"column:count" db:"count" json:"count" form:"count"`
}
func (w WpTermTaxonomy) PrimaryKey() string {
func (w TermTaxonomy) PrimaryKey() string {
return "term_taxonomy_id"
}
func (w WpTermTaxonomy) Table() string {
func (w TermTaxonomy) Table() string {
return "wp_term_taxonomy"
}

View File

@ -16,7 +16,7 @@ func (t WpTerms) Table() string {
type WpTermsMy struct {
WpTerms
WpTermTaxonomy
TermTaxonomy
}
func (t WpTermsMy) PrimaryKey() string {

View File

@ -2,7 +2,7 @@ package wp
import "time"
type WpUsers struct {
type Users struct {
Id uint64 `gorm:"column:ID" db:"ID" json:"ID"`
UserLogin string `gorm:"column:user_login" db:"user_login" json:"user_login"`
UserPass string `gorm:"column:user_pass" db:"user_pass" json:"user_pass"`
@ -15,10 +15,10 @@ type WpUsers struct {
DisplayName string `gorm:"column:display_name" db:"display_name" json:"display_name"`
}
func (u WpUsers) Table() string {
func (u Users) Table() string {
return "wp_users"
}
func (u WpUsers) PrimaryKey() string {
func (u Users) PrimaryKey() string {
return "ID"
}

View File

@ -116,7 +116,7 @@ func DigestRaw(str string, limit int, u string) string {
return content
}
func Digest(p *Plugin[wp.WpPosts], c *gin.Context, post *wp.WpPosts, scene uint) {
func Digest(p *Plugin[wp.Posts], c *gin.Context, post *wp.Posts, scene uint) {
if scene == Detail {
return
}

View File

@ -5,13 +5,13 @@ import (
"github/fthvgb1/wp-go/models/wp"
)
func NewPostPlugin(ctx *gin.Context, scene uint) *Plugin[wp.WpPosts] {
p := NewPlugin[wp.WpPosts](nil, -1, nil, scene, ctx)
func NewPostPlugin(ctx *gin.Context, scene uint) *Plugin[wp.Posts] {
p := NewPlugin[wp.Posts](nil, -1, nil, scene, ctx)
p.Push(Digest)
return p
}
func ApplyPlugin(p *Plugin[wp.WpPosts], post *wp.WpPosts) {
func ApplyPlugin(p *Plugin[wp.Posts], post *wp.Posts) {
p.post = post
p.Next()
p.index = -1