From 520f45cab8c36c1ed0ed5355aca77b034d1619ef Mon Sep 17 00:00:00 2001 From: r-freeman Date: Thu, 2 Feb 2023 21:47:35 +0000 Subject: [PATCH] Added spotify minutes listened metric to dashboard --- .env.example | 3 ++- lib/dashboard.ts | 12 ++++++++++-- lib/statsfm.ts | 25 +++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 3 deletions(-) create mode 100644 lib/statsfm.ts diff --git a/.env.example b/.env.example index 74cad7f..95f210c 100644 --- a/.env.example +++ b/.env.example @@ -5,4 +5,5 @@ NEXT_PUBLIC_SITE_URL=https://example.com DATABASE_URL= SHADOW_DATABASE_URL= GITHUB_ACCESS_TOKEN= -GITHUB_USERNAME= \ No newline at end of file +GITHUB_USERNAME= +STATSFM_USERNAME= \ No newline at end of file diff --git a/lib/dashboard.ts b/lib/dashboard.ts index 91b86c2..87a28a3 100644 --- a/lib/dashboard.ts +++ b/lib/dashboard.ts @@ -2,6 +2,7 @@ import {getTotalFollowers, getTotalRepos, getTotalStars} from '@/lib/github' import {getAllArticles} from '@/lib/getAllArticles' import {getTopArtist, getTopGenre} from '@/lib/spotify' import {getViews} from '@/lib/views' +import {getStats} from '@/lib/statsfm' import {Metric} from '@/types' export async function getDashboardData() { @@ -14,12 +15,19 @@ export async function getDashboardData() { const totalArticles = (await getAllArticles()).length const totalArticleViews = (await getViews()).views const topArtist = await getTopArtist() - const topGenre = await getTopGenre() + const {genre} = await getTopGenre() + const {minutesListened} = await getStats() const metrics: Metric[] = [ + { + title: "Minutes listened", + value: minutesListened, + group: "Spotify", + href: "https://open.spotify.com/?" + }, { title: "Top genre", - value: topGenre.genre, + value: genre, group: "Spotify", href: "https://open.spotify.com/?" }, diff --git a/lib/statsfm.ts b/lib/statsfm.ts new file mode 100644 index 0000000..93f038f --- /dev/null +++ b/lib/statsfm.ts @@ -0,0 +1,25 @@ +import fetch from 'node-fetch' + +const STATSFM_USERNAME = process.env.STATSFM_USERNAME +const STATSFM_LIFETIME_STATS = `https://beta-api.stats.fm/api/v1/users/${STATSFM_USERNAME}/streams/stats?range=lifetime` + +type StatsFmResponse = { + items: { + durationMs: number + } +} + +export const getStats = async () => { + const response = await fetch(STATSFM_LIFETIME_STATS, { + method: 'GET', + headers: { + 'Accept': 'application/json' + } + }).then(r => r.json()) as StatsFmResponse + + const minutesListened = ((response.items.durationMs / 1000) / 60).toFixed(0) + + return { + minutesListened + } +} \ No newline at end of file