stow last.fm album art entries in localStorage
This commit is contained in:
parent
3c8f6bb199
commit
ac84309134
|
@ -1,22 +1,55 @@
|
|||
export function fetch_album_art(album, artist, img, small) {
|
||||
fetch(`https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=5460c3381d64e7e9908b9fdfc5559747&format=json&album=${encodeURIComponent(album)}&artist=${encodeURIComponent(artist)}`)
|
||||
.then(r => r.json())
|
||||
.then(lastfm => {
|
||||
if (!lastfm.error) {
|
||||
const arts = lastfm.album.image;
|
||||
const art = small ? arts[1] : arts.find(({size}) => size === 'extralarge') ?? arts.find(({'#text': url}) => url.includes('300x300')) ?? arts[arts.length - 1];
|
||||
const url = art['#text'];
|
||||
if (url) {
|
||||
img.src = url;
|
||||
} else if (small) {
|
||||
img.src = '../../img/disc.webp';
|
||||
function make_key(artist, album) {
|
||||
return `${album}\n${artist}`;
|
||||
}
|
||||
|
||||
async function get_lastfm_entry(artist, album) {
|
||||
const local_storage_key = make_key(artist, album);
|
||||
let entry = null;
|
||||
try {
|
||||
const json = window.localStorage.getItem(local_storage_key);
|
||||
entry = JSON.parse(json);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
if (entry) {
|
||||
return entry;
|
||||
} else {
|
||||
return fetch(`https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=5460c3381d64e7e9908b9fdfc5559747&format=json&album=${encodeURIComponent(album)}&artist=${encodeURIComponent(artist)}`)
|
||||
.then(r => r.json())
|
||||
.then(lastfm => {
|
||||
if (lastfm.error) {
|
||||
throw lastfm.error;
|
||||
} else {
|
||||
img.style.opacity = 0;
|
||||
const entry = lastfm.album.image;
|
||||
window.localStorage.setItem(local_storage_key, JSON.stringify(entry));
|
||||
return entry;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function fetch_album_art(album, artist, img, small, is_retry) {
|
||||
try {
|
||||
const arts = await get_lastfm_entry(artist, album);
|
||||
const art = small ? arts[1] : arts.find(({size}) => size === 'extralarge') ?? arts.find(({'#text': url}) => url.includes('300x300')) ?? arts[arts.length - 1];
|
||||
const url = art['#text'];
|
||||
if (url) {
|
||||
img.src = url;
|
||||
img.addEventListener('error', () => {
|
||||
window.localStorage.removeItem(make_key(artist, album));
|
||||
if (!is_retry) {
|
||||
fetch_album_art(album, artist, img, small, true);
|
||||
}
|
||||
});
|
||||
} else if (small) {
|
||||
img.src = '../../img/disc.webp';
|
||||
} else {
|
||||
img.style.opacity = 0;
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
img.style.opacity = 0;
|
||||
}
|
||||
}
|
||||
|
||||
for (const img of document.querySelectorAll('img[data-album][data-artist]')) {
|
||||
|
|
Loading…
Reference in New Issue