Interactive/pkg/services/posts.go

351 lines
9.8 KiB
Go
Raw Normal View History

2024-02-02 15:42:42 +00:00
package services
import (
2024-02-02 16:50:23 +00:00
"errors"
2024-02-03 07:20:32 +00:00
"fmt"
2024-02-14 14:03:45 +00:00
"time"
"github.com/gofiber/fiber/v2"
"github.com/rs/zerolog/log"
2024-02-03 16:24:04 +00:00
"code.smartsheep.studio/hydrogen/interactive/pkg/database"
"code.smartsheep.studio/hydrogen/interactive/pkg/models"
2024-02-03 07:20:32 +00:00
"github.com/samber/lo"
"github.com/spf13/viper"
2024-02-02 16:50:23 +00:00
"gorm.io/gorm"
2024-02-02 15:42:42 +00:00
)
2024-02-05 07:51:31 +00:00
func PreloadRelatedPost(tx *gorm.DB) *gorm.DB {
return tx.
2024-02-03 07:20:32 +00:00
Preload("Author").
2024-02-04 10:40:20 +00:00
Preload("Attachments").
Preload("Categories").
Preload("Tags").
2024-02-03 16:24:04 +00:00
Preload("RepostTo").
Preload("ReplyTo").
Preload("RepostTo.Author").
Preload("ReplyTo.Author").
2024-02-04 10:40:20 +00:00
Preload("RepostTo.Attachments").
Preload("ReplyTo.Attachments").
Preload("RepostTo.Categories").
Preload("ReplyTo.Categories").
Preload("RepostTo.Tags").
2024-02-05 07:51:31 +00:00
Preload("ReplyTo.Tags")
}
func FilterPostWithCategory(tx *gorm.DB, alias string) *gorm.DB {
prefix := viper.GetString("database.prefix")
return tx.Joins(fmt.Sprintf("JOIN %spost_categories ON %sposts.id = %spost_categories.post_id", prefix, prefix, prefix)).
Joins(fmt.Sprintf("JOIN %scategories ON %scategories.id = %spost_categories.category_id", prefix, prefix, prefix)).
Where(fmt.Sprintf("%scategories.alias = ?", prefix), alias)
}
func FilterPostWithTag(tx *gorm.DB, alias string) *gorm.DB {
prefix := viper.GetString("database.prefix")
return tx.Joins(fmt.Sprintf("JOIN %spost_tags ON %sposts.id = %spost_tags.post_id", prefix, prefix, prefix)).
Joins(fmt.Sprintf("JOIN %stags ON %stags.id = %spost_tags.tag_id", prefix, prefix, prefix)).
Where(fmt.Sprintf("%stags.alias = ?", prefix), alias)
}
func GetPost(tx *gorm.DB) (*models.Post, error) {
var post *models.Post
2024-02-14 14:30:07 +00:00
if err := PreloadRelatedPost(tx).First(&post).Error; err != nil {
return post, err
}
var reactInfo struct {
2024-02-14 14:30:07 +00:00
PostID uint `json:"post_id"`
LikeCount int64 `json:"like_count"`
DislikeCount int64 `json:"dislike_count"`
ReplyCount int64 `json:"reply_count"`
RepostCount int64 `json:"repost_count"`
}
prefix := viper.GetString("database.prefix")
2024-02-14 14:30:07 +00:00
database.C.Raw(fmt.Sprintf(`
SELECT t.id as post_id,
COALESCE(l.like_count, 0) AS like_count,
2024-02-14 14:30:07 +00:00
COALESCE(d.dislike_count, 0) AS dislike_count,
COALESCE(r.reply_count, 0) AS reply_count,
COALESCE(rp.repost_count, 0) AS repost_count
FROM %sposts t
LEFT JOIN (SELECT post_id, COUNT(*) AS like_count
FROM %spost_likes
GROUP BY post_id) l ON t.id = l.post_id
LEFT JOIN (SELECT post_id, COUNT(*) AS dislike_count
FROM %spost_dislikes
GROUP BY post_id) d ON t.id = d.post_id
2024-02-14 14:30:07 +00:00
LEFT JOIN (SELECT reply_id, COUNT(*) AS reply_count
FROM %sposts
WHERE reply_id IS NOT NULL
GROUP BY reply_id) r ON t.id = r.reply_id
LEFT JOIN (SELECT repost_id, COUNT(*) AS repost_count
FROM %sposts
WHERE repost_id IS NOT NULL
GROUP BY repost_id) rp ON t.id = rp.repost_id
WHERE t.id = ?`, prefix, prefix, prefix, prefix, prefix), post.ID).Scan(&reactInfo)
post.LikeCount = reactInfo.LikeCount
post.DislikeCount = reactInfo.DislikeCount
2024-02-14 14:30:07 +00:00
post.ReplyCount = reactInfo.ReplyCount
post.RepostCount = reactInfo.RepostCount
return post, nil
}
2024-02-05 07:51:31 +00:00
func ListPost(tx *gorm.DB, take int, offset int) ([]*models.Post, error) {
2024-02-12 04:32:37 +00:00
if take > 20 {
take = 20
}
2024-02-05 07:51:31 +00:00
var posts []*models.Post
if err := PreloadRelatedPost(tx).
Limit(take).
Offset(offset).
2024-02-03 07:20:32 +00:00
Find(&posts).Error; err != nil {
return posts, err
}
postIds := lo.Map(posts, func(item *models.Post, _ int) uint {
return item.ID
})
var reactInfo []struct {
2024-02-14 14:30:07 +00:00
PostID uint `json:"post_id"`
LikeCount int64 `json:"like_count"`
DislikeCount int64 `json:"dislike_count"`
ReplyCount int64 `json:"reply_count"`
RepostCount int64 `json:"repost_count"`
2024-02-03 07:20:32 +00:00
}
prefix := viper.GetString("database.prefix")
2024-02-14 14:30:07 +00:00
database.C.Raw(fmt.Sprintf(`
SELECT t.id as post_id,
2024-02-03 07:20:32 +00:00
COALESCE(l.like_count, 0) AS like_count,
2024-02-14 14:30:07 +00:00
COALESCE(d.dislike_count, 0) AS dislike_count,
COALESCE(r.reply_count, 0) AS reply_count,
COALESCE(rp.repost_count, 0) AS repost_count
2024-02-03 07:20:32 +00:00
FROM %sposts t
LEFT JOIN (SELECT post_id, COUNT(*) AS like_count
FROM %spost_likes
GROUP BY post_id) l ON t.id = l.post_id
LEFT JOIN (SELECT post_id, COUNT(*) AS dislike_count
FROM %spost_dislikes
GROUP BY post_id) d ON t.id = d.post_id
2024-02-14 14:30:07 +00:00
LEFT JOIN (SELECT reply_id, COUNT(*) AS reply_count
FROM %sposts
WHERE reply_id IS NOT NULL
GROUP BY reply_id) r ON t.id = r.reply_id
LEFT JOIN (SELECT repost_id, COUNT(*) AS repost_count
FROM %sposts
WHERE repost_id IS NOT NULL
GROUP BY repost_id) rp ON t.id = rp.repost_id
WHERE t.id IN ?`, prefix, prefix, prefix, prefix, prefix), postIds).Scan(&reactInfo)
2024-02-03 07:20:32 +00:00
postMap := lo.SliceToMap(posts, func(item *models.Post) (uint, *models.Post) {
return item.ID, item
})
for _, info := range reactInfo {
if post, ok := postMap[info.PostID]; ok {
post.LikeCount = info.LikeCount
post.DislikeCount = info.DislikeCount
2024-02-14 14:30:07 +00:00
post.ReplyCount = info.ReplyCount
post.RepostCount = info.RepostCount
2024-02-03 07:20:32 +00:00
}
}
return posts, nil
}
2024-02-02 15:42:42 +00:00
func NewPost(
user models.Account,
realm *models.Realm,
alias, title, content string,
2024-02-04 10:40:20 +00:00
attachments []models.Attachment,
2024-02-02 15:42:42 +00:00
categories []models.Category,
tags []models.Tag,
2024-02-03 17:08:31 +00:00
publishedAt *time.Time,
2024-02-03 16:24:04 +00:00
replyTo, repostTo *uint,
2024-02-02 15:42:42 +00:00
) (models.Post, error) {
var err error
var post models.Post
for idx, category := range categories {
2024-02-14 14:03:45 +00:00
categories[idx], err = GetCategory(category.Alias)
2024-02-02 15:42:42 +00:00
if err != nil {
return post, err
}
}
for idx, tag := range tags {
2024-02-14 14:03:45 +00:00
tags[idx], err = GetTagOrCreate(tag.Alias, tag.Name)
2024-02-02 15:42:42 +00:00
if err != nil {
return post, err
}
}
var realmId *uint
if realm != nil {
2024-02-09 04:36:39 +00:00
if !realm.IsPublic {
var member models.RealmMember
if err := database.C.Where(&models.RealmMember{
2024-02-09 10:43:48 +00:00
RealmID: realm.ID,
2024-02-09 04:36:39 +00:00
AccountID: user.ID,
}).First(&member).Error; err != nil {
return post, fmt.Errorf("you aren't a part of that realm")
}
}
2024-02-02 15:42:42 +00:00
realmId = &realm.ID
}
2024-02-03 17:08:31 +00:00
if publishedAt == nil {
publishedAt = lo.ToPtr(time.Now())
}
2024-02-02 15:42:42 +00:00
post = models.Post{
2024-02-03 17:08:31 +00:00
Alias: alias,
Title: title,
Content: content,
2024-02-04 10:40:20 +00:00
Attachments: attachments,
2024-02-03 17:08:31 +00:00
Tags: tags,
Categories: categories,
AuthorID: user.ID,
RealmID: realmId,
PublishedAt: *publishedAt,
RepostID: repostTo,
ReplyID: replyTo,
2024-02-02 15:42:42 +00:00
}
if err := database.C.Save(&post).Error; err != nil {
return post, err
}
if post.ReplyID != nil {
var op models.Post
if err := database.C.Where(&models.Post{
BaseModel: models.BaseModel{ID: *post.ReplyID},
}).Preload("Author").First(&op).Error; err == nil {
if op.Author.ID != user.ID {
2024-02-12 09:54:36 +00:00
postUrl := fmt.Sprintf("https://%s/posts/%s", viper.GetString("domain"), post.Alias)
err := NotifyAccount(
op.Author,
fmt.Sprintf("%s replied you", user.Name),
fmt.Sprintf("%s replied your post. Check it out!", user.Name),
fiber.Map{"label": "Related post", "url": postUrl},
)
if err != nil {
log.Error().Err(err).Msg("An error occurred when notifying user...")
}
}
}
}
go func() {
var subscribers []models.AccountMembership
if err := database.C.Where(&models.AccountMembership{
FollowingID: user.ID,
}).Preload("Follower").Find(&subscribers).Error; err != nil {
return
}
accounts := lo.Map(subscribers, func(item models.AccountMembership, index int) models.Account {
return item.Follower
})
for _, account := range accounts {
2024-02-12 09:54:36 +00:00
postUrl := fmt.Sprintf("https://%s/posts/%s", viper.GetString("domain"), post.Alias)
err := NotifyAccount(
account,
fmt.Sprintf("%s just posted a post", user.Name),
"Account you followed post a brand new post. Check it out!",
2024-02-12 09:54:36 +00:00
fiber.Map{"label": "Related post", "url": postUrl},
)
2024-02-12 09:54:36 +00:00
if err != nil {
log.Error().Err(err).Msg("An error occurred when notifying user...")
}
}
}()
2024-02-02 15:42:42 +00:00
return post, nil
}
2024-02-02 16:50:23 +00:00
2024-02-03 17:08:31 +00:00
func EditPost(
post models.Post,
alias, title, content string,
publishedAt *time.Time,
categories []models.Category,
tags []models.Tag,
attachments []models.Attachment,
2024-02-03 17:08:31 +00:00
) (models.Post, error) {
var err error
for idx, category := range categories {
2024-02-14 14:03:45 +00:00
categories[idx], err = GetCategory(category.Alias)
2024-02-03 17:08:31 +00:00
if err != nil {
return post, err
}
}
for idx, tag := range tags {
2024-02-14 14:03:45 +00:00
tags[idx], err = GetTagOrCreate(tag.Alias, tag.Name)
2024-02-03 17:08:31 +00:00
if err != nil {
return post, err
}
}
if publishedAt == nil {
publishedAt = lo.ToPtr(time.Now())
}
post.Alias = alias
post.Title = title
post.Content = content
post.PublishedAt = *publishedAt
post.Tags = tags
post.Categories = categories
post.Attachments = attachments
2024-02-03 17:08:31 +00:00
err = database.C.Save(&post).Error
return post, err
}
2024-02-02 16:50:23 +00:00
func LikePost(user models.Account, post models.Post) (bool, error) {
var like models.PostLike
if err := database.C.Where(&models.PostLike{
AccountID: user.ID,
PostID: post.ID,
}).First(&like).Error; err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
return true, err
}
like = models.PostLike{
AccountID: user.ID,
PostID: post.ID,
}
return true, database.C.Save(&like).Error
} else {
return false, database.C.Delete(&like).Error
}
}
func DislikePost(user models.Account, post models.Post) (bool, error) {
var dislike models.PostDislike
if err := database.C.Where(&models.PostDislike{
AccountID: user.ID,
PostID: post.ID,
}).First(&dislike).Error; err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
return true, err
}
dislike = models.PostDislike{
AccountID: user.ID,
PostID: post.ID,
}
return true, database.C.Save(&dislike).Error
} else {
return false, database.C.Delete(&dislike).Error
}
}
2024-02-03 17:08:31 +00:00
func DeletePost(post models.Post) error {
return database.C.Delete(&post).Error
}