Articles & Article CRUD APIs

This commit is contained in:
2024-07-03 22:16:23 +08:00
parent 396b5c6122
commit 93285e3ac1
15 changed files with 703 additions and 235 deletions

View File

@ -0,0 +1,223 @@
package services
import (
"errors"
"fmt"
"time"
"git.solsynth.dev/hydrogen/interactive/pkg/internal/database"
"git.solsynth.dev/hydrogen/interactive/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/proto"
"github.com/rs/zerolog/log"
"github.com/samber/lo"
"github.com/spf13/viper"
"gorm.io/gorm"
)
func FilterArticleWithCategory(tx *gorm.DB, alias string) *gorm.DB {
return tx.Joins("JOIN article_categories ON articles.id = article_categories.article_id").
Joins("JOIN article_categories ON article_categories.id = article_categories.category_id").
Where("article_categories.alias = ?", alias)
}
func FilterArticleWithTag(tx *gorm.DB, alias string) *gorm.DB {
return tx.Joins("JOIN article_tags ON articles.id = article_tags.article_id").
Joins("JOIN article_tags ON article_tags.id = article_tags.category_id").
Where("article_tags.alias = ?", alias)
}
func FilterArticleWithRealm(tx *gorm.DB, id uint) *gorm.DB {
if id > 0 {
return tx.Where("realm_id = ?", id)
} else {
return tx.Where("realm_id IS NULL")
}
}
func FilterArticleWithPublishedAt(tx *gorm.DB, date time.Time) *gorm.DB {
return tx.Where("published_at <= ? OR published_at IS NULL", date)
}
func FilterArticleWithAuthorDraft(tx *gorm.DB, uid uint) *gorm.DB {
return tx.Where("author_id = ? AND is_draft = ?", uid, true)
}
func FilterArticleDraft(tx *gorm.DB) *gorm.DB {
return tx.Where("is_draft = ?", false)
}
func GetArticleWithAlias(tx *gorm.DB, alias string, ignoreLimitation ...bool) (models.Article, error) {
if len(ignoreLimitation) == 0 || !ignoreLimitation[0] {
tx = FilterArticleWithPublishedAt(tx, time.Now())
}
var item models.Article
if err := tx.
Where("alias = ?", alias).
Preload("Realm").
Preload("Author").
First(&item).Error; err != nil {
return item, err
}
return item, nil
}
func GetArticle(tx *gorm.DB, id uint, ignoreLimitation ...bool) (models.Article, error) {
if len(ignoreLimitation) == 0 || !ignoreLimitation[0] {
tx = FilterArticleWithPublishedAt(tx, time.Now())
}
var item models.Article
if err := tx.
Where("id = ?", id).
Preload("Realm").
Preload("Author").
First(&item).Error; err != nil {
return item, err
}
return item, nil
}
func CountArticle(tx *gorm.DB) (int64, error) {
var count int64
if err := tx.Model(&models.Article{}).Count(&count).Error; err != nil {
return count, err
}
return count, nil
}
func CountArticleReactions(id uint) int64 {
var count int64
if err := database.C.Model(&models.Reaction{}).
Where("article_id = ?", id).
Count(&count).Error; err != nil {
return 0
}
return count
}
func ListArticle(tx *gorm.DB, take int, offset int, noReact ...bool) ([]*models.Article, error) {
if take > 20 {
take = 20
}
var items []*models.Article
if err := tx.
Limit(take).Offset(offset).
Order("created_at DESC").
Preload("Realm").
Preload("Author").
Find(&items).Error; err != nil {
return items, err
}
idx := lo.Map(items, func(item *models.Article, index int) uint {
return item.ID
})
// Load reactions
if len(noReact) <= 0 || !noReact[0] {
if mapping, err := BatchListResourceReactions(database.C.Where("article_id IN ?", idx)); err != nil {
return items, err
} else {
itemMap := lo.SliceToMap(items, func(item *models.Article) (uint, *models.Article) {
return item.ID, item
})
for k, v := range mapping {
if post, ok := itemMap[k]; ok {
post.ReactionList = v
}
}
}
}
return items, nil
}
func EnsureArticleCategoriesAndTags(item models.Article) (models.Article, error) {
var err error
for idx, category := range item.Categories {
item.Categories[idx], err = GetCategory(category.Alias)
if err != nil {
return item, err
}
}
for idx, tag := range item.Tags {
item.Tags[idx], err = GetTagOrCreate(tag.Alias, tag.Name)
if err != nil {
return item, err
}
}
return item, nil
}
func NewArticle(user models.Account, item models.Article) (models.Article, error) {
item, err := EnsureArticleCategoriesAndTags(item)
if err != nil {
return item, err
}
if item.RealmID != nil {
_, err := GetRealmMember(*item.RealmID, user.ExternalID)
if err != nil {
return item, fmt.Errorf("you aren't a part of that realm: %v", err)
}
}
if err := database.C.Save(&item).Error; err != nil {
return item, err
}
return item, nil
}
func EditArticle(item models.Article) (models.Article, error) {
item, err := EnsureArticleCategoriesAndTags(item)
if err != nil {
return item, err
}
err = database.C.Save(&item).Error
return item, err
}
func DeleteArticle(item models.Article) error {
return database.C.Delete(&item).Error
}
func ReactArticle(user models.Account, reaction models.Reaction) (bool, models.Reaction, error) {
if err := database.C.Where(reaction).First(&reaction).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
var op models.Article
if err := database.C.
Where("id = ?", reaction.ArticleID).
Preload("Author").
First(&op).Error; err == nil {
if op.Author.ID != user.ID {
articleUrl := fmt.Sprintf("https://%s/articles/%s", viper.GetString("domain"), op.Alias)
err := NotifyPosterAccount(
op.Author,
fmt.Sprintf("%s reacted your article", user.Nick),
fmt.Sprintf("%s (%s) reacted your article a %s", user.Nick, user.Name, reaction.Symbol),
&proto.NotifyLink{Label: "Related article", Url: articleUrl},
)
if err != nil {
log.Error().Err(err).Msg("An error occurred when notifying user...")
}
}
}
return true, reaction, database.C.Save(&reaction).Error
} else {
return true, reaction, err
}
} else {
return false, reaction, database.C.Delete(&reaction).Error
}
}

View File

@ -1,81 +0,0 @@
package services
import (
"fmt"
"github.com/gofiber/fiber/v2"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/spf13/viper"
)
type PayloadClaims struct {
jwt.RegisteredClaims
Type string `json:"typ"`
}
const (
JwtAccessType = "access"
JwtRefreshType = "refresh"
)
const (
CookieAccessKey = "passport_auth_key"
CookieRefreshKey = "passport_refresh_key"
)
func EncodeJwt(id string, typ, sub string, aud []string, exp time.Time) (string, error) {
tk := jwt.NewWithClaims(jwt.SigningMethodHS512, PayloadClaims{
jwt.RegisteredClaims{
Subject: sub,
Audience: aud,
Issuer: fmt.Sprintf("https://%s", viper.GetString("domain")),
ExpiresAt: jwt.NewNumericDate(exp),
NotBefore: jwt.NewNumericDate(time.Now()),
IssuedAt: jwt.NewNumericDate(time.Now()),
ID: id,
},
typ,
})
return tk.SignedString([]byte(viper.GetString("secret")))
}
func DecodeJwt(str string) (PayloadClaims, error) {
var claims PayloadClaims
tk, err := jwt.ParseWithClaims(str, &claims, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(viper.GetString("secret")), nil
})
if err != nil {
return claims, err
}
if data, ok := tk.Claims.(*PayloadClaims); ok {
return *data, nil
} else {
return claims, fmt.Errorf("unexpected token payload: not payload claims type")
}
}
func SetJwtCookieSet(c *fiber.Ctx, access, refresh string) {
c.Cookie(&fiber.Cookie{
Name: CookieAccessKey,
Value: access,
Domain: viper.GetString("security.cookie_domain"),
SameSite: viper.GetString("security.cookie_samesite"),
Expires: time.Now().Add(60 * time.Minute),
Path: "/",
})
c.Cookie(&fiber.Cookie{
Name: CookieRefreshKey,
Value: refresh,
Domain: viper.GetString("security.cookie_domain"),
SameSite: viper.GetString("security.cookie_samesite"),
Expires: time.Now().Add(24 * 30 * time.Hour),
Path: "/",
})
}

View File

@ -1,51 +0,0 @@
package services
import (
"crypto/tls"
"fmt"
"net/smtp"
"net/textproto"
"github.com/jordan-wright/email"
"github.com/spf13/viper"
)
func SendMail(target string, subject string, content string) error {
mail := &email.Email{
To: []string{target},
From: viper.GetString("mailer.name"),
Subject: subject,
Text: []byte(content),
Headers: textproto.MIMEHeader{},
}
return mail.SendWithTLS(
fmt.Sprintf("%s:%d", viper.GetString("mailer.smtp_host"), viper.GetInt("mailer.smtp_port")),
smtp.PlainAuth(
"",
viper.GetString("mailer.username"),
viper.GetString("mailer.password"),
viper.GetString("mailer.smtp_host"),
),
&tls.Config{ServerName: viper.GetString("mailer.smtp_host")},
)
}
func SendMailHTML(target string, subject string, content string) error {
mail := &email.Email{
To: []string{target},
From: viper.GetString("mailer.name"),
Subject: subject,
HTML: []byte(content),
Headers: textproto.MIMEHeader{},
}
return mail.SendWithTLS(
fmt.Sprintf("%s:%d", viper.GetString("mailer.smtp_host"), viper.GetInt("mailer.smtp_port")),
smtp.PlainAuth(
"",
viper.GetString("mailer.username"),
viper.GetString("mailer.password"),
viper.GetString("mailer.smtp_host"),
),
&tls.Config{ServerName: viper.GetString("mailer.smtp_host")},
)
}

View File

@ -26,7 +26,7 @@ func FilterPostWithTag(tx *gorm.DB, alias string) *gorm.DB {
Where("post_tags.alias = ?", alias)
}
func FilterWithRealm(tx *gorm.DB, id uint) *gorm.DB {
func FilterPostWithRealm(tx *gorm.DB, id uint) *gorm.DB {
if id > 0 {
return tx.Where("realm_id = ?", id)
} else {
@ -46,8 +46,15 @@ func FilterPostWithPublishedAt(tx *gorm.DB, date time.Time) *gorm.DB {
return tx.Where("published_at <= ? OR published_at IS NULL", date)
}
func GetPostWithAlias(alias string, ignoreLimitation ...bool) (models.Post, error) {
tx := database.C
func FilterPostWithAuthorDraft(tx *gorm.DB, uid uint) *gorm.DB {
return tx.Where("author_id = ? AND is_draft = ?", uid, true)
}
func FilterPostDraft(tx *gorm.DB) *gorm.DB {
return tx.Where("is_draft = ?", false)
}
func GetPostWithAlias(tx *gorm.DB, alias string, ignoreLimitation ...bool) (models.Post, error) {
if len(ignoreLimitation) == 0 || !ignoreLimitation[0] {
tx = FilterPostWithPublishedAt(tx, time.Now())
}
@ -68,8 +75,7 @@ func GetPostWithAlias(alias string, ignoreLimitation ...bool) (models.Post, erro
return item, nil
}
func GetPost(id uint, ignoreLimitation ...bool) (models.Post, error) {
tx := database.C
func GetPost(tx *gorm.DB, id uint, ignoreLimitation ...bool) (models.Post, error) {
if len(ignoreLimitation) == 0 || !ignoreLimitation[0] {
tx = FilterPostWithPublishedAt(tx, time.Now())
}
@ -121,29 +127,6 @@ func CountPostReactions(id uint) int64 {
return count
}
func ListPostReactions(id uint) (map[string]int64, error) {
var reactions []struct {
Symbol string
Count int64
}
if err := database.C.Model(&models.Reaction{}).
Select("symbol, COUNT(id) as count").
Where("post_id = ?", id).
Group("symbol").
Scan(&reactions).Error; err != nil {
return map[string]int64{}, err
}
return lo.SliceToMap(reactions, func(item struct {
Symbol string
Count int64
},
) (string, int64) {
return item.Symbol, item.Count
}), nil
}
func ListPost(tx *gorm.DB, take int, offset int, noReact ...bool) ([]*models.Post, error) {
if take > 20 {
take = 20
@ -167,40 +150,24 @@ func ListPost(tx *gorm.DB, take int, offset int, noReact ...bool) ([]*models.Pos
return item.ID
})
// Load reactions
if len(noReact) <= 0 || !noReact[0] {
var reactions []struct {
PostID uint
Symbol string
Count int64
}
if err := database.C.Model(&models.Reaction{}).
Select("post_id, symbol, COUNT(id) as count").
Where("post_id IN (?)", idx).
Group("post_id, symbol").
Scan(&reactions).Error; err != nil {
if mapping, err := BatchListResourceReactions(database.C.Where("post_id IN ?", idx)); err != nil {
return items, err
}
} else {
itemMap := lo.SliceToMap(items, func(item *models.Post) (uint, *models.Post) {
return item.ID, item
})
itemMap := lo.SliceToMap(items, func(item *models.Post) (uint, *models.Post) {
return item.ID, item
})
list := map[uint]map[string]int64{}
for _, info := range reactions {
if _, ok := list[info.PostID]; !ok {
list[info.PostID] = make(map[string]int64)
}
list[info.PostID][info.Symbol] = info.Count
}
for k, v := range list {
if post, ok := itemMap[k]; ok {
post.ReactionList = v
for k, v := range mapping {
if post, ok := itemMap[k]; ok {
post.ReactionList = v
}
}
}
}
// Load replies
if len(noReact) <= 0 || !noReact[0] {
var replies []struct {
PostID uint
@ -234,7 +201,7 @@ func ListPost(tx *gorm.DB, take int, offset int, noReact ...bool) ([]*models.Pos
return items, nil
}
func InitPostCategoriesAndTags(item models.Post) (models.Post, error) {
func EnsurePostCategoriesAndTags(item models.Post) (models.Post, error) {
var err error
for idx, category := range item.Categories {
item.Categories[idx], err = GetCategory(category.Alias)
@ -252,7 +219,7 @@ func InitPostCategoriesAndTags(item models.Post) (models.Post, error) {
}
func NewPost(user models.Account, item models.Post) (models.Post, error) {
item, err := InitPostCategoriesAndTags(item)
item, err := EnsurePostCategoriesAndTags(item)
if err != nil {
return item, err
}
@ -294,7 +261,7 @@ func NewPost(user models.Account, item models.Post) (models.Post, error) {
}
func EditPost(item models.Post) (models.Post, error) {
item, err := InitPostCategoriesAndTags(item)
item, err := EnsurePostCategoriesAndTags(item)
if err != nil {
return item, err
}

View File

@ -0,0 +1,54 @@
package services
import (
"git.solsynth.dev/hydrogen/interactive/pkg/internal/models"
"github.com/samber/lo"
"gorm.io/gorm"
)
func ListResourceReactions(tx *gorm.DB) (map[string]int64, error) {
var reactions []struct {
Symbol string
Count int64
}
if err := tx.Model(&models.Reaction{}).
Select("symbol, COUNT(id) as count").
Group("symbol").
Scan(&reactions).Error; err != nil {
return map[string]int64{}, err
}
return lo.SliceToMap(reactions, func(item struct {
Symbol string
Count int64
},
) (string, int64) {
return item.Symbol, item.Count
}), nil
}
func BatchListResourceReactions(tx *gorm.DB) (map[uint]map[string]int64, error) {
var reactions []struct {
ArticleID uint
Symbol string
Count int64
}
reactInfo := map[uint]map[string]int64{}
if err := tx.Model(&models.Reaction{}).
Select("article_id, symbol, COUNT(id) as count").
Group("article_id, symbol").
Scan(&reactions).Error; err != nil {
return reactInfo, err
}
for _, info := range reactions {
if _, ok := reactInfo[info.ArticleID]; !ok {
reactInfo[info.ArticleID] = make(map[string]int64)
}
reactInfo[info.ArticleID][info.Symbol] = info.Count
}
return reactInfo, nil
}