feat: simplify scrobbling

This commit is contained in:
Cory Dransfeldt 2024-04-23 14:11:17 -07:00
parent 0a27398712
commit 11e4c511ec
No known key found for this signature in database
3 changed files with 8 additions and 69 deletions

View file

@ -47,96 +47,35 @@ export default async (request) => {
const trackNumber = payload['Metadata']['index'] const trackNumber = payload['Metadata']['index']
const timestamp = DateTime.now() const timestamp = DateTime.now()
const artistsMap = await artists.get('artists-map', { type: 'json' }) const artistsMap = await artists.get('artists-map', { type: 'json' })
const albumsMap = await albums.get('albums-map', { type: 'json' })
const artistSanitizedKey = `${sanitizeMediaString(artist).replace(/\s+/g, '-').toLowerCase()}` const artistSanitizedKey = `${sanitizeMediaString(artist).replace(/\s+/g, '-').toLowerCase()}`
const albumSanitizedKey = `${sanitizeMediaString(artist).replace(/\s+/g, '-').toLowerCase()}-${sanitizeMediaString(album.replace(/[:\/\\,'']+/g const albumSanitizedKey = `${sanitizeMediaString(artist).replace(/\s+/g, '-').toLowerCase()}-${sanitizeMediaString(album.replace(/[:\/\\,'']+/g
, '').replace(/\s+/g, '-').toLowerCase())}` , '').replace(/\s+/g, '-').toLowerCase())}`
let artistInfo = artistsMap[artistSanitizedKey]
// if there is no artist blob, populate one
if (!artistsMap[artistSanitizedKey]) {
const artistRes = await fetch(
`https://ws.audioscrobbler.com/2.0/?method=artist.getInfo&api_key=${MUSIC_KEY}&artist=${sanitizeMediaString(artist).replace(/\s+/g, '+').toLowerCase()}&format=json`,
{
type: "json",
}
).then((data) => {
if (data.ok) return data.json()
throw new Error('Something went wrong with the Last.fm endpoint.');
}).catch(err => {
console.log(err);
return {}
});
const artistData = artistRes['artist'];
const mbid = artistData['mbid'] || ''
const genreUrl = `https://musicbrainz.org/ws/2/artist/${mbid}?inc=aliases+genres&fmt=json`;
const genreRes = await fetch(genreUrl, {
type: "json",
}).then((data) => {
if (data.ok) return data.json()
throw new Error('Something went wrong with the MusicBrainz endpoint.');
}).catch(err => {
console.log(err);
return []
});
const genre = genreRes['genres']?.sort((a, b) => b.count - a.count)[0]?.['name'] || '';
const artistObj = {
mbid,
genre,
image: `https://coryd.dev/.netlify/images/?url=https://f001.backblazeb2.com/file/coryd-dev-images/artists/${sanitizeMediaString(artist).replace(/\s+/g, '-').toLowerCase()}.jpg&w=320&h=320&fit=fill`
}
artistInfo = artistObj
artistsMap[artistSanitizedKey] = artistObj
await artists.setJSON('artists-map', artistsMap)
}
// if there is no album blob, populate one
if (!albumsMap[albumSanitizedKey]) {
const albumRes = await fetch(
`https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=${MUSIC_KEY}&artist=${sanitizeMediaString(artist).replace(/\s+/g, '+').toLowerCase()}&album=${sanitizeMediaString(album).replace(/\s+/g, '+').toLowerCase()}&format=json`,
{
type: "json",
}
).then((data) => {
if (data.ok) return data.json()
throw new Error('Something went wrong with the Last.fm endpoint.');
}).catch(err => {
console.log(err);
return {}
});
const mbid = albumRes['album']['mbid'] || ''
const albumObj = {
mbid,
image: `https://coryd.dev/.netlify/images/?url=https://f001.backblazeb2.com/file/coryd-dev-images/albums/${sanitizeMediaString(artist).replace(/\s+/g, '-').toLowerCase()}-${sanitizeMediaString(album.replace(/[:\/\\,'']+/g
, '').replace(/\s+/g, '-').toLowerCase())}.jpg&w=320&h=320&fit=fill`
}
albumsMap[albumSanitizedKey] = albumObj
await albums.setJSON('albums-map', albumsMap)
}
// scrobble logic
const trackScrobbleData = { const trackScrobbleData = {
track, track,
album, album,
artist, artist,
trackNumber, trackNumber,
timestamp, timestamp,
genre: artistInfo?.['genre'] || '' genre: artistsMap?.['genre'] || ''
} }
const scrobbleData = await scrobbles.get(`${weekKey()}`, { type: 'json'}) const scrobbleData = await scrobbles.get(`${weekKey()}`, { type: 'json'})
const windowData = await scrobbles.get('window', { type: 'json'}) const windowData = await scrobbles.get('window', { type: 'json'})
const artistUrl = (artistInfo?.['mbid'] && artistInfo?.['mbid'] !== '') ? `http://musicbrainz.org/artist/${artistInfo?.['mbid']}` : `https://musicbrainz.org/search?query=${artist.replace( const artistUrl = (artistsMap?.['mbid'] && artistsMap?.['mbid'] !== '') ? `http://musicbrainz.org/artist/${artistsMap?.['mbid']}` : `https://musicbrainz.org/search?query=${artist.replace(
/\s+/g, /\s+/g,
'+' '+'
)}&type=artist` )}&type=artist`
await scrobbles.setJSON('now-playing', {...trackScrobbleData, ...{ url: artistUrl }}) await scrobbles.setJSON('now-playing', {...trackScrobbleData, ...{ url: artistUrl }})
let scrobbleUpdate = scrobbleData let scrobbleUpdate = scrobbleData
let windowUpdate = windowData; let windowUpdate = windowData;
if (scrobbleUpdate?.['data']) scrobbleUpdate['data'].push(trackScrobbleData) if (scrobbleUpdate?.['data']) scrobbleUpdate['data'].push(trackScrobbleData)
if (!scrobbleUpdate?.['data']) scrobbleUpdate = { data: [trackScrobbleData] } if (!scrobbleUpdate?.['data']) scrobbleUpdate = { data: [trackScrobbleData] }
if (windowData?.['data']) windowUpdate['data'].push(trackScrobbleData) if (windowData?.['data']) windowUpdate['data'].push(trackScrobbleData)
if (!windowData?.['data']) windowUpdate = { data: [trackScrobbleData] } if (!windowData?.['data']) windowUpdate = { data: [trackScrobbleData] }
windowUpdate = { data: filterOldScrobbles(windowUpdate.data) } windowUpdate = { data: filterOldScrobbles(windowUpdate.data) }
await scrobbles.setJSON(`${weekKey()}`, scrobbleUpdate) await scrobbles.setJSON(`${weekKey()}`, scrobbleUpdate)
await scrobbles.setJSON('window', windowUpdate) await scrobbles.setJSON('window', windowUpdate)
} }

View file

@ -1,6 +1,6 @@
{ {
"name": "coryd.dev", "name": "coryd.dev",
"version": "12.8.4", "version": "12.9.0",
"description": "The source for my personal site. Built using 11ty.", "description": "The source for my personal site. Built using 11ty.",
"type": "module", "type": "module",
"scripts": { "scripts": {

View file

@ -57,7 +57,7 @@ export const buildChart = (tracks, artists, albums, nowPlaying = {}) => {
artist: artistCapitalization(track['artist']), artist: artistCapitalization(track['artist']),
plays: 1, plays: 1,
mbid: albums[albumKey]?.['mbid'] || '', mbid: albums[albumKey]?.['mbid'] || '',
url: (albums[albumKey]?.['mbid'] && albums[albumSanitizedKey(artistCapitalization(track['artist']), track['artist'], track['album'])]?.['mbid'] !== '') ? `https://musicbrainz.org/release-group/${albums[albumKey]?.['mbid']}` : `https://musicbrainz.org/taglookup/index?tag-lookup.artist=${track['artist'].replace(/\s+/g, '+')}&tag-lookup.release=${track['album'].replace(/\s+/g, '+')}`, url: (albums[albumKey]?.['mbid'] && albums[albumSanitizedKey(artistCapitalization(track['artist']), track['artist'], track['album'])]?.['mbid'] !== '') ? `https://musicbrainz.org/release/${albums[albumKey]?.['mbid']}` : `https://musicbrainz.org/taglookup/index?tag-lookup.artist=${track['artist'].replace(/\s+/g, '+')}&tag-lookup.release=${track['album'].replace(/\s+/g, '+')}`,
image: albums[albumKey]?.['image'] || `https://coryd.dev/.netlify/images/?url=https://f001.backblazeb2.com/file/coryd-dev-images/albums/${sanitizeMediaString(track['artist']).replace(/\s+/g, '-').toLowerCase()}-${sanitizeMediaString(track['album'].replace(/[:\/\\,'']+/g image: albums[albumKey]?.['image'] || `https://coryd.dev/.netlify/images/?url=https://f001.backblazeb2.com/file/coryd-dev-images/albums/${sanitizeMediaString(track['artist']).replace(/\s+/g, '-').toLowerCase()}-${sanitizeMediaString(track['album'].replace(/[:\/\\,'']+/g
, '').replace(/\s+/g, '-').toLowerCase())}.jpg&fit=cover&w=320&h=320`, , '').replace(/\s+/g, '-').toLowerCase())}.jpg&fit=cover&w=320&h=320`,
type: 'album' type: 'album'