|
| 1 | +import crypto from 'crypto' |
| 2 | +import axios from 'axios' |
| 3 | +import qs from 'qs' |
| 4 | +import TranslateEngine, { TranslateOptions, TranslateResult } from './base' |
| 5 | +import { Config } from '~/core' |
| 6 | + |
| 7 | +interface BaiduSignOptions { |
| 8 | + appid: string | null | undefined |
| 9 | + salt: string |
| 10 | + secret: string | null | undefined |
| 11 | + query: string |
| 12 | +} |
| 13 | + |
| 14 | +export default class BaiduTranslate extends TranslateEngine { |
| 15 | + apiLink = 'https://fanyi.baidu.com' |
| 16 | + apiRoot = 'https://fanyi-api.baidu.com' |
| 17 | + |
| 18 | + async translate(options: TranslateOptions) { |
| 19 | + let { from = 'auto', to = 'auto' } = options |
| 20 | + |
| 21 | + from = this.convertToSupportedLocalesForGoogleCloud(from) |
| 22 | + to = this.convertToSupportedLocalesForGoogleCloud(to) |
| 23 | + |
| 24 | + const appid = Config.baiduAppid |
| 25 | + const secret = Config.baiduApiSecret |
| 26 | + const salt = Date.now().toString() |
| 27 | + const sign = this.getSign({ appid, secret, query: options.text, salt }) |
| 28 | + |
| 29 | + const form = { |
| 30 | + q: options.text, |
| 31 | + appid, |
| 32 | + salt, |
| 33 | + from, |
| 34 | + to, |
| 35 | + sign, |
| 36 | + } |
| 37 | + |
| 38 | + const { data } = await axios({ |
| 39 | + method: 'GET', |
| 40 | + url: `${this.apiRoot}/api/trans/vip/translate?${qs.stringify(form)}`, |
| 41 | + }) |
| 42 | + |
| 43 | + return this.transform(data, options) |
| 44 | + } |
| 45 | + |
| 46 | + convertToSupportedLocalesForGoogleCloud(locale: string): string { |
| 47 | + return locale.replace(/-/g, '_').split('_')[0] |
| 48 | + } |
| 49 | + |
| 50 | + getSign({ appid, salt, query, secret }: BaiduSignOptions): string { |
| 51 | + if (appid && salt) { |
| 52 | + const string = appid + query + salt + secret |
| 53 | + const md5 = crypto.createHash('md5') |
| 54 | + md5.update(string) |
| 55 | + return md5.digest('hex') |
| 56 | + } |
| 57 | + return '' |
| 58 | + } |
| 59 | + |
| 60 | + transform(response: any, options: TranslateOptions): TranslateResult { |
| 61 | + const { text } = options |
| 62 | + |
| 63 | + const r: TranslateResult = { |
| 64 | + text, |
| 65 | + to: response.to, |
| 66 | + from: response.from, |
| 67 | + response, |
| 68 | + linkToResult: `${this.apiLink}/#${response.from}/${response.to}/${text}`, |
| 69 | + } |
| 70 | + |
| 71 | + try { |
| 72 | + const result: string[] = [] |
| 73 | + response.trans_result.forEach((v: any) => { |
| 74 | + result.push(v.dst) |
| 75 | + }) |
| 76 | + r.result = result |
| 77 | + } |
| 78 | + catch (e) {} |
| 79 | + |
| 80 | + if (!r.result) r.error = new Error((`[${response.error_code}] ${response.error_msg}`) || 'No result') |
| 81 | + |
| 82 | + return r |
| 83 | + } |
| 84 | +} |
0 commit comments