fix: show actionable error message when API quota is exceeded

pull/270/head
dessant 4 years ago
parent e927330f43
commit d01968d5b4

@ -521,6 +521,11 @@
"description": "Error message." "description": "Error message."
}, },
"error_apiQuotaExceeded": {
"message": "API quota exceeded. Try again later, or visit the extension's options and switch to a different service.",
"description": "Error message."
},
"error_scriptsNotAllowed": { "error_scriptsNotAllowed": {
"message": "Content scripts are not allowed on this page.", "message": "Content scripts are not allowed on this page.",
"description": "Error message." "description": "Error message."

@ -267,6 +267,8 @@ async function getWitSpeechApiKey(speechService, language) {
} }
async function getWitSpeechApiResult(apiKey, audioContent) { async function getWitSpeechApiResult(apiKey, audioContent) {
const result = {};
const rsp = await fetch('https://api.wit.ai/speech?v=20200513', { const rsp = await fetch('https://api.wit.ai/speech?v=20200513', {
referrer: '', referrer: '',
mode: 'cors', mode: 'cors',
@ -278,14 +280,19 @@ async function getWitSpeechApiResult(apiKey, audioContent) {
}); });
if (rsp.status !== 200) { if (rsp.status !== 200) {
throw new Error(`API response: ${rsp.status}, ${await rsp.text()}`); if (rsp.status === 429) {
result.errorId = 'error_apiQuotaExceeded';
} else {
throw new Error(`API response: ${rsp.status}, ${await rsp.text()}`);
}
} else {
const data = (await rsp.json()).text;
if (data) {
result.text = data.trim();
}
} }
const result = (await rsp.json()).text; return result;
if (result) {
return result.trim();
}
} }
async function getIbmSpeechApiResult(apiUrl, apiKey, audioContent, language) { async function getIbmSpeechApiResult(apiUrl, apiKey, audioContent, language) {
@ -363,14 +370,25 @@ async function transcribeAudio(audioUrl, lang) {
return; return;
} }
solution = await getWitSpeechApiResult(apiKey, audioContent); const result = await getWitSpeechApiResult(apiKey, audioContent);
if (result.errorId) {
showNotification({messageId: result.errorId});
return;
}
solution = result.text;
if (!solution && language !== 'english' && tryEnglishSpeechModel) { if (!solution && language !== 'english' && tryEnglishSpeechModel) {
const apiKey = await getWitSpeechApiKey(speechService, 'english'); const apiKey = await getWitSpeechApiKey(speechService, 'english');
if (!apiKey) { if (!apiKey) {
showNotification({messageId: 'error_missingApiKey'}); showNotification({messageId: 'error_missingApiKey'});
return; return;
} }
solution = await getWitSpeechApiResult(apiKey, audioContent); const result = await getWitSpeechApiResult(apiKey, audioContent);
if (result.errorId) {
showNotification({messageId: result.errorId});
return;
}
solution = result.text;
} }
} else if (speechService === 'googleSpeechApi') { } else if (speechService === 'googleSpeechApi') {
const {googleSpeechApiKey: apiKey} = await storage.get( const {googleSpeechApiKey: apiKey} = await storage.get(

Loading…
Cancel
Save