rimgo/api/album.go

60 lines
1.5 KiB
Go
Raw Normal View History

2022-01-17 20:23:04 +00:00
package api
import (
"io"
"net/http"
"strings"
"time"
2022-01-17 22:34:05 +00:00
"codeberg.org/video-prize-ranch/rimgo/types"
2022-01-17 20:23:04 +00:00
"github.com/spf13/viper"
"github.com/tidwall/gjson"
)
func FetchAlbum(albumID string) (types.Album, error) {
// https://api.imgur.com/post/v1/albums/zk7mdKH?client_id=${CLIENT_ID}&include=media%2Caccount
res, err := http.Get("https://api.imgur.com/post/v1/albums/" + albumID + "?client_id=" + viper.GetString("RIMGU_IMGUR_CLIENT_ID") + "&include=media%2Caccount")
if err != nil {
return types.Album{}, err
}
body, err := io.ReadAll(res.Body)
if err != nil {
return types.Album{}, err
}
data := gjson.Parse(string(body))
2022-01-17 22:11:33 +00:00
media := make([]types.Media, 0)
2022-01-17 20:23:04 +00:00
data.Get("media").ForEach(
func(key gjson.Result, value gjson.Result) bool {
url := value.Get("url").String()
2022-01-17 22:47:33 +00:00
url = strings.ReplaceAll(url, "https://i.imgur.com", "")
2022-01-17 22:11:33 +00:00
media = append(media, types.Media{
2022-01-17 22:34:05 +00:00
Id: value.Get("id").String(),
Name: value.Get("name").String(),
Title: value.Get("metadata.title").String(),
2022-01-17 22:11:33 +00:00
Description: value.Get("metadata.description").String(),
2022-01-17 22:34:05 +00:00
Url: url,
2022-01-17 22:11:33 +00:00
})
2022-01-17 20:23:04 +00:00
return true
},
)
createdAt, err := time.Parse("2006-01-02T15:04:05Z", data.Get("created_at").String())
if err != nil {
return types.Album{}, err
}
return types.Album{
2022-01-17 22:34:05 +00:00
Id: data.Get("id").String(),
Title: data.Get("title").String(),
Views: data.Get("view_count").Int(),
CreatedAt: createdAt.Format("January 2, 2006 3:04 PM"),
Media: media,
2022-01-17 20:23:04 +00:00
}, nil
2022-01-17 22:34:05 +00:00
}