Skip to content

Commit

Permalink
feat: support google translate api key
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Feb 17, 2021
1 parent 6b40469 commit a93a404
Show file tree
Hide file tree
Showing 16 changed files with 58 additions and 19 deletions.
1 change: 1 addition & 0 deletions locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"config.key_max_length": "Schlüssel werden bei der Extrahierung auf die angegebene Zeichenzahl gekürzt (exlusive des keyPrefix). Standardwert ist unlimitiert.",
"config.key_prefix": "Zeichenfolge, die dem Schlüssel bei der Extrahierung vorangestellt wird. Sie können {fileName} für den Dateinamen und {fileNameWithoutExt} für den Teil des Dateinamens vor dem ersten Punkt verwenden.",
"config.keygen_strategy": "Strategie der Schlüsselerzeugung.",
"config.keygen_style": "",
"config.keys_in_use": "Schlüssel, die als verwendet markiert werden sollen, obwohl sie nicht im Code vorkommen",
"config.keystyle": "Stil der Lokalisierungsschlüssel",
"config.language_tag_system": "Sprachen tag system",
Expand Down
1 change: 1 addition & 0 deletions locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"config.enabled_parsers": "Locale file format parsers. By default, It will be handled by activated frameworks",
"config.encoding": "File encoding for reading and writing locale files",
"config.full_reload_on_changed": "Perform a full reload on locale file changes. (for .js/.ts dynamic import)",
"config.google_api_key": "API key for Google Translate (Optional)",
"config.ignore_files": "Locale files to ignore on loading. Accepting an array of glob.",
"config.ignored_locales": "Locale codes to ignore",
"config.include_subfolders": "Search recursively inside locale directories",
Expand Down
1 change: 1 addition & 0 deletions locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"config.key_max_length": "Si especificada, la clave generada al extraer se truncará a este número de caracteres (excluyendo el keyPrefix). El valor predeterminado es ilimitado.",
"config.key_prefix": "Cadena a anteponer a la ",
"config.keygen_strategy": "Estrategia para la generación de claves",
"config.keygen_style": "",
"config.keys_in_use": "Claves a marcar para rellenar incluso sin aparecer en el código",
"config.keystyle": "Estilo de la clave de configuración regional",
"config.language_tag_system": "Sistema de etiquetado de lenguaje se está usando",
Expand Down
1 change: 1 addition & 0 deletions locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"config.key_max_length": "",
"config.key_prefix": "",
"config.keygen_strategy": "",
"config.keygen_style": "",
"config.keys_in_use": "",
"config.keystyle": "Style de Clé locale.",
"config.language_tag_system": "",
Expand Down
1 change: 1 addition & 0 deletions locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"config.key_max_length": "",
"config.key_prefix": "",
"config.keygen_strategy": "",
"config.keygen_style": "",
"config.keys_in_use": "",
"config.keystyle": "ロケールキースタイル",
"config.language_tag_system": "",
Expand Down
1 change: 1 addition & 0 deletions locales/nb-NO.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"config.key_max_length": "",
"config.key_prefix": "",
"config.keygen_strategy": "",
"config.keygen_style": "",
"config.keys_in_use": "",
"config.keystyle": "Oversettelseskodestil",
"config.language_tag_system": "",
Expand Down
1 change: 1 addition & 0 deletions locales/nl-NL.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"config.key_max_length": "",
"config.key_prefix": "",
"config.keygen_strategy": "",
"config.keygen_style": "",
"config.keys_in_use": "",
"config.keystyle": "Locale sleutel stijl",
"config.language_tag_system": "",
Expand Down
1 change: 1 addition & 0 deletions locales/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"config.key_max_length": "",
"config.key_prefix": "",
"config.keygen_strategy": "",
"config.keygen_style": "",
"config.keys_in_use": "",
"config.keystyle": "Estilo de chave de tradução",
"config.language_tag_system": "",
Expand Down
1 change: 1 addition & 0 deletions locales/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"config.key_max_length": "Если указано, сгенерированный ключ при извлечении будет сокращен до этого количества символов (исключая keyPrefix). По умолчанию неограниченно.",
"config.key_prefix": "Строка перед ключом извлечения. Вы можете использовать {fileName} для имени файла и {fileNameWithoutExt} для части имени файла перед первой точкой.",
"config.keygen_strategy": "Стратегия генерации ключа.",
"config.keygen_style": "",
"config.keys_in_use": "Ключи, которые нужно отметить как используемые, несмотря на то, что они не отображаются в коде",
"config.keystyle": "Стиль ключа перевода",
"config.language_tag_system": "Использование языковой системы тегов.",
Expand Down
1 change: 1 addition & 0 deletions locales/sv-SE.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"config.key_max_length": "Om specifierad kommer den genererade nyckeln vid extrahering trunkeras till så här många tecken (exklusive `keyPrefix`). Sätts som standard till obegränsat.",
"config.key_prefix": "Sträng att lägga till innan dem extraherade nyckeln. Du kan använda {fileName} för filnamnet, och {fileNameWithoutExt} för den del av namnet fram tills första punkten.",
"config.keygen_strategy": "Strategi för att generera nycklar.",
"config.keygen_style": "",
"config.keys_in_use": "Nycklar att markera som i användning, även fast de inte dyker upp i koden",
"config.keystyle": "locale-fils nyckelstilmall",
"config.language_tag_system": "Språkmärkningssystem som används.",
Expand Down
1 change: 1 addition & 0 deletions locales/uk-UA.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"config.key_max_length": "Якщо вказано, створений ключ при добуванні буде усічений до цієї кількості символів (виключаючи keyPrefix). За замовчуванням необмежено.",
"config.key_prefix": "Рядок перед ключем вилучення. Ви можете використовувати {fileName} для імені файлу і {fileNameWithoutExt} для частини імені файлу перед першою точкою.",
"config.keygen_strategy": "Стратегія генерації ключа.",
"config.keygen_style": "",
"config.keys_in_use": "Ключі, які потрібно відзначити як використовувані, незважаючи на те, що вони не відображаються в коді",
"config.keystyle": "Стиль ключа перекладу",
"config.language_tag_system": "Використання мовної системи тегів.",
Expand Down
1 change: 1 addition & 0 deletions locales/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"config.key_max_length": "",
"config.key_prefix": "提取出的文案路径前缀",
"config.keygen_strategy": "提取文案路径的生成策略",
"config.keygen_style": "",
"config.keys_in_use": "尽管代码中没有出现,但仍标记为正在使用的键",
"config.keystyle": "翻译路径格式",
"config.language_tag_system": "语言标签系统",
Expand Down
1 change: 1 addition & 0 deletions locales/zh-TW.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"config.key_max_length": "",
"config.key_prefix": "文案 key 的前綴",
"config.keygen_strategy": "文案 key 的生成策略, slug 默認策略, random 生成隨機字串",
"config.keygen_style": "",
"config.keys_in_use": "儘管程式碼中沒有出現,但仍標記為正在使用的鍵",
"config.keystyle": "翻譯路徑格式",
"config.language_tag_system": "語言標籤系統",
Expand Down
25 changes: 15 additions & 10 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -908,6 +908,21 @@
"default": false,
"description": "%config.translate_override_existing%"
},
"i18n-ally.translate.google.apiKey": {
"type": "string",
"default": null,
"description": "%config.google_api_key%"
},
"i18n-ally.translate.deepl.apiKey": {
"type": "string",
"default": null,
"description": "%config.deepl_api_key%"
},
"i18n-ally.translate.deepl.enableLog": {
"type": "boolean",
"default": false,
"description": "%config.deepl_log%"
},
"i18n-ally.usage.scanningIgnore": {
"type": "array",
"items": {
Expand Down Expand Up @@ -1020,16 +1035,6 @@
"type": "string",
"description": "%config.default_namespace%"
},
"i18n-ally.translate.deepl.apiKey": {
"type": "string",
"default": null,
"description": "%config.deepl_api_key%"
},
"i18n-ally.translate.deepl.enableLog": {
"type": "boolean",
"default": false,
"description": "%config.deepl_log%"
},
"i18n-ally.derivedKeyRules": {
"deprecationMessage": "Depreacted. Use \"i18n-ally.usage.derivedKeyRules\" instead."
},
Expand Down
4 changes: 4 additions & 0 deletions src/core/Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,10 @@ export class Config {
.update(key, value, isGlobal)
}

static get googleApiKey() {
return this.getConfig<string | null | undefined>('translate.google.apiKey')
}

static get deeplApiKey() {
return this.getConfig<string | null | undefined>('translate.deepl.apiKey')
}
Expand Down
35 changes: 26 additions & 9 deletions src/translators/engines/google.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,49 @@
import axios from 'axios'
import TranslateEngine, { TranslateOptions, TranslateResult } from './base'
import { Config } from '~/core'

export default class GoogleTranslate extends TranslateEngine {
link = 'https://translate.google.com'
apiRoot = 'https://translate.googleapis.com'

async translate(options: TranslateOptions) {
const {
from = 'auto',
to = 'auto',
} = options

const key = Config.googleApiKey
const headers = key
? { Authorization: `Bearer ${key}` }
: undefined

const { data } = await axios({
method: 'GET',
url: `${this.apiRoot}/translate_a/single?client=gtx&sl=${options.from || 'auto'}&tl=${options.to || 'auto'}&hl=zh-CN&dt=t&dt=bd&ie=UTF-8&oe=UTF-8&dj=1&source=icon&q=${encodeURI(options.text)}`,
url: `${this.apiRoot}/translate_a/single?client=gtx&sl=${from}&tl=${to}&hl=zh-CN&dt=t&dt=bd&ie=UTF-8&oe=UTF-8&dj=1&source=icon&q=${encodeURI(options.text)}`,
headers,
})

return this.transform(data, options)
}

transform(rawRes: any, options: TranslateOptions): TranslateResult {
transform(response: any, options: TranslateOptions): TranslateResult {
const {
text,
to = 'auto',
} = options

const r: TranslateResult = {
text: options.text,
to: options.to || 'auto',
from: rawRes.src,
response: rawRes,
linkToResult: `${this.link}/#auto/${options.to || 'auto'}/${options.text}`,
text,
to,
from: response.src,
response,
linkToResult: `${this.link}/#auto/${to}/${text}`,
}

// 尝试获取详细释义
try {
const d: string[] = []
rawRes.dict.forEach((v: any) => {
response.dict.forEach((v: any) => {
d.push(`${v.pos}${(v.terms.slice(0, 3) || []).join(',')}`)
})
r.detailed = d
Expand All @@ -36,7 +53,7 @@ export default class GoogleTranslate extends TranslateEngine {
// 尝试取得翻译结果
try {
const result: string[] = []
rawRes.sentences.forEach((v: any) => {
response.sentences.forEach((v: any) => {
result.push(v.trans)
})
r.result = result
Expand Down

0 comments on commit a93a404

Please sign in to comment.