From d01968d5b46694ea84ba643a95ba29ce46e52c31 Mon Sep 17 00:00:00 2001 From: dessant Date: Mon, 12 Oct 2020 15:23:26 +0300 Subject: [PATCH] fix: show actionable error message when API quota is exceeded --- src/_locales/en/messages.json | 5 +++++ src/background/main.js | 34 ++++++++++++++++++++++++++-------- 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/src/_locales/en/messages.json b/src/_locales/en/messages.json index 131042b..ce2281f 100644 --- a/src/_locales/en/messages.json +++ b/src/_locales/en/messages.json @@ -521,6 +521,11 @@ "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": { "message": "Content scripts are not allowed on this page.", "description": "Error message." diff --git a/src/background/main.js b/src/background/main.js index f6cbef1..064a4c3 100644 --- a/src/background/main.js +++ b/src/background/main.js @@ -267,6 +267,8 @@ async function getWitSpeechApiKey(speechService, language) { } async function getWitSpeechApiResult(apiKey, audioContent) { + const result = {}; + const rsp = await fetch('https://api.wit.ai/speech?v=20200513', { referrer: '', mode: 'cors', @@ -278,14 +280,19 @@ async function getWitSpeechApiResult(apiKey, audioContent) { }); 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; - - if (result) { - return result.trim(); - } + return result; } async function getIbmSpeechApiResult(apiUrl, apiKey, audioContent, language) { @@ -363,14 +370,25 @@ async function transcribeAudio(audioUrl, lang) { 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) { const apiKey = await getWitSpeechApiKey(speechService, 'english'); if (!apiKey) { showNotification({messageId: 'error_missingApiKey'}); 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') { const {googleSpeechApiKey: apiKey} = await storage.get(