1 | const axios = require("axios");
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | function isObject(it) {
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | return Object.prototype.toString.call(it) === "[object Object]";
|
14 | }
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | function isArray(it) {
|
22 | if (Array.isArray != null)
|
23 | return Array.isArray(it);
|
24 | return Object.prototype.toString.call(it) === "[object Array]";
|
25 | }
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 | async function translateText(text, targetLang, yandex) {
|
35 | if (targetLang === "en") {
|
36 | return text;
|
37 | }
|
38 | if (yandex) {
|
39 | return await translateYandex(text, targetLang, yandex);
|
40 | } else {
|
41 | return await translateGoogle(text, targetLang);
|
42 | }
|
43 | }
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 | async function translateYandex(text, targetLang, yandex) {
|
53 | if (targetLang === "zh-cn") {
|
54 | targetLang = "zh";
|
55 | }
|
56 | try {
|
57 | const url = `https://translate.yandex.net/api/v1.5/tr.json/translate?key=${yandex}&text=${encodeURIComponent(text)}&lang=en-${targetLang}`;
|
58 | const response = await axios({url, timeout: 15000});
|
59 | if (response.data && response.data['text']) {
|
60 | return response.data['text'][0];
|
61 | }
|
62 | throw new Error("Invalid response for translate request");
|
63 | } catch (e) {
|
64 | throw new Error(`Could not translate to "${targetLang}": ${e}`);
|
65 | }
|
66 | }
|
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 | async function translateGoogle(text, targetLang) {
|
75 | try {
|
76 | const url = `http://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=${targetLang}&dt=t&q=${encodeURIComponent(text)}&ie=UTF-8&oe=UTF-8`;
|
77 | const response = await axios({url, timeout: 15000});
|
78 | if (isArray(response.data)) {
|
79 |
|
80 | return response.data[0][0][0];
|
81 | }
|
82 | throw new Error("Invalid response for translate request");
|
83 | } catch (e) {
|
84 | throw new Error(`Could not translate to "${targetLang}": ${e}`);
|
85 | }
|
86 | }
|
87 |
|
88 | module.exports = {
|
89 | isArray,
|
90 | isObject,
|
91 | translateText
|
92 | }; |
\ | No newline at end of file |