2023-01-12 12:42:16 +00:00
|
|
|
package plugins
|
|
|
|
|
|
|
|
import (
|
2023-02-02 11:16:18 +00:00
|
|
|
"context"
|
2023-01-12 12:42:16 +00:00
|
|
|
"fmt"
|
2023-01-18 15:02:59 +00:00
|
|
|
"github.com/fthvgb1/wp-go/cache"
|
|
|
|
"github.com/fthvgb1/wp-go/internal/pkg/config"
|
|
|
|
"github.com/fthvgb1/wp-go/internal/pkg/models"
|
|
|
|
"github.com/fthvgb1/wp-go/plugin/digest"
|
2023-01-12 12:42:16 +00:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
var digestCache *cache.MapCache[uint64, string]
|
2023-02-02 11:16:18 +00:00
|
|
|
var ctx context.Context
|
2023-01-12 12:42:16 +00:00
|
|
|
|
|
|
|
func InitDigestCache() {
|
2023-02-02 11:16:18 +00:00
|
|
|
ctx = context.Background()
|
2023-02-05 13:06:04 +00:00
|
|
|
digestCache = cache.NewMemoryMapCacheByFn[uint64](digestRaw, config.GetConfig().CacheTime.DigestCacheTime)
|
2023-01-12 12:42:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func ClearDigestCache() {
|
2023-02-02 11:16:18 +00:00
|
|
|
digestCache.ClearExpired(ctx)
|
2023-01-12 12:42:16 +00:00
|
|
|
}
|
|
|
|
func FlushCache() {
|
2023-02-02 11:16:18 +00:00
|
|
|
digestCache.Flush(ctx)
|
2023-01-12 12:42:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func digestRaw(arg ...any) (string, error) {
|
|
|
|
str := arg[0].(string)
|
|
|
|
id := arg[1].(uint64)
|
2023-02-05 13:06:04 +00:00
|
|
|
limit := config.GetConfig().DigestWordCount
|
2023-01-12 12:42:16 +00:00
|
|
|
if limit < 0 {
|
|
|
|
return str, nil
|
|
|
|
} else if limit == 0 {
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
return digest.Raw(str, limit, fmt.Sprintf("/p/%d", id)), nil
|
|
|
|
}
|
|
|
|
|
2023-01-21 13:13:33 +00:00
|
|
|
func Digest(p *Plugin[models.Posts], c *gin.Context, post *models.Posts, scene int) {
|
2023-01-12 12:42:16 +00:00
|
|
|
if scene == Detail {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if post.PostExcerpt != "" {
|
|
|
|
post.PostContent = strings.Replace(post.PostExcerpt, "\n", "<br/>", -1)
|
|
|
|
} else {
|
|
|
|
post.PostContent = DigestCache(c, post.Id, post.PostContent)
|
|
|
|
|
|
|
|
}
|
|
|
|
p.Next()
|
|
|
|
}
|
|
|
|
|
|
|
|
func DigestCache(ctx *gin.Context, id uint64, str string) string {
|
|
|
|
content, _ := digestCache.GetCache(ctx, id, time.Second, str, id)
|
|
|
|
return content
|
|
|
|
}
|