import type { AniListAuthorisation } from '$lib/AniList/identity'; import type { UserIdentity } from './identity'; import anime from '../../stores/anime'; import manga from '../../stores/manga'; import mangaLastPrune from '../../stores/mangaLastPrune'; import animeLastPrune from '../../stores/animeLastPrune'; import cacheMinutes from '../../stores/cacheMinutes'; export enum Type { Anime, Manga } export interface Media { id: number; status: string; type: string; episodes: number; format: string; title: { romaji: string; english: string; native: string; }; nextAiringEpisode?: { episode: number; timeUntilAiring?: number; }; mediaListEntry?: { progress: number; }; startDate: { year: number; }; } export const flattenLists = (lists: object[][]) => { if (lists === undefined) { return []; } let flattenedList: any[] = []; const minimisedList: Media[] = []; for (const list of lists) { flattenedList = flattenedList.concat(list['entries']); } for (const [position, entry] of flattenedList.entries()) { minimisedList[position] = entry['media']; } return minimisedList; }; export const mediaListCollection = async ( anilistAuthorisation: AniListAuthorisation, userIdentity: UserIdentity, type: Type, mediaCache: string | undefined, currentLastPruneAt: string | number = 0 ) => { let currentCacheMinutes; cacheMinutes.subscribe((value) => { currentCacheMinutes = value; }); if (String(currentLastPruneAt) == '') { if (type === Type.Anime) { animeLastPrune.set(new Date().getTime().toString()); } else { mangaLastPrune.set(new Date().getTime().toString()); } } else { if ( (new Date().getTime() - Number(currentLastPruneAt)) / 1000 / 60 > Number(currentCacheMinutes) ) { if (type === Type.Anime) { animeLastPrune.set(new Date().getTime().toString()); anime.set(''); } else { mangaLastPrune.set(new Date().getTime().toString()); manga.set(''); } mediaCache = ''; } } if (mediaCache !== undefined && mediaCache !== '') { return JSON.parse(mediaCache); } const userIdResponse = await ( await fetch('https://graphql.anilist.co', { method: 'POST', headers: { Authorization: `${anilistAuthorisation.tokenType} ${anilistAuthorisation.accessToken}`, 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify({ query: `{ MediaListCollection(userId: ${userIdentity.id}, type: ${ type === Type.Anime ? 'ANIME' : 'MANGA' }, status_not_in: [ COMPLETED ]) { lists { entries { media { id status type episodes format title { romaji english native } nextAiringEpisode { episode timeUntilAiring } mediaListEntry { progress } startDate { year } } } } } }` }) }) ).json(); if (mediaCache === '') { if (type === Type.Anime) { anime.set(JSON.stringify(userIdResponse['data']['MediaListCollection']['lists'])); } else { manga.set(JSON.stringify(userIdResponse['data']['MediaListCollection']['lists'])); } } return userIdResponse['data']['MediaListCollection']['lists']; };