⬆️ Upgrade to support the latest version Hydrogen Project standard

This commit is contained in:
2024-06-22 17:29:53 +08:00
parent 52c864b11f
commit c79c8d3618
45 changed files with 538 additions and 279 deletions

View File

@ -0,0 +1,64 @@
package services
import (
"context"
"git.solsynth.dev/hydrogen/interactive/pkg/internal/database"
"git.solsynth.dev/hydrogen/interactive/pkg/internal/gap"
"git.solsynth.dev/hydrogen/interactive/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/proto"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
"time"
)
func GetAccountFriend(userId, relatedId uint, status int) (*proto.FriendshipResponse, error) {
var user models.Account
if err := database.C.Where("id = ?", userId).First(&user).Error; err != nil {
return nil, err
}
var related models.Account
if err := database.C.Where("id = ?", relatedId).First(&related).Error; err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
pc, err := gap.H.DiscoverServiceGRPC("Hydrogen.Passport")
if err != nil {
return nil, err
}
return proto.NewFriendshipsClient(pc).GetFriendship(ctx, &proto.FriendshipTwoSideLookupRequest{
AccountId: uint64(user.ExternalID),
RelatedId: uint64(related.ExternalID),
Status: uint32(status),
})
}
func NotifyPosterAccount(user models.Account, subject, content string, links ...*proto.NotifyLink) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
pc, err := gap.H.DiscoverServiceGRPC("Hydrogen.Passport")
if err != nil {
return err
}
_, err = proto.NewNotifyClient(pc).NotifyUser(ctx, &proto.NotifyRequest{
ClientId: viper.GetString("passport.client_id"),
ClientSecret: viper.GetString("passport.client_secret"),
Type: "interactive.feedback",
Subject: subject,
Content: content,
Links: links,
RecipientId: uint64(user.ExternalID),
IsRealtime: false,
IsForcePush: true,
})
if err != nil {
log.Warn().Err(err).Msg("An error occurred when notify account...")
} else {
log.Debug().Uint("eid", user.ExternalID).Msg("Notified account.")
}
return err
}

View File

@ -0,0 +1,20 @@
package services
import (
"context"
"git.solsynth.dev/hydrogen/interactive/pkg/internal/gap"
"git.solsynth.dev/hydrogen/paperclip/pkg/proto"
"github.com/samber/lo"
)
func CheckAttachmentByIDExists(id uint, usage string) bool {
pc, err := gap.H.DiscoverServiceGRPC("Hydrogen.Paperclip")
if err != nil {
return false
}
_, err = proto.NewAttachmentsClient(pc).CheckAttachmentExists(context.Background(), &proto.AttachmentLookupRequest{
Id: lo.ToPtr(uint64(id)),
Usage: &usage,
})
return err == nil
}

View File

@ -0,0 +1,51 @@
package services
import (
"errors"
"fmt"
"git.solsynth.dev/hydrogen/interactive/pkg/internal/database"
"git.solsynth.dev/hydrogen/interactive/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/proto"
"gorm.io/gorm"
"reflect"
)
func LinkAccount(userinfo *proto.Userinfo) (models.Account, error) {
var account models.Account
if userinfo == nil {
return account, fmt.Errorf("remote userinfo was not found")
}
if err := database.C.Where(&models.Account{
ExternalID: uint(userinfo.Id),
}).First(&account).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
account = models.Account{
Name: userinfo.Name,
Nick: userinfo.Nick,
Avatar: userinfo.Avatar,
Banner: userinfo.Banner,
Description: userinfo.GetDescription(),
EmailAddress: userinfo.Email,
PowerLevel: 0,
ExternalID: uint(userinfo.Id),
}
return account, database.C.Save(&account).Error
}
return account, err
}
prev := account
account.Name = userinfo.Name
account.Nick = userinfo.Nick
account.Avatar = userinfo.Avatar
account.Banner = userinfo.Banner
account.Description = userinfo.GetDescription()
account.EmailAddress = userinfo.Email
var err error
if !reflect.DeepEqual(prev, account) {
err = database.C.Save(&account).Error
}
return account, err
}

View File

@ -0,0 +1,77 @@
package services
import (
"errors"
"git.solsynth.dev/hydrogen/interactive/pkg/internal/database"
"git.solsynth.dev/hydrogen/interactive/pkg/internal/models"
"gorm.io/gorm"
)
func ListCategory() ([]models.Category, error) {
var categories []models.Category
err := database.C.Find(&categories).Error
return categories, err
}
func GetCategory(alias string) (models.Category, error) {
var category models.Category
if err := database.C.Where(models.Category{Alias: alias}).First(&category).Error; err != nil {
return category, err
}
return category, nil
}
func GetCategoryWithID(id uint) (models.Category, error) {
var category models.Category
if err := database.C.Where(models.Category{
BaseModel: models.BaseModel{ID: id},
}).First(&category).Error; err != nil {
return category, err
}
return category, nil
}
func NewCategory(alias, name, description string) (models.Category, error) {
category := models.Category{
Alias: alias,
Name: name,
Description: description,
}
err := database.C.Save(&category).Error
return category, err
}
func EditCategory(category models.Category, alias, name, description string) (models.Category, error) {
category.Alias = alias
category.Name = name
category.Description = description
err := database.C.Save(&category).Error
return category, err
}
func DeleteCategory(category models.Category) error {
return database.C.Delete(category).Error
}
func GetTagOrCreate(alias, name string) (models.Tag, error) {
var tag models.Tag
if err := database.C.Where(models.Category{Alias: alias}).First(&tag).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
tag = models.Tag{
Alias: alias,
Name: name,
}
err := database.C.Save(&tag).Error
return tag, err
}
return tag, err
}
return tag, nil
}

View File

@ -0,0 +1,23 @@
package services
import (
"git.solsynth.dev/hydrogen/interactive/pkg/internal/database"
"github.com/rs/zerolog/log"
"time"
)
func DoAutoDatabaseCleanup() {
deadline := time.Now().Add(60 * time.Minute)
log.Debug().Time("deadline", deadline).Msg("Now cleaning up entire database...")
var count int64
for _, model := range database.AutoMaintainRange {
tx := database.C.Unscoped().Delete(model, "deleted_at >= ?", deadline)
if tx.Error != nil {
log.Error().Err(tx.Error).Msg("An error occurred when running auth context cleanup...")
}
count += tx.RowsAffected
}
log.Debug().Int64("affected", count).Msg("Clean up entire database accomplished.")
}

View File

@ -0,0 +1,12 @@
package services
import "golang.org/x/crypto/bcrypt"
func HashPassword(raw string) string {
data, _ := bcrypt.GenerateFromPassword([]byte(raw), 12)
return string(data)
}
func VerifyPassword(text string, password string) bool {
return bcrypt.CompareHashAndPassword([]byte(password), []byte(text)) == nil
}

View File

@ -0,0 +1,81 @@
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

@ -0,0 +1,51 @@
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

@ -0,0 +1,337 @@
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 FilterPostWithCategory(tx *gorm.DB, alias string) *gorm.DB {
return tx.Joins("JOIN post_categories ON posts.id = post_categories.post_id").
Joins("JOIN post_categories ON post_categories.id = post_categories.category_id").
Where("post_categories.alias = ?", alias)
}
func FilterPostWithTag(tx *gorm.DB, alias string) *gorm.DB {
return tx.Joins("JOIN post_tags ON posts.id = post_tags.post_id").
Joins("JOIN post_tags ON post_tags.id = post_tags.category_id").
Where("post_tags.alias = ?", alias)
}
func FilterWithRealm(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 FilterPostReply(tx *gorm.DB, replyTo ...uint) *gorm.DB {
if len(replyTo) > 0 && replyTo[0] > 0 {
return tx.Where("reply_id = ?", replyTo[0])
} else {
return tx.Where("reply_id IS NULL")
}
}
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
if len(ignoreLimitation) == 0 || !ignoreLimitation[0] {
tx = FilterPostWithPublishedAt(tx, time.Now())
}
var item models.Post
if err := tx.
Where("alias = ?", alias).
Preload("Author").
Preload("ReplyTo").
Preload("ReplyTo.Author").
Preload("RepostTo").
Preload("RepostTo.Author").
First(&item).Error; err != nil {
return item, err
}
return item, nil
}
func GetPost(id uint, ignoreLimitation ...bool) (models.Post, error) {
tx := database.C
if len(ignoreLimitation) == 0 || !ignoreLimitation[0] {
tx = FilterPostWithPublishedAt(tx, time.Now())
}
var item models.Post
if err := tx.
Where("id = ?", id).
Preload("Author").
Preload("ReplyTo").
Preload("ReplyTo.Author").
Preload("RepostTo").
Preload("RepostTo.Author").
First(&item).Error; err != nil {
return item, err
}
return item, nil
}
func CountPost(tx *gorm.DB) (int64, error) {
var count int64
if err := tx.Model(&models.Post{}).Count(&count).Error; err != nil {
return count, err
}
return count, nil
}
func CountPostReply(id uint) int64 {
var count int64
if err := database.C.Model(&models.Post{}).
Where("reply_id = ?", id).
Count(&count).Error; err != nil {
return 0
}
return count
}
func CountPostReactions(id uint) int64 {
var count int64
if err := database.C.Model(&models.Reaction{}).
Where("post_id = ?", id).
Count(&count).Error; err != nil {
return 0
}
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
}
var items []*models.Post
if err := tx.
Limit(take).Offset(offset).
Order("created_at DESC").
Preload("Author").
Preload("ReplyTo").
Preload("ReplyTo.Author").
Preload("RepostTo").
Preload("RepostTo.Author").
Find(&items).Error; err != nil {
return items, err
}
idx := lo.Map(items, func(item *models.Post, index int) uint {
return item.ID
})
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 {
return items, err
}
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
}
}
}
if len(noReact) <= 0 || !noReact[0] {
var replies []struct {
PostID uint
Count int64
}
if err := database.C.Model(&models.Post{}).
Select("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 {
post.ReplyCount = v
}
}
}
return items, nil
}
func InitPostCategoriesAndTags(item models.Post) (models.Post, 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 NewPost(user models.Account, item models.Post) (models.Post, error) {
item, err := InitPostCategoriesAndTags(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
}
// Notify the original poster its post has been replied
if item.ReplyID != nil {
var op models.Post
if err := database.C.
Where("id = ?", item.ReplyID).
Preload("Author").
First(&op).Error; err == nil {
if op.Author.ID != user.ID {
postUrl := fmt.Sprintf("https://%s/posts/%s", viper.GetString("domain"), item.Alias)
err := NotifyPosterAccount(
op.Author,
fmt.Sprintf("%s replied you", user.Nick),
fmt.Sprintf("%s (%s) replied your post #%s.", user.Nick, user.Name, op.Alias),
&proto.NotifyLink{Label: "Related post", Url: postUrl},
)
if err != nil {
log.Error().Err(err).Msg("An error occurred when notifying user...")
}
}
}
}
return item, nil
}
func EditPost(item models.Post) (models.Post, error) {
item, err := InitPostCategoriesAndTags(item)
if err != nil {
return item, err
}
err = database.C.Save(&item).Error
return item, err
}
func DeletePost(item models.Post) error {
return database.C.Delete(&item).Error
}
func ReactPost(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.Post
if err := database.C.
Where("id = ?", reaction.PostID).
Preload("Author").
First(&op).Error; err == nil {
if op.Author.ID != user.ID {
postUrl := fmt.Sprintf("https://%s/posts/%s", viper.GetString("domain"), op.Alias)
err := NotifyPosterAccount(
op.Author,
fmt.Sprintf("%s reacted your post", user.Nick),
fmt.Sprintf("%s (%s) reacted your post a %s", user.Nick, user.Name, reaction.Symbol),
&proto.NotifyLink{Label: "Related post", Url: postUrl},
)
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

@ -0,0 +1,112 @@
package services
import (
"context"
"errors"
"fmt"
"git.solsynth.dev/hydrogen/interactive/pkg/internal/database"
"git.solsynth.dev/hydrogen/interactive/pkg/internal/gap"
"git.solsynth.dev/hydrogen/interactive/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/proto"
"github.com/samber/lo"
"gorm.io/gorm"
"reflect"
)
func GetRealm(id uint) (models.Realm, error) {
var realm models.Realm
pc, err := gap.H.DiscoverServiceGRPC("Hydrogen.Passport")
if err != nil {
return realm, err
}
response, err := proto.NewRealmsClient(pc).GetRealm(context.Background(), &proto.RealmLookupRequest{
Id: lo.ToPtr(uint64(id)),
})
if err != nil {
return realm, err
}
return LinkRealm(response)
}
func GetRealmWithAlias(alias string) (models.Realm, error) {
var realm models.Realm
pc, err := gap.H.DiscoverServiceGRPC("Hydrogen.Passport")
if err != nil {
return realm, err
}
response, err := proto.NewRealmsClient(pc).GetRealm(context.Background(), &proto.RealmLookupRequest{
Alias: &alias,
})
if err != nil {
return realm, err
}
return LinkRealm(response)
}
func GetRealmMember(realmId uint, userId uint) (*proto.RealmMemberResponse, error) {
pc, err := gap.H.DiscoverServiceGRPC("Hydrogen.Passport")
if err != nil {
return nil, err
}
response, err := proto.NewRealmsClient(pc).GetRealmMember(context.Background(), &proto.RealmMemberLookupRequest{
RealmId: uint64(realmId),
UserId: lo.ToPtr(uint64(userId)),
})
if err != nil {
return nil, err
} else {
return response, nil
}
}
func ListRealmMember(realmId uint) ([]*proto.RealmMemberResponse, error) {
pc, err := gap.H.DiscoverServiceGRPC("Hydrogen.Passport")
if err != nil {
return nil, err
}
response, err := proto.NewRealmsClient(pc).ListRealmMember(context.Background(), &proto.RealmMemberLookupRequest{
RealmId: uint64(realmId),
})
if err != nil {
return nil, err
} else {
return response.Data, nil
}
}
func LinkRealm(info *proto.RealmResponse) (models.Realm, error) {
var realm models.Realm
if info == nil {
return realm, fmt.Errorf("remote realm info was not found")
}
if err := database.C.Where(&models.Realm{
ExternalID: uint(info.Id),
}).First(&realm).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
realm = models.Realm{
Alias: info.Alias,
Name: info.Name,
Description: info.Description,
IsPublic: info.IsPublic,
IsCommunity: info.IsCommunity,
ExternalID: uint(info.Id),
}
return realm, database.C.Save(&realm).Error
}
return realm, err
}
prev := realm
realm.Alias = info.Alias
realm.Name = info.Name
realm.Description = info.Description
realm.IsPublic = info.IsPublic
realm.IsCommunity = info.IsCommunity
var err error
if !reflect.DeepEqual(prev, realm) {
err = database.C.Save(&realm).Error
}
return realm, err
}