feat: last.fm -> apple music

This commit is contained in:
Cory Dransfeldt 2023-06-20 19:15:01 -07:00
parent c2905fc9fa
commit bd2aa7439c
No known key found for this signature in database
9 changed files with 280 additions and 212 deletions

View file

@ -0,0 +1,20 @@
const EleventyFetch = require('@11ty/eleventy-fetch')
module.exports = async function () {
const APPLE_BEARER = process.env.API_BEARER_APPLE_MUSIC
const APPLE_TOKEN = process.env.API_TOKEN_APPLE_MUSIC
const url = `https://api.music.apple.com/v1/me/history/heavy-rotation`
const res = EleventyFetch(url, {
duration: '1h',
type: 'json',
fetchOptions: {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${APPLE_BEARER}`,
'music-user-token': `${APPLE_TOKEN}`,
},
},
}).catch()
const rotation = await res
return rotation.data
}

62
src/_data/recentTracks.js Normal file
View file

@ -0,0 +1,62 @@
const { AssetCache } = require('@11ty/eleventy-fetch')
const sortTrim = (array, length = 5) =>
Object.values(array)
.sort((a, b) => b.plays - a.plays)
.splice(0, length)
module.exports = async function () {
const APPLE_BEARER = process.env.API_BEARER_APPLE_MUSIC
const APPLE_TOKEN = process.env.API_TOKEN_APPLE_MUSIC
const PAGE_SIZE = 30
let CURRENT_PAGE = 0
const PAGES = 4
let res = []
const asset = new AssetCache('recent_tracks_data')
if (asset.isCacheValid('1h')) return await asset.getCachedValue()
while (CURRENT_PAGE < PAGES) {
const URL = `https://api.music.apple.com/v1/me/recent/played/tracks?limit=${PAGE_SIZE}&offset=${
PAGE_SIZE * CURRENT_PAGE
}`
const tracks = await fetch(URL, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${APPLE_BEARER}`,
'music-user-token': `${APPLE_TOKEN}`,
},
})
.then((data) => data.json())
.catch()
res = [...res, ...tracks.data]
CURRENT_PAGE++
}
const response = {
artists: {},
tracks: {},
}
res.forEach((track) => {
// aggregate artists
if (!response.artists[track.attributes.artistName]) {
response.artists[track.attributes.artistName] = {
name: track.attributes.artistName,
plays: 1,
}
} else {
response.artists[track.attributes.artistName].plays++
}
// aggregate tracks
if (!response.tracks[track.attributes.name]) {
response.tracks[track.attributes.name] = {
name: track.attributes.name,
plays: 1,
}
} else {
response.tracks[track.attributes.name].plays++
}
})
response.artists = sortTrim(response.artists, 4)
response.tracks = sortTrim(response.tracks)
await asset.save(response, 'json')
return response
}

View file

@ -8,7 +8,7 @@
"fastmail": "mailto:hi@coryd.dev",
"github": "https://github.com/cdransf",
"mastodon": "https://social.lol/@cory",
"lastfm": "https://last.fm/user/cdme_",
"applemusic": "https://music.apple.com/profile/cdransf",
"listenbrainz": "https://listenbrainz.org/user/cdransf/",
"instapaper": "https://www.instapaper.com/p/coryd",
"letterboxd": "https://letterboxd.com/cdme",