audio-vis/raw/worker/id3.js
2020-08-06 23:44:37 +02:00

86 lines
2.8 KiB
JavaScript

self.importScripts('jsmediatags.min.js');
class Tagger {
constructor(worker) {
this.db = new Database("SongLib", 1);
}
static prepareName(data) {
let name = data.name || '';
return name.replace(/[^\w\s]/gi, '').split(" ").join("")
}
init() {
eventHandler.addEvent('getData', this.getData.bind(this));
eventHandler.addEvent('removeData', this.getData.bind(this));
eventHandler.addEvent('setData', this.getData.bind(this));
eventHandler.addEvent('dbReady-SongLib', this.ready.bind(this));
eventHandler.addEvent('dbUpgrade-SongLib', this.upgrade.bind(this));
}
async getData(data) {
let key = Tagger.prepareName(data),
newData = await this.db.get(key, 'songs'),
handlerName = data.force ? 'id3-request-force' : 'id3-request';
if (newData) {
newData['index'] = data['index'];
eventHandler.sendData(handlerName, 'success', newData);
} else {
this.parseData(data, key).then(r => {
r['index'] = data['index'];
eventHandler.sendData(handlerName, 'success', r);
});
eventHandler.sendData(handlerName, 'waiting', data);
}
}
async removeData(data) {
let key = Tagger.prepareName(data),
newData = await this.db.remove(key, 'songs');
eventHandler.sendData('id3-remove', 'success', newData);
}
async setData(data, key) {
let newData = await this.db.set(key, data, 'songs');
eventHandler.sendData('id3-set', 'success', newData);
}
ready(data) {
console.log("[ID3] > Song Database Ready");
eventHandler.sendData('id3-ready', "startup", "");
}
upgrade(data) {
let db = data.result,
songs = db.createObjectStore("songs", {keyPath: 'key'});
songs.createIndex("name", "name", {unique: false});
}
//if not found in key-value storage read it! this take some time so this is async!
async parseData(data, key) {
let tag = await new Promise((resolve, reject) => {
new jsmediatags.Reader(data.file)
.read({
onSuccess: (tag) => {
resolve(tag);
},
onError: (error) => {
console.log(`[ID3] > Error Parsing Data!`);
resolve({
tags: {}
});
}
});
})
let tags = tag.tags,
values = {
title: tags.title || data.name,
artist: tags.artist || 'VA',
genre: tags.genre || 'Unknown',
year: tags.year || 1970,
key: key
};
await this.setData(values, key);
return values;
}
}