logic/anilist.go

69 lines
1.9 KiB
Go
Raw Normal View History

2023-01-13 11:10:07 +01:00
package logic
import (
"context"
"git.milar.in/milarin/anilist"
"git.milar.in/milarin/channel"
"git.milar.in/nyaanime/model"
)
func GetAnimeListByAnimeID() (map[anilist.MediaID]*anilist.MediaList, error) {
watchingAnimesChannel, err := GetCurrentlyWatchingAnimes()
if err != nil {
return nil, err
}
toMapFunc := func(entry *anilist.MediaList) (anilist.MediaID, *anilist.MediaList) { return entry.MediaID, entry }
return channel.ToMap(watchingAnimesChannel, toMapFunc), nil
}
func GetCurrentlyWatchingAnimes() (<-chan *anilist.MediaList, error) {
return GetCurrentlyWatchingAnimesContext(context.Background())
}
func GetCurrentlyWatchingAnimesContext(ctx context.Context) (<-chan *anilist.MediaList, error) {
2023-01-13 11:10:07 +01:00
token, err := GetAnilistAccessToken()
if err != nil {
return nil, ErrAnimeListNotObtainable.Wrap(err, "access token acquisition failed")
}
media := channel.Map(channel.Of(AnimeStatuses...), func(status anilist.MediaListStatus) <-chan *anilist.MediaList {
return anilist.NewApi(token).GetMediaList(ctx, anilist.MediaListQuery{
2023-01-13 11:10:07 +01:00
UserName: AnilistUsername,
Type: anilist.MediaTypeAnime,
Status: status,
}, nil).Chan
})
return channel.FlatChan(media), nil
}
var (
animeByTitleCache = map[string]model.Pair[*anilist.Media, error]{}
)
func SearchAnimeByTitle(title string) (anime *anilist.Media, err error) {
// caching
if cacheEntry, ok := animeByTitleCache[title]; ok {
return cacheEntry.First, cacheEntry.Second
}
defer func() { animeByTitleCache[title] = model.Pair[*anilist.Media, error]{First: anime, Second: err} }()
token, err := GetAnilistAccessToken()
if err != nil {
return nil, err
}
anime = anilist.NewApi(token).GetMedia(context.Background(), anilist.MediaQuery{
Search: title,
Type: anilist.MediaTypeAnime,
}, nil).First()
2023-01-13 11:10:07 +01:00
if anime == nil {
return nil, ErrAnimeNotFound.New(title)
}
return anime, nil
}