rimgo/api/comments.go

90 lines
2.3 KiB
Go
Raw Normal View History

2022-01-18 23:05:06 +00:00
package api
import (
"strings"
"sync"
"time"
"codeberg.org/video-prize-ranch/rimgo/types"
"codeberg.org/video-prize-ranch/rimgo/utils"
"github.com/dustin/go-humanize"
2022-03-16 02:56:34 +00:00
"github.com/patrickmn/go-cache"
2022-01-18 23:05:06 +00:00
"github.com/tidwall/gjson"
)
2022-03-16 02:56:34 +00:00
var commentCache = cache.New(15*time.Minute, 15*time.Minute)
2022-01-18 23:05:06 +00:00
func FetchComments(galleryID string) ([]types.Comment, error) {
2022-03-16 02:56:34 +00:00
cacheData, found := commentCache.Get(galleryID)
if found {
return cacheData.([]types.Comment), nil
}
2022-01-18 23:05:06 +00:00
2022-05-23 15:10:50 +00:00
data, err := utils.GetJSON("https://api.imgur.com/comment/v1/comments?client_id=" + utils.Config["imgurId"].(string) + "&filter[post]=eq:" + galleryID + "&include=account,adconfig&per_page=30&sort=best")
2022-01-18 23:05:06 +00:00
if err != nil {
2022-05-23 15:10:50 +00:00
return []types.Comment{}, nil
2022-01-18 23:05:06 +00:00
}
wg := sync.WaitGroup{}
comments := make([]types.Comment, 0)
data.Get("data").ForEach(
func(key, value gjson.Result) bool {
wg.Add(1)
go func() {
defer wg.Done()
comments = append(comments, ParseComment(value))
}()
return true
},
)
wg.Wait()
2022-03-16 02:56:34 +00:00
commentCache.Set(galleryID, comments, cache.DefaultExpiration)
2022-01-18 23:05:06 +00:00
return comments, nil
}
func ParseComment(data gjson.Result) types.Comment {
createdTime, _ := time.Parse("2006-01-02T15:04:05Z", data.Get("created_at").String())
createdAt := createdTime.Format("January 2, 2006 3:04 PM")
updatedAt, _ := utils.FormatDate(data.Get("updated_at").String())
deletedAt, _ := utils.FormatDate(data.Get("deleted_at").String())
userAvatar := strings.ReplaceAll(data.Get("account.avatar").String(), "https://i.imgur.com", "")
wg := sync.WaitGroup{}
comments := make([]types.Comment, 0)
data.Get("comments").ForEach(
func(key, value gjson.Result) bool {
wg.Add(1)
go func() {
defer wg.Done()
comments = append(comments, ParseComment(value))
}()
return true
},
)
wg.Wait()
return types.Comment{
Comments: comments,
User: types.User{
2022-01-28 01:41:10 +00:00
Id: data.Get("account.id").Int(),
2022-01-18 23:05:06 +00:00
Username: data.Get("account.username").String(),
Avatar: userAvatar,
},
Id: data.Get("id").String(),
Comment: data.Get("comment").String(),
Upvotes: data.Get("upvote_count").Int(),
Downvotes: data.Get("downvote_count").Int(),
Platform: data.Get("platform").String(),
CreatedAt: createdAt,
RelTime: humanize.Time(createdTime),
UpdatedAt: updatedAt,
DeletedAt: deletedAt,
}
}