Created
February 4, 2025 08:40
-
-
Save akramsaouri/8e4a243b26509ea737d2cf66c660a3a3 to your computer and use it in GitHub Desktop.
Fetches and sums up the total hours you’ve spent watching anime from your Kitsu library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fetch from 'node-fetch'; | |
async function getTotalHoursWatched(userId) { | |
let page = `https://kitsu.io/api/edge/library-entries?filter[userId]=${userId}&include=anime&page[limit]=20`; | |
let totalMinutes = 0; | |
let totalEpisodes = 0; | |
const processedAnimeIds = new Set(); | |
let nullAnimeDataCount = 0; | |
while (page) { | |
const response = await fetch(page); | |
const data = await response.json(); | |
const entries = data.data; | |
const includedAnime = data.included || []; | |
for (let entry of entries) { | |
const animeData = entry.relationships.anime.data; | |
if (!animeData) { | |
nullAnimeDataCount++; | |
continue; | |
} | |
const animeId = animeData.id; | |
const anime = includedAnime.find(a => a.id === animeId); | |
if (anime) { | |
const episodeLength = anime.attributes.episodeLength || 0; | |
const progress = entry.attributes.progress || 0; | |
totalMinutes += episodeLength * progress; | |
totalEpisodes += progress; | |
processedAnimeIds.add(animeId); | |
} | |
} | |
page = data.links && data.links.next ? data.links.next : null; | |
} | |
if (nullAnimeDataCount > 0) { | |
console.warn(`${nullAnimeDataCount} entries had null anime data`); | |
} | |
return { | |
hoursWatched: totalMinutes / 60, | |
totalAnime: processedAnimeIds.size, | |
totalEpisodes | |
}; | |
} | |
getTotalHoursWatched('USER_ID').then(result => { | |
console.log(result); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment