diff --git a/package-lock.json b/package-lock.json index c66fa61..4a9ca2b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1421,6 +1421,14 @@ "integrity": "sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA==", "dev": true }, + "axios": { + "version": "0.26.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-0.26.0.tgz", + "integrity": "sha512-lKoGLMYtHvFrPVt3r+RBMp9nh34N0M8zEfCWqdWZx6phynIEhQqAdydpyBAAG211zlhX9Rgu08cOamy6XjE5Og==", + "requires": { + "follow-redirects": "^1.14.8" + } + }, "babel-code-frame": { "version": "6.26.0", "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", @@ -3232,6 +3240,11 @@ } } }, + "follow-redirects": { + "version": "1.14.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.9.tgz", + "integrity": "sha512-MQDfihBQYMcyy5dhRDJUHcw7lb2Pv/TuE6xP1vyraLukNDHKbDxDNaOE3NbCAdKQApno+GPRyo1YAp89yCjK4w==" + }, "forever-agent": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", diff --git a/package.json b/package.json index 8b16d11..68f3c51 100644 --- a/package.json +++ b/package.json @@ -2,6 +2,7 @@ "name": "simple-translate", "version": "0.0.0", "dependencies": { + "axios": "^0.26.0", "browser-info": "^1.2.0", "loglevel": "^1.6.1", "query-string": "^6.1.0", diff --git a/src/common/getErrorMessage.js b/src/common/getErrorMessage.js deleted file mode 100644 index 2bf585e..0000000 --- a/src/common/getErrorMessage.js +++ /dev/null @@ -1,17 +0,0 @@ -import browser from "webextension-polyfill"; - -export default statusText => { - let errorMessage = ""; - switch (statusText) { - case "Network Error": - errorMessage = browser.i18n.getMessage("networkError"); - break; - case "Service Unavailable": - errorMessage = browser.i18n.getMessage("unavailableError"); - break; - default: - errorMessage = `${browser.i18n.getMessage("unknownError")} [${statusText}]`; - break; - } - return errorMessage; -}; diff --git a/src/common/translate.js b/src/common/translate.js index cca7932..755d7e9 100644 --- a/src/common/translate.js +++ b/src/common/translate.js @@ -1,4 +1,5 @@ import log from "loglevel"; +import axios from "axios"; let translationHistory = []; const logDir = "common/translate"; @@ -23,59 +24,62 @@ const setHistory = (sourceWord, sourceLang, targetLang, formattedResult) => { }); }; -const sendRequest = (word, sourceLang, targetLang) => { - log.log(logDir, "sendRequest()"); +const sendRequest = async (word, sourceLang, targetLang) => { const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=${sourceLang}&tl=${targetLang}&dt=t&dt=bd&dj=1&q=${encodeURIComponent( word )}`; - const xhr = new XMLHttpRequest(); - xhr.responseType = "json"; - xhr.open("GET", url); - xhr.send(); + const result = await axios.get(url).catch(error => error.response); - return new Promise((resolve, reject) => { - xhr.onload = () => { - resolve(xhr); - }; - xhr.onerror = () => { - resolve(xhr); - }; - }); -}; - -const formatResult = result => { const resultData = { resultText: "", candidateText: "", sourceLanguage: "", percentage: 0, - statusText: "" + isError: false, + errorMessage: "" }; - if (result.status === 0) resultData.statusText = "Network Error"; - else if (result.status === 200) resultData.statusText = "OK"; - else if (result.status === 429) resultData.statusText = "Service Unavailable"; - else if (result.status === 503) resultData.statusText = "Service Unavailable"; - else resultData.statusText = result.statusText || result.status; + if (!result || result?.status !== 200) { + resultData.isError = true; - if (resultData.statusText !== "OK") { - log.error(logDir, "formatResult()", resultData); + if (!result || result.status === 0) resultData.errorMessage = browser.i18n.getMessage("networkError"); + else if (result.status === 429 || result.status === 503) resultData.errorMessage = browser.i18n.getMessage("unavailableError"); + else resultData.errorMessage = `${browser.i18n.getMessage("unknownError")} [${result?.status} ${result?.statusText}]`; + + log.error(logDir, "sendRequest()", result); return resultData; } - resultData.sourceLanguage = result.response.src; - resultData.percentage = result.response.ld_result.srclangs_confidences[0]; - resultData.resultText = result.response.sentences.map(sentence => sentence.trans).join(""); - if (result.response.dict) { - resultData.candidateText = result.response.dict + resultData.sourceLanguage = result.data.src; + resultData.percentage = result.data.ld_result.srclangs_confidences[0]; + resultData.resultText = result.data.sentences.map(sentence => sentence.trans).join(""); + if (result.data.dict) { + resultData.candidateText = result.data.dict .map(dict => `${dict.pos}${dict.pos != "" ? ": " : ""}${dict.terms.join(", ")}\n`) .join(""); } - log.log(logDir, "formatResult()", resultData); + log.log(logDir, "sendRequest()", resultData); return resultData; }; +const sendRequestToDeepL = async (word, sourceLang, targetLang) => { + log.log(logDir, "sendRequestToDeepL()"); + + let params = new URLSearchParams(); + + const key = "f5a2c02c-7871-af5c-0d6a-244a9e6d4a1f:fx"; + params.append("auth_key", key); + params.append("text", word); + params.append("target_lang", "ja"); + + const url = "https://api-free.deepl.com/v2/translate"; + + const res = await axios.post(url, params).catch(e => e.response); + console.log("!!!!!!!!!!!!!!!", res); +}; + + export default async (sourceWord, sourceLang = "auto", targetLang) => { log.log(logDir, "tranlate()", sourceWord, targetLang); sourceWord = sourceWord.trim(); @@ -92,7 +96,6 @@ export default async (sourceWord, sourceLang = "auto", targetLang) => { if (history) return history.result; const result = await sendRequest(sourceWord, sourceLang, targetLang); - const formattedResult = formatResult(result); - setHistory(sourceWord, sourceLang, targetLang, formattedResult); - return formattedResult; + setHistory(sourceWord, sourceLang, targetLang, result); + return result; }; diff --git a/src/content/components/TranslateContainer.js b/src/content/components/TranslateContainer.js index 34a530a..f680cab 100644 --- a/src/content/components/TranslateContainer.js +++ b/src/content/components/TranslateContainer.js @@ -21,8 +21,7 @@ const matchesTargetLang = async selectedText => { //先頭100字を翻訳にかけて判定 const partSelectedText = selectedText.substring(0, 100); const result = await translateText(partSelectedText); - const isError = result.statusText !== "OK"; - if (isError) return false; + if (result.isError) return false; const isNotText = result.percentage === 0; if (isNotText) return true; @@ -42,7 +41,8 @@ export default class TranslateContainer extends Component { currentLang: getSettings("targetLang"), resultText: "", candidateText: "", - statusText: "OK" + isError: false, + errorMessage: "" }; this.selectedText = props.selectedText; this.selectedPosition = props.selectedPosition; @@ -98,7 +98,8 @@ export default class TranslateContainer extends Component { panelPosition: panelPosition, resultText: result.resultText, candidateText: getSettings("ifShowCandidate") ? result.candidateText : "", - statusText: result.statusText, + isError: result.isError, + errorMessage: result.errorMessage, currentLang: shouldSwitchSecondLang ? secondLang : targetLang }); }; @@ -122,7 +123,8 @@ export default class TranslateContainer extends Component { currentLang={this.state.currentLang} resultText={this.state.resultText} candidateText={this.state.candidateText} - statusText={this.state.statusText} + isError={this.state.isError} + errorMessage={this.state.errorMessage} hidePanel={this.hidePanel} /> diff --git a/src/content/components/TranslatePanel.js b/src/content/components/TranslatePanel.js index 6f9a714..fb99989 100644 --- a/src/content/components/TranslatePanel.js +++ b/src/content/components/TranslatePanel.js @@ -2,7 +2,6 @@ import browser from "webextension-polyfill"; import React, { Component } from "react"; import ReactDOM from "react-dom"; import { getSettings } from "src/settings/settings"; -import getErrorMessage from "src/common/getErrorMessage"; import "../styles/TranslatePanel.scss"; const splitLine = text => { @@ -163,8 +162,7 @@ export default class TranslatePanel extends Component { }; render = () => { - const { shouldShow, selectedText, currentLang, resultText, candidateText, statusText } = this.props; - const isError = statusText !== "OK"; + const { shouldShow, selectedText, currentLang, resultText, candidateText, isError, errorMessage } = this.props; const { width, height } = this.state.shouldResize ? { width: parseInt(getSettings("width")), height: parseInt(getSettings("height")) } : { width: this.state.panelWidth, height: this.state.panelHeight }; @@ -204,7 +202,7 @@ export default class TranslatePanel extends Component {
{isError && (