simple-translate/src/common/translate.js

87 lines
2.5 KiB
JavaScript
Raw Normal View History

2018-06-02 12:42:29 +00:00
/* Copyright (c) 2017-2018 Sienori All rights reserved.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
2018-06-02 12:29:38 +00:00
class Translate {
constructor() {
this.history = [];
}
2018-06-02 12:29:38 +00:00
getHistory(sourceWord, sourceLang, targetLang) {
const history = this.history.find(
history =>
history.sourceWord == sourceWord &&
history.sourceLang == sourceLang &&
history.targetLang == targetLang &&
history.result.statusText == "OK"
);
return history;
}
setHistory(sourceWord, sourceLang, targetLang, formattedResult) {
this.history.push({
sourceWord: sourceWord,
sourceLang: sourceLang,
targetLang: targetLang,
result: formattedResult
});
}
async translate(sourceWord, sourceLang = "auto", targetLang) {
2018-11-15 12:24:18 +00:00
sourceWord = sourceWord.trim();
const history = this.getHistory(sourceWord, sourceLang, targetLang);
if (history) return history.result;
const result = await this.sendRequest(sourceWord, sourceLang, targetLang);
const formattedResult = this.formatResult(result);
this.setHistory(sourceWord, sourceLang, targetLang, formattedResult);
return formattedResult;
2018-07-31 11:35:03 +00:00
}
2018-06-02 12:29:38 +00:00
2018-07-31 11:35:03 +00:00
sendRequest(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(
2018-07-31 11:35:03 +00:00
word
)}`;
const xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.open("GET", url);
xhr.send();
2018-06-02 12:29:38 +00:00
2018-07-31 11:35:03 +00:00
return new Promise((resolve, reject) => {
xhr.onload = () => {
resolve(xhr);
};
2018-07-31 15:50:10 +00:00
xhr.onerror = () => {
resolve(xhr);
};
2018-07-31 11:35:03 +00:00
});
}
2018-06-02 12:29:38 +00:00
formatResult(result) {
2018-07-31 11:35:03 +00:00
const resultData = {
resultText: "",
candidateText: "",
sourceLanguage: "",
2018-07-31 15:50:10 +00:00
percentage: 0,
statusText: ""
2018-07-31 11:35:03 +00:00
};
2018-06-02 12:29:38 +00:00
resultData.statusText = result.statusText;
2018-07-31 15:50:10 +00:00
if (resultData.statusText !== "OK") return resultData;
resultData.sourceLanguage = result.response.src;
resultData.percentage = result.response.confidence;
resultData.resultText = result.response.sentences.map(sentence => sentence.trans).join("");
if (result.response.dict) {
resultData.candidateText = result.response.dict
.map(dict => `${dict.pos}${dict.pos != "" ? ": " : ""}${dict.terms.join(", ")}\n`)
.join("");
2018-06-02 12:29:38 +00:00
}
2018-07-31 11:35:03 +00:00
return resultData;
}
}