art cache

This commit is contained in:
Ondrej Zara 2019-03-21 10:53:38 +01:00
parent 28b8d4ad84
commit ecbb7e3d97

View file

@ -3,6 +3,16 @@ import * as parser from "./parser.js";
let cache = {}; let cache = {};
const SIZE = 64; const SIZE = 64;
const MIME = "image/jpeg";
const STORAGE_PREFIX = `art-${SIZE}` ;
function store(key, data) {
localStorage.setItem(`${STORAGE_PREFIX}-${key}`, data);
}
function load(key) {
return localStorage.getItem(`${STORAGE_PREFIX}-${key}`);
}
async function getImageData(songUrl) { async function getImageData(songUrl) {
let data = []; let data = [];
@ -26,20 +36,25 @@ async function bytesToImage(bytes) {
}); });
} }
async function resize(image) { function resize(image) {
let canvas = document.createElement("canvas"); let canvas = document.createElement("canvas");
canvas.width = SIZE; canvas.width = SIZE;
canvas.height = SIZE; canvas.height = SIZE;
let ctx = canvas.getContext("2d"); let ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, SIZE, SIZE); ctx.drawImage(image, 0, 0, SIZE, SIZE);
return canvas;
return new Promise(resolve => canvas.toBlob(resolve));
} }
export async function get(artist, album, songUrl = null) { export async function get(artist, album, songUrl = null) {
let key = `${artist}-${album}`; let key = `${artist}-${album}`;
if (key in cache) { return cache[key]; } if (key in cache) { return cache[key]; }
let loaded = await load(key);
if (loaded) {
cache[key] = loaded;
return loaded;
}
if (!songUrl) { return null; } if (!songUrl) { return null; }
// promise to be returned in the meantime // promise to be returned in the meantime
@ -51,8 +66,8 @@ export async function get(artist, album, songUrl = null) {
let data = await getImageData(songUrl); let data = await getImageData(songUrl);
let bytes = new Uint8Array(data); let bytes = new Uint8Array(data);
let image = await bytesToImage(bytes); let image = await bytesToImage(bytes);
let blob = await resize(image); let url = resize(image).toDataURL(MIME);
let url = URL.createObjectURL(blob); store(key, url);
cache[key] = url; cache[key] = url;
resolve(url); resolve(url);
} catch (e) { } catch (e) {