jisho.org audio support

This commit is contained in:
Alex Yatskov 2017-08-15 21:36:30 -07:00
parent e079e5f252
commit e19933f980
6 changed files with 42 additions and 3 deletions

View File

@ -127,3 +127,6 @@ async function apiCommandExec(command) {
}
}
async function apiAudioGetUrl(definition, source) {
return audioBuildUrl(definition, source);
}

View File

@ -110,6 +110,10 @@ class Backend {
commandExec: ({command, callback}) => {
forward(apiCommandExec(command), callback);
},
audioGetUrl: ({definition, source, callback}) => {
forward(apiAudioGetUrl(definition, source), callback);
}
};

View File

@ -48,6 +48,7 @@
<option value="disabled">Disabled</option>
<option value="jpod101">JapanesePod101</option>
<option value="jpod101-alternate">JapanesePod101 (alternate)</option>
<option value="jisho">Jisho</option>
</select>
</div>

View File

@ -52,3 +52,7 @@ function apiTemplateRender(template, data) {
function apiCommandExec(command) {
return utilInvoke('commandExec', {command});
}
function apiAudioGetUrl(definition, source) {
return utilInvoke('audioGetUrl', {definition, source});
}

View File

@ -79,7 +79,35 @@ async function audioBuildUrl(definition, mode, cache={}) {
}
}
});
} else {
} else if (mode === 'jisho') {
return new Promise((resolve, reject) => {
const response = cache[definition.expression];
if (response) {
resolve(response);
} else {
const xhr = new XMLHttpRequest();
xhr.open('GET', `http://jisho.org/search/${definition.expression}`);
xhr.addEventListener('error', () => reject('failed to scrape audio data'));
xhr.addEventListener('load', () => {
cache[definition.expression] = xhr.responseText;
resolve(xhr.responseText);
});
xhr.send();
}
}).then(response => {
try {
const dom = new DOMParser().parseFromString(response, 'text/html');
const audio = dom.getElementById(`audio_${definition.expression}:${definition.reading}`);
if (audio) {
return audio.getElementsByTagName('source').item(0).getAttribute('src');
}
} catch (e) {
// NOP
}
});
}
else {
return Promise.resolve();
}
}

View File

@ -27,7 +27,6 @@ class Display {
this.sequence = 0;
this.index = 0;
this.audioCache = {};
this.responseCache = {};
$(document).keydown(this.onKeyDown.bind(this));
}
@ -368,7 +367,7 @@ class Display {
try {
this.spinner.show();
let url = await audioBuildUrl(definition, this.options.general.audioSource, this.responseCache);
let url = await apiAudioGetUrl(definition, this.options.general.audioSource);
if (!url) {
url = '/mixed/mp3/button.mp3';
}