687 lines
19 KiB
Go
Raw Normal View History

2024-02-02 23:42:42 +08:00
package services
import (
"context"
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"time"
localCache "git.solsynth.dev/hypernet/interactive/pkg/internal/cache"
2024-11-02 13:41:51 +08:00
"git.solsynth.dev/hypernet/interactive/pkg/internal/gap"
"git.solsynth.dev/hypernet/nexus/pkg/proto"
pproto "git.solsynth.dev/hypernet/paperclip/pkg/proto"
"git.solsynth.dev/hypernet/passport/pkg/authkit"
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
"github.com/eko/gocache/lib/v4/cache"
"github.com/eko/gocache/lib/v4/marshaler"
"github.com/eko/gocache/lib/v4/store"
"gorm.io/datatypes"
2024-11-02 13:41:51 +08:00
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
2024-03-03 01:23:11 +08:00
"github.com/rs/zerolog/log"
2024-02-03 15:20:32 +08:00
"github.com/samber/lo"
2024-02-03 00:50:23 +08:00
"gorm.io/gorm"
2024-03-03 01:23:11 +08:00
)
func FilterPostWithUserContext(tx *gorm.DB, user *authm.Account) *gorm.DB {
2024-07-28 01:49:16 +08:00
if user == nil {
return tx.Where("visibility = ?", models.PostVisibilityAll)
}
2024-07-30 00:06:58 +08:00
const (
FriendsVisibility = models.PostVisibilityFriends
SelectedVisibility = models.PostVisibilitySelected
2024-08-18 01:06:52 +08:00
FilteredVisibility = models.PostVisibilityFiltered
2024-07-30 00:06:58 +08:00
NoneVisibility = models.PostVisibilityNone
2024-07-29 23:33:55 +08:00
)
2024-07-28 01:49:16 +08:00
type userContextState struct {
Allowlist []uint
InvisibleList []uint
}
cacheManager := cache.New[any](localCache.S)
marshal := marshaler.New(cacheManager)
ctx := context.Background()
var allowlist, invisibleList []uint
2024-08-18 01:06:52 +08:00
statusCacheKey := fmt.Sprintf("post-user-context-query#%d", user.ID)
statusCache, err := marshal.Get(ctx, statusCacheKey, new(userContextState))
if err == nil {
state := statusCache.(*userContextState)
allowlist = state.Allowlist
invisibleList = state.InvisibleList
} else {
userFriends, _ := authkit.ListRelative(gap.Nx, user.ID, int32(authm.RelationshipFriend), true)
userGotBlocked, _ := authkit.ListRelative(gap.Nx, user.ID, int32(authm.RelationshipBlocked), true)
userBlocked, _ := authkit.ListRelative(gap.Nx, user.ID, int32(authm.RelationshipBlocked), false)
userFriendList := lo.Map(userFriends, func(item *proto.UserInfo, index int) uint {
return uint(item.GetId())
})
userGotBlockList := lo.Map(userGotBlocked, func(item *proto.UserInfo, index int) uint {
return uint(item.GetId())
})
userBlocklist := lo.Map(userBlocked, func(item *proto.UserInfo, index int) uint {
return uint(item.GetId())
})
// Query the publishers according to the user's relationship
var publishers []models.Publisher
database.C.Where(
2025-02-15 18:02:12 +08:00
"account_id IN ? AND type = ?",
lo.Uniq(append(append(userFriendList, userGotBlockList...), userBlocklist...)),
models.PublisherTypePersonal,
).Find(&publishers)
allowlist = lo.Map(lo.Filter(publishers, func(item models.Publisher, index int) bool {
if item.AccountID == nil {
return false
}
return lo.Contains(userFriendList, *item.AccountID)
}), func(item models.Publisher, index int) uint {
return item.ID
})
invisibleList = lo.Map(lo.Filter(publishers, func(item models.Publisher, index int) bool {
if item.AccountID == nil {
return false
}
return lo.Contains(userBlocklist, *item.AccountID)
}), func(item models.Publisher, index int) uint {
return item.ID
})
_ = marshal.Set(
ctx,
statusCacheKey,
userContextState{
Allowlist: allowlist,
InvisibleList: invisibleList,
},
store.WithExpiration(5*time.Minute),
store.WithTags([]string{"post-user-context-query", fmt.Sprintf("user#%d", user.ID)}),
)
}
2024-08-10 17:18:55 +08:00
tx = tx.Where(
"publisher_id = ? OR visibility != ? OR "+
2025-02-15 18:02:12 +08:00
"(visibility = ? AND publisher_id IN ?) OR "+
"(visibility = ? AND ?) OR "+
"(visibility = ? AND NOT ?)",
user.ID,
2024-08-10 17:18:55 +08:00
NoneVisibility,
2025-02-15 18:02:12 +08:00
FriendsVisibility,
allowlist,
2024-08-10 17:18:55 +08:00
SelectedVisibility,
datatypes.JSONQuery("visible_users").HasKey(strconv.Itoa(int(user.ID))),
2024-08-18 01:06:52 +08:00
FilteredVisibility,
2024-08-10 17:18:55 +08:00
datatypes.JSONQuery("invisible_users").HasKey(strconv.Itoa(int(user.ID))),
)
2024-07-30 00:06:58 +08:00
if len(invisibleList) > 0 {
tx = tx.Where("publisher_id NOT IN ?", invisibleList)
}
2024-07-28 01:49:16 +08:00
return tx
}
2024-05-15 19:45:49 +08:00
func FilterPostWithCategory(tx *gorm.DB, alias string) *gorm.DB {
2024-12-22 15:49:02 +08:00
aliases := strings.Split(alias, ",")
return tx.Joins("JOIN post_categories ON posts.id = post_categories.post_id").
Joins("JOIN categories ON categories.id = post_categories.category_id").
2024-12-22 15:49:02 +08:00
Where("categories.alias IN ?", aliases).
Group("posts.id").
Having("COUNT(DISTINCT categories.id) = ?", len(aliases))
}
2024-05-15 19:45:49 +08:00
func FilterPostWithTag(tx *gorm.DB, alias string) *gorm.DB {
aliases := strings.Split(alias, ",")
return tx.Joins("JOIN post_tags ON posts.id = post_tags.post_id").
Joins("JOIN tags ON tags.id = post_tags.tag_id").
Where("tags.alias IN ?", aliases).
Group("posts.id").
Having("COUNT(DISTINCT tags.id) = ?", len(aliases))
}
2024-12-01 22:51:56 +08:00
func FilterPostWithType(tx *gorm.DB, t string) *gorm.DB {
return tx.Where("type = ?", t)
}
2024-05-15 19:45:49 +08:00
func FilterPostReply(tx *gorm.DB, replyTo ...uint) *gorm.DB {
if len(replyTo) > 0 && replyTo[0] > 0 {
return tx.Where("reply_id = ?", replyTo[0])
2024-03-03 01:23:11 +08:00
} else {
2024-05-15 19:45:49 +08:00
return tx.Where("reply_id IS NULL")
}
2024-03-03 01:23:11 +08:00
}
2024-05-15 19:45:49 +08:00
func FilterPostWithPublishedAt(tx *gorm.DB, date time.Time) *gorm.DB {
2024-07-22 01:44:04 +08:00
return tx.
Where("published_at <= ? OR published_at IS NULL", date).
Where("published_until > ? OR published_until IS NULL", date)
2024-03-03 01:23:11 +08:00
}
func FilterPostWithAuthorDraft(tx *gorm.DB, uid uint) *gorm.DB {
2024-11-02 23:47:44 +08:00
return tx.Where("publisher_id = ? AND is_draft = ?", uid, true)
}
func FilterPostDraft(tx *gorm.DB) *gorm.DB {
return tx.Where("is_draft = ? OR is_draft IS NULL", false)
}
2024-10-13 21:25:15 +08:00
func FilterPostWithFuzzySearch(tx *gorm.DB, probe string) *gorm.DB {
if len(probe) == 0 {
return tx
}
2024-10-13 21:25:15 +08:00
probe = "%" + probe + "%"
return tx.
Where("? AND body->>'content' ILIKE ?", gorm.Expr("body ? 'content'"), probe).
Or("? AND body->>'title' ILIKE ?", gorm.Expr("body ? 'title'"), probe).
Or("? AND body->>'description' ILIKE ?", gorm.Expr("body ? 'description'"), probe)
2024-10-13 21:25:15 +08:00
}
2024-07-23 16:12:19 +08:00
func PreloadGeneral(tx *gorm.DB) *gorm.DB {
return tx.
Preload("Tags").
Preload("Categories").
2024-11-09 00:47:19 +08:00
Preload("Publisher").
Preload("ReplyTo").
2024-11-09 00:47:19 +08:00
Preload("ReplyTo.Publisher").
Preload("ReplyTo.Tags").
Preload("ReplyTo.Categories").
Preload("RepostTo").
2024-11-09 00:47:19 +08:00
Preload("RepostTo.Publisher").
Preload("RepostTo.Tags").
2024-07-23 16:12:19 +08:00
Preload("RepostTo.Categories")
}
func GetPost(tx *gorm.DB, id uint, ignoreLimitation ...bool) (models.Post, error) {
if len(ignoreLimitation) == 0 || !ignoreLimitation[0] {
tx = FilterPostWithPublishedAt(tx, time.Now())
}
var item models.Post
if err := PreloadGeneral(tx).
Where("id = ?", id).
2024-05-15 19:45:49 +08:00
First(&item).Error; err != nil {
2024-03-10 23:35:38 +08:00
return item, err
}
2024-03-03 01:23:11 +08:00
return item, nil
}
func GetPostByAlias(tx *gorm.DB, alias, area string, ignoreLimitation ...bool) (models.Post, error) {
if len(ignoreLimitation) == 0 || !ignoreLimitation[0] {
tx = FilterPostWithPublishedAt(tx, time.Now())
}
var item models.Post
if err := PreloadGeneral(tx).
Where("alias = ?", alias).
2024-12-20 23:56:56 +08:00
Where("alias_prefix = ?", area).
First(&item).Error; err != nil {
return item, err
}
return item, nil
}
2024-05-15 19:45:49 +08:00
func CountPost(tx *gorm.DB) (int64, error) {
2024-03-03 01:23:11 +08:00
var count int64
2024-05-15 19:45:49 +08:00
if err := tx.Model(&models.Post{}).Count(&count).Error; err != nil {
2024-03-03 01:23:11 +08:00
return count, err
}
return count, nil
}
2024-05-15 19:45:49 +08:00
func CountPostReply(id uint) int64 {
var count int64
2024-05-15 19:45:49 +08:00
if err := database.C.Model(&models.Post{}).
Where("reply_id = ?", id).
Count(&count).Error; err != nil {
return 0
}
return count
}
2024-05-15 19:45:49 +08:00
func CountPostReactions(id uint) int64 {
var count int64
if err := database.C.Model(&models.Reaction{}).
2024-05-15 19:45:49 +08:00
Where("post_id = ?", id).
Count(&count).Error; err != nil {
return 0
}
return count
}
2024-07-23 16:12:19 +08:00
func ListPost(tx *gorm.DB, take int, offset int, order any, noReact ...bool) ([]*models.Post, error) {
2024-07-16 16:52:00 +08:00
if take > 100 {
take = 100
2024-02-12 12:32:37 +08:00
}
var items []*models.Post
2024-07-23 16:12:19 +08:00
if err := PreloadGeneral(tx).
2024-05-15 19:45:49 +08:00
Limit(take).Offset(offset).
2024-07-23 16:12:19 +08:00
Order(order).
2024-05-15 19:45:49 +08:00
Find(&items).Error; err != nil {
2024-03-03 01:23:11 +08:00
return items, err
2024-02-03 15:20:32 +08:00
}
idx := lo.Map(items, func(item *models.Post, index int) uint {
return item.ID
2024-03-03 22:57:17 +08:00
})
// Load reactions
2024-03-03 22:57:17 +08:00
if len(noReact) <= 0 || !noReact[0] {
if mapping, err := BatchListPostReactions(database.C.Where("post_id IN ?", idx), "post_id"); err != nil {
2024-03-03 22:57:17 +08:00
return items, err
} else {
itemMap := lo.SliceToMap(items, func(item *models.Post) (uint, *models.Post) {
return item.ID, item
})
for k, v := range mapping {
if post, ok := itemMap[k]; ok {
2024-07-16 16:52:00 +08:00
post.Metric = models.PostMetric{
ReactionList: v,
}
}
2024-03-03 22:57:17 +08:00
}
}
}
// Load replies
if len(noReact) <= 0 || !noReact[0] {
var replies []struct {
PostID uint
Count int64
}
if err := database.C.Model(&models.Post{}).
2024-08-02 04:53:25 +08:00
Select("reply_id as post_id, COUNT(id) as count").
Where("reply_id IN (?)", idx).
Group("post_id").
Scan(&replies).Error; err != nil {
return items, err
}
itemMap := lo.SliceToMap(items, func(item *models.Post) (uint, *models.Post) {
return item.ID, item
})
list := map[uint]int64{}
for _, info := range replies {
list[info.PostID] = info.Count
}
for k, v := range list {
if post, ok := itemMap[k]; ok {
2024-07-16 16:52:00 +08:00
post.Metric = models.PostMetric{
ReactionList: post.Metric.ReactionList,
ReplyCount: v,
}
}
}
}
2024-03-03 01:23:11 +08:00
return items, nil
2024-02-03 15:20:32 +08:00
}
2024-08-10 21:11:55 +08:00
func ListPostMinimal(tx *gorm.DB, take int, offset int, order any) ([]*models.Post, error) {
if take > 500 {
take = 500
}
var items []*models.Post
if err := tx.
Limit(take).Offset(offset).
Order(order).
Find(&items).Error; err != nil {
return items, err
}
return items, nil
}
func EnsurePostCategoriesAndTags(item models.Post) (models.Post, error) {
2024-02-02 23:42:42 +08:00
var err error
2024-05-15 19:45:49 +08:00
for idx, category := range item.Categories {
item.Categories[idx], err = GetCategory(category.Alias)
2024-02-02 23:42:42 +08:00
if err != nil {
2024-03-03 01:23:11 +08:00
return item, err
2024-02-02 23:42:42 +08:00
}
}
2024-05-15 19:45:49 +08:00
for idx, tag := range item.Tags {
item.Tags[idx], err = GetTagOrCreate(tag.Alias, tag.Name)
2024-02-02 23:42:42 +08:00
if err != nil {
2024-03-03 01:23:11 +08:00
return item, err
2024-02-02 23:42:42 +08:00
}
}
2024-03-03 01:23:11 +08:00
return item, nil
}
func NewPost(user models.Publisher, item models.Post) (models.Post, error) {
if item.Alias != nil && len(*item.Alias) == 0 {
item.Alias = nil
}
2024-12-22 23:34:53 +08:00
if item.PublishedAt != nil && item.PublishedAt.UTC().Unix() < time.Now().UTC().Unix() {
return item, fmt.Errorf("post cannot be published before now")
}
2024-08-17 22:25:11 +08:00
if item.Alias != nil {
re := regexp.MustCompile(`^[a-z0-9.-]+$`)
if !re.MatchString(*item.Alias) {
return item, fmt.Errorf("invalid post alias, learn more about alias rule on our wiki")
}
}
if item.Realm != nil {
item.AliasPrefix = &item.Realm.Alias
} else {
item.AliasPrefix = &user.Name
}
log.Debug().Any("body", item.Body).Msg("Posting a post...")
start := time.Now()
log.Debug().Any("tags", item.Tags).Any("categories", item.Categories).Msg("Preparing categories and tags...")
item, err := EnsurePostCategoriesAndTags(item)
2024-03-03 01:23:11 +08:00
if err != nil {
return item, err
}
2024-02-02 23:42:42 +08:00
log.Debug().Msg("Saving post record into database...")
2024-03-03 01:23:11 +08:00
if err := database.C.Save(&item).Error; err != nil {
return item, err
2024-02-04 01:08:31 +08:00
}
item.Publisher = user
_ = updatePostAttachmentVisibility(item)
2024-05-15 19:45:49 +08:00
// Notify the original poster its post has been replied
if item.ReplyID != nil {
content, ok := item.Body["content"].(string)
if !ok {
content = "Posted a post"
} else {
content = TruncatePostContentShort(content)
}
var op models.Post
if err := database.C.
Where("id = ?", item.ReplyID).
2024-11-09 00:47:19 +08:00
Preload("Publisher").
First(&op).Error; err == nil {
if op.Publisher.AccountID != nil && op.Publisher.ID != user.ID {
log.Debug().Uint("user", *op.Publisher.AccountID).Msg("Notifying the original poster their post got replied...")
2024-07-16 10:53:02 +08:00
err = NotifyPosterAccount(
op.Publisher,
item,
2024-07-16 10:53:02 +08:00
"Post got replied",
fmt.Sprintf("%s (%s) replied you: %s", user.Nick, user.Name, content),
"interactive.feedback",
fmt.Sprintf("%s replied your post #%d", user.Nick, *item.ReplyID),
)
if err != nil {
log.Error().Err(err).Msg("An error occurred when notifying user...")
2024-03-03 01:23:11 +08:00
}
}
}
2024-02-02 23:42:42 +08:00
}
2024-09-17 00:35:42 +08:00
// Notify the subscriptions
if item.ReplyID == nil {
content, ok := item.Body["content"].(string)
if !ok {
content = "Posted a post"
}
2024-09-17 00:35:42 +08:00
var title *string
title, _ = item.Body["title"].(*string)
go func() {
item.Publisher = user
if err := NotifyUserSubscription(user, item, content, title); err != nil {
2024-09-17 00:35:42 +08:00
log.Error().Err(err).Msg("An error occurred when notifying subscriptions user by user...")
}
for _, tag := range item.Tags {
if err := NotifyTagSubscription(tag, user, item, content, title); err != nil {
2024-09-17 00:35:42 +08:00
log.Error().Err(err).Msg("An error occurred when notifying subscriptions user by tag...")
}
}
for _, category := range item.Categories {
if err := NotifyCategorySubscription(category, user, item, content, title); err != nil {
2024-09-17 00:35:42 +08:00
log.Error().Err(err).Msg("An error occurred when notifying subscriptions user by category...")
}
}
}()
}
log.Debug().Dur("elapsed", time.Since(start)).Msg("The post is posted.")
2024-03-03 01:23:11 +08:00
return item, nil
2024-02-02 23:42:42 +08:00
}
2024-02-03 00:50:23 +08:00
2024-05-15 19:45:49 +08:00
func EditPost(item models.Post) (models.Post, error) {
if _, ok := item.Body["content_truncated"]; ok {
return item, fmt.Errorf("prevented from editing post with truncated content")
}
if item.Alias != nil && len(*item.Alias) == 0 {
item.Alias = nil
}
2024-08-17 22:25:11 +08:00
if item.Alias != nil {
re := regexp.MustCompile(`^[a-z0-9.-]+$`)
if !re.MatchString(*item.Alias) {
return item, fmt.Errorf("invalid post alias, learn more about alias rule on our wiki")
}
}
if item.Realm != nil {
item.AliasPrefix = &item.Realm.Alias
} else {
item.AliasPrefix = &item.Publisher.Name
}
item, err := EnsurePostCategoriesAndTags(item)
2024-03-03 01:23:11 +08:00
if err != nil {
return item, err
2024-02-04 01:08:31 +08:00
}
_ = database.C.Model(&item).Association("Categories").Replace(item.Categories)
_ = database.C.Model(&item).Association("Tags").Replace(item.Tags)
pub := item.Publisher
2024-03-03 01:23:11 +08:00
err = database.C.Save(&item).Error
2024-02-04 01:08:31 +08:00
if err == nil {
item.Publisher = pub
_ = updatePostAttachmentVisibility(item)
}
2024-03-03 01:23:11 +08:00
return item, err
}
2024-02-04 01:08:31 +08:00
func updatePostAttachmentVisibility(item models.Post) error {
log.Debug().Any("attachments", item.Body["attachments"]).Msg("Updating post attachments visibility...")
if item.Publisher.AccountID == nil {
log.Warn().Msg("Post publisher did not have account id, skip updating attachments visibility...")
return nil
}
if val, ok := item.Body["attachments"].([]any); ok && len(val) > 0 {
conn, err := gap.Nx.GetClientGrpcConn("uc")
if err != nil {
log.Error().Err(err).Msg("An error occurred when getting grpc connection to Paperclip...")
return nil
}
pc := pproto.NewAttachmentServiceClient(conn)
2025-01-27 00:31:15 +08:00
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
resp, err := pc.UpdateVisibility(ctx, &pproto.UpdateVisibilityRequest{
Rid: lo.Map(val, func(item any, _ int) string {
return item.(string)
}),
UserId: lo.ToPtr(uint64(*item.Publisher.AccountID)),
IsIndexable: item.Visibility == models.PostVisibilityAll,
})
if err != nil {
log.Error().Any("attachments", val).Err(err).Msg("An error occurred when updating post attachment visibility...")
return err
}
2025-01-27 00:31:15 +08:00
log.Debug().Any("attachments", val).Int32("count", resp.Count).Msg("Post attachment visibility updated.")
} else {
log.Debug().Any("attachments", val).Msg("Post attachment visibility update skipped...")
}
return nil
}
2024-05-15 19:45:49 +08:00
func DeletePost(item models.Post) error {
if err := database.C.Delete(&item).Error; err != nil {
return err
}
// Cleaning up related attachments
if val, ok := item.Body["attachments"].([]string); ok && len(val) > 0 {
if item.Publisher.AccountID == nil {
return nil
}
conn, err := gap.Nx.GetClientGrpcConn("uc")
if err != nil {
return nil
}
pc := pproto.NewAttachmentServiceClient(conn)
_, err = pc.DeleteAttachment(context.Background(), &pproto.DeleteAttachmentRequest{
Rid: lo.Map(val, func(item string, _ int) string {
return item
}),
UserId: lo.ToPtr(uint64(*item.Publisher.AccountID)),
})
if err != nil {
log.Error().Err(err).Msg("An error occurred when deleting post attachment...")
}
}
return nil
2024-02-04 01:08:31 +08:00
}
func ReactPost(user authm.Account, reaction models.Reaction) (bool, models.Reaction, error) {
2024-07-23 16:12:19 +08:00
var op models.Post
if err := database.C.
Where("id = ?", reaction.PostID).
2024-11-09 00:47:19 +08:00
Preload("Publisher").
2024-07-23 16:12:19 +08:00
First(&op).Error; err != nil {
return true, reaction, err
}
if err := database.C.Where(reaction).First(&reaction).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
if op.Publisher.AccountID != nil && *op.Publisher.AccountID != user.ID {
2024-07-23 16:12:19 +08:00
err = NotifyPosterAccount(
op.Publisher,
op,
2024-07-23 16:12:19 +08:00
"Post got reacted",
fmt.Sprintf("%s (%s) reacted your post a %s.", user.Nick, user.Name, reaction.Symbol),
2024-12-08 21:04:13 +08:00
"interactive.feedback",
fmt.Sprintf("%s reacted you", user.Nick),
2024-07-23 16:12:19 +08:00
)
if err != nil {
log.Error().Err(err).Msg("An error occurred when notifying user...")
}
}
2024-07-23 16:12:19 +08:00
err = database.C.Save(&reaction).Error
if err == nil && reaction.Attitude != models.AttitudeNeutral {
_ = ModifyPosterVoteCount(op.Publisher, reaction.Attitude == models.AttitudePositive, 1)
if reaction.Attitude == models.AttitudePositive {
op.TotalUpvote++
database.C.Model(&op).Update("total_upvote", op.TotalUpvote)
} else {
op.TotalDownvote++
database.C.Model(&op).Update("total_downvote", op.TotalDownvote)
}
2024-07-23 16:12:19 +08:00
}
return true, reaction, err
} else {
return true, reaction, err
}
2024-02-03 00:50:23 +08:00
} else {
2024-07-23 16:12:19 +08:00
err = database.C.Delete(&reaction).Error
if err == nil && reaction.Attitude != models.AttitudeNeutral {
_ = ModifyPosterVoteCount(op.Publisher, reaction.Attitude == models.AttitudePositive, -1)
if reaction.Attitude == models.AttitudePositive {
op.TotalUpvote--
database.C.Model(&op).Update("total_upvote", op.TotalUpvote)
} else {
op.TotalDownvote--
database.C.Model(&op).Update("total_downvote", op.TotalDownvote)
}
2024-07-23 16:12:19 +08:00
}
return false, reaction, err
2024-02-03 00:50:23 +08:00
}
}
2024-07-25 22:58:47 +08:00
func PinPost(post models.Post) (bool, error) {
if post.PinnedAt != nil {
post.PinnedAt = nil
} else {
post.PinnedAt = lo.ToPtr(time.Now())
}
if err := database.C.Model(&post).Update("pinned_at", post.PinnedAt).Error; err != nil {
2024-07-25 22:58:47 +08:00
return post.PinnedAt != nil, err
}
return post.PinnedAt != nil, nil
}
const TruncatePostContentThreshold = 160
func TruncatePostContent(post models.Post) models.Post {
if post.Body["content"] != nil {
2024-10-13 20:32:32 +08:00
if val, ok := post.Body["content"].(string); ok {
length := TruncatePostContentThreshold
2024-11-25 00:33:57 +08:00
post.Body["content_length"] = len([]rune(val))
2024-10-13 20:32:32 +08:00
if len([]rune(val)) >= length {
post.Body["content"] = string([]rune(val)[:length]) + "..."
post.Body["content_truncated"] = true
}
}
}
if post.RepostTo != nil {
post.RepostTo = lo.ToPtr(TruncatePostContent(*post.RepostTo))
}
if post.ReplyTo != nil {
post.ReplyTo = lo.ToPtr(TruncatePostContent(*post.ReplyTo))
}
return post
}
2024-10-14 21:40:28 +08:00
const TruncatePostContentShortThreshold = 80
func TruncatePostContentShort(content string) string {
length := TruncatePostContentShortThreshold
if len([]rune(content)) >= length {
return string([]rune(content)[:length]) + "..."
} else {
return content
}
}