├── .husky ├── .gitignore ├── commit-msg └── pre-commit ├── proxy ├── .gitignore ├── translate.google.com.json └── README.md ├── .eslintignore ├── images ├── preview-result.png └── preview-setting.png ├── src ├── global.d.ts ├── util.ts ├── libs │ └── human-string.js ├── main.ts ├── info.json ├── common.ts ├── google-translate-mobile.ts ├── lang.ts ├── google-translate.ts ├── appcast.json └── google-translate-rpc.ts ├── .vscode └── settings.json ├── .editorconfig ├── tsconfig.eslint.json ├── .commitlintrc.js ├── scripts ├── init-info.js ├── build-zip.js └── init-appcast.js ├── README.md ├── .github └── workflows │ └── release.yml ├── .prettierrc.js ├── LICENSE ├── .cz-config.js ├── rollup.config.js ├── .gitignore ├── .eslintrc.js ├── package.json ├── CHANGELOG.md └── tsconfig.json /.husky/.gitignore: -------------------------------------------------------------------------------- 1 | _ 2 | -------------------------------------------------------------------------------- /proxy/.gitignore: -------------------------------------------------------------------------------- 1 | .vercel 2 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | dist/ 3 | 4 | .DS_Store 5 | 6 | *.log 7 | 8 | .vscode -------------------------------------------------------------------------------- /.husky/commit-msg: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | npx --no-install commitlint --edit "$1" 5 | -------------------------------------------------------------------------------- /images/preview-result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roojay/bobplugin-google-translate/HEAD/images/preview-result.png -------------------------------------------------------------------------------- /images/preview-setting.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roojay/bobplugin-google-translate/HEAD/images/preview-setting.png -------------------------------------------------------------------------------- /src/global.d.ts: -------------------------------------------------------------------------------- 1 | declare function supportLanguages(): any; 2 | declare function translate(query: any, completion: any): void; 3 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | npx --no-install lint-staged 5 | 6 | npm run type-check 7 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "god.tsconfig": "./tsconfig.json", 3 | "cSpell.words": ["addtions", "reqid", "ssel", "tsel"] 4 | } 5 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 2 6 | end_of_line = lf 7 | charset = utf-8 8 | trim_trailing_whitespace = true 9 | insert_final_newline = false -------------------------------------------------------------------------------- /tsconfig.eslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": [ 4 | "src/**/*.ts", 5 | "types/**/*.ts", 6 | "./src/**/*.js", 7 | "./.eslintrc.js", 8 | "./rollup.config.js", 9 | "./scripts/**/*.js" 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /src/util.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable max-len */ 2 | export var userAgent = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36`; 3 | export var userAgentMobile = `Mozilla/5.0 (Linux; Android 10; GM1910) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.85 Mobile Safari/537.36`; 4 | -------------------------------------------------------------------------------- /.commitlintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: ['cz'], 3 | rules: { 4 | 'subject-empty': [2, 'never'], 5 | 'type-empty': [2, 'never'], 6 | 'type-enum': [ 7 | 2, 8 | 'always', 9 | ['feat', 'fix', 'docs', 'style', 'refactor', 'test', 'build', 'chore', 'revert', 'i18n', 'wip'], 10 | ], 11 | }, 12 | }; 13 | -------------------------------------------------------------------------------- /scripts/init-info.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const fs = require('fs-extra'); 3 | 4 | const info = require('../src/info.json'); 5 | const pkg = require('../package.json'); 6 | 7 | const { version, author = '', homepage = ' ', description = '' } = pkg; 8 | 9 | const infoData = { ...info, version, author, homepage, summary: description }; 10 | const infoPath = path.join(__dirname, '../src/info.json'); 11 | 12 | fs.outputJSONSync(infoPath, infoData, { spaces: 2 }); 13 | -------------------------------------------------------------------------------- /scripts/build-zip.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const AdmZip = require('adm-zip'); 3 | const initAppcast = require('./init-appcast'); 4 | const plugInfo = require('../src/info.json'); 5 | 6 | const pkgName = 'google-translate'; 7 | const pkg = path.resolve(__dirname, `../release/${pkgName}-v${plugInfo.version}.bobplugin`); 8 | 9 | const zip = new AdmZip(); 10 | zip.addLocalFolder(path.resolve(__dirname, `../dist/${pkgName}.bobplugin`)); 11 | zip.writeZip(pkg); 12 | 13 | initAppcast(); 14 | -------------------------------------------------------------------------------- /proxy/translate.google.com.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 2, 3 | "routes": [ 4 | { 5 | "src": "/(.*)", 6 | "dest": "https://translate.google.com/$1", 7 | "headers": { 8 | "Cache-Control": "no-cache", 9 | "Host": "translate.google.com", 10 | "origin": "https://translate.google.com", 11 | "referer": "https://translate.google.com/", 12 | "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" 13 | } 14 | } 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /proxy/README.md: -------------------------------------------------------------------------------- 1 | # 反向代理谷歌翻译 2 | 3 | > 前提条件: 需要拥有一个自己的域名, 需要熟悉基础的命令行操作 4 | 5 | 1. 创建 Vercel 账号: [https://vercel.com](https://vercel.com/); 6 | 2. 配置 nodejs 环境: [https://nodejs.org/zh-cn/download/](https://nodejs.org/zh-cn/download/); 7 | 3. 安装 vercel-cli: `npm i -g vercel` ; 8 | 4. 登录 vercel: `vercel login` 参考 [https://vercel.com/docs/cli/login](https://vercel.com/docs/cli/login); 9 | 5. 将配置发布到生产环境: `vercel -A translate.google.com.json --prod` 10 | 6. 配置自定义域名: `vercel domains add google-translate.[你自己的域名].com`; 11 | 7. 为上一步配置自定义的配置 DNS 解析, 在你的域名管理处添加一条 `CNAME google-translate cname-china.vercel-dns.com`; 12 | 8. 网页访问测试配置的自定义域名: `google-translate.[你自己的域名].com`; 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # bobplugin-google-translate 2 | 3 | > 这是一个 [Bob](https://bobtranslate.com/) 的 google 翻译插件 4 | 5 | ## 特性 6 | 7 | - 支持缓存查询结果(默认缓存过期时间为一周); 8 | - 支持自定义配置替换 `translate.google.com` 以实现国内直接访问; 9 | - 支持驼峰, 下划线, 部分特殊符号等分隔符; 10 | - 支持 google tts 发音; 11 | 12 | ## 安装 13 | 14 | 1. 安装 [Bob](https://ripperhe.gitee.io/bob/#/general/quickstart/install) (version >= 0.50) 15 | 2. 下载插件: [bobplugin-google-translate](https://github.com/roojay520/bobplugin-google-translate/releases) 16 | 3. 插件安装: [Bob 插件安装文档说明](https://bobtranslate.com/guide/advance/plugin.html#%E4%BD%BF%E7%94%A8%E6%8F%92%E4%BB%B6-1) 17 | 18 | ## 预览 19 | 20 | ![setting](./images/preview-setting.png) 21 | ![result](./images/preview-result.png) 22 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | on: 3 | push: 4 | tags: 5 | - '*' 6 | 7 | jobs: 8 | build: 9 | runs-on: macos-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | with: 13 | fetch-depth: 0 14 | token: ${{ secrets.GIT_TOKEN }} 15 | 16 | - uses: actions/setup-node@v3 17 | with: 18 | node-version: 16 19 | 20 | - name: Install Dependencies And Build 21 | run: | 22 | yarn install 23 | yarn run build 24 | 25 | - name: Commit files 26 | run: | 27 | git config --global user.name 'roojay520' 28 | git config --global user.email 'roojay520@users.noreply.github.com' 29 | git commit -am "chore: 更新版本文件" 30 | 31 | - name: Push changes 32 | uses: ad-m/github-push-action@master 33 | with: 34 | github_token: ${{ secrets.GIT_TOKEN }} 35 | 36 | - uses: ncipollo/release-action@v1 37 | with: 38 | artifacts: 'release/*.bobplugin' 39 | token: ${{ secrets.GIT_TOKEN }} 40 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | // .prettierrc.js 2 | module.exports = { 3 | // 一行最多 120 字符 4 | printWidth: 120, 5 | // 使用 2 个空格缩进 6 | tabWidth: 2, 7 | // 不使用缩进符,而使用空格 8 | useTabs: false, 9 | // 行尾需要有分号 10 | semi: true, 11 | // 使用单引号 12 | singleQuote: true, 13 | // 对象的 key 仅在必要时用引号 14 | quoteProps: 'as-needed', 15 | // jsx 不使用单引号,而使用双引号 16 | jsxSingleQuote: false, 17 | // 末尾需要有逗号 18 | trailingComma: 'all', 19 | // 大括号内的首尾需要空格 20 | bracketSpacing: true, 21 | // jsx 标签的反尖括号需要换行 22 | jsxBracketSameLine: false, 23 | // 箭头函数,只有一个参数的时候,也需要括号 24 | arrowParens: 'always', 25 | // 每个文件格式化的范围是文件的全部内容 26 | rangeStart: 0, 27 | rangeEnd: Infinity, 28 | // 不需要写文件开头的 @prettier 29 | requirePragma: false, 30 | // 不需要自动在文件开头插入 @prettier 31 | insertPragma: false, 32 | // 使用默认的折行标准 33 | proseWrap: 'preserve', 34 | // 根据显示样式决定 html 要不要折行 35 | htmlWhitespaceSensitivity: 'css', 36 | // vue 文件中的 script 和 style 内不用缩进 37 | vueIndentScriptAndStyle: false, 38 | // 换行符使用 lf 39 | endOfLine: 'lf', 40 | // 格式化嵌入的内容 41 | embeddedLanguageFormatting: 'auto', 42 | }; 43 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Roojay 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/libs/human-string.js: -------------------------------------------------------------------------------- 1 | // https://github.com/sindresorhus/humanize-string 2 | 3 | var decamelize = (text, separator = '_') => { 4 | if (!(typeof text === 'string' && typeof separator === 'string')) { 5 | throw new TypeError('The `text` and `separator` arguments should be of type `string`'); 6 | } 7 | return text 8 | .replace(/([\p{Lowercase_Letter}\d])(\p{Uppercase_Letter})/gu, `$1${separator}$2`) 9 | .replace(/(\p{Uppercase_Letter}+)(\p{Uppercase_Letter}\p{Lowercase_Letter}+)/gu, `$1${separator}$2`); 10 | }; 11 | 12 | var humanizeString = (input) => { 13 | let _input = input; 14 | if (typeof _input !== 'string') { 15 | throw new TypeError('Expected a string'); 16 | } 17 | _input = decamelize(_input, ''); 18 | _input = _input 19 | .replace(/[]+/g, ' ') 20 | .replace(/([_-])+/g, ' $1 ') 21 | // https://stackoverflow.com/questions/3469080/match-whitespace-but-not-newlines#answer-3469155:~:text=Use%20a%20double%2Dnegative 22 | .replace(/[^\S\r\n]{2,}/g, ' ') 23 | .trim(); 24 | _input = `${_input.charAt(0).toUpperCase()}${_input.slice(1)}`; 25 | 26 | // https://github.com/roojay520/bobplugin-google-translate/issues/2 27 | if (!_input.includes(' ')) return _input.toLowerCase(); 28 | 29 | return _input; 30 | }; 31 | 32 | module.exports = humanizeString; 33 | -------------------------------------------------------------------------------- /.cz-config.js: -------------------------------------------------------------------------------- 1 | // https://github.com/leonardoanalista/cz-customizable/blob/master/cz-config-EXAMPLE.js 2 | module.exports = { 3 | types: [ 4 | { 5 | value: 'chore', 6 | name: 'chore: 构建过程或者辅助工具的变动(配置文件,依赖管理等), 生产代码无变动', 7 | }, 8 | { 9 | value: 'feat', 10 | name: 'feat: 增加新功能(feature)', 11 | }, 12 | { 13 | value: 'fix', 14 | name: 'fix: 修复 bug', 15 | }, 16 | { 17 | value: 'refactor', 18 | name: 'refactor: 重构(即不是新增功能, 也不是修改bug的代码变动)', 19 | }, 20 | { 21 | value: 'docs', 22 | name: 'docs: 更新文档', 23 | }, 24 | { 25 | value: 'test', 26 | name: 'test: 新增测试或更新现有测试', 27 | }, 28 | { 29 | value: 'i18n', 30 | name: 'i18n: 更新国际化语言文件', 31 | }, 32 | { 33 | value: 'style', 34 | name: 'style: 调整代码风格(空格, 分号等),不影响代码运行的更改', 35 | }, 36 | { 37 | value: 'revert', 38 | name: 'revert: 代码版本回退', 39 | }, 40 | ], 41 | scopes: [], 42 | subjectLimit: 50, 43 | allowCustomScopes: true, 44 | allowBreakingChanges: ['feat', 'fix'], 45 | skipQuestions: ['scope', 'breaking', 'footer'], 46 | messages: { 47 | type: '选择您要提交的更改类型:', 48 | scope: '\n此次更改影响的范围(可选):', 49 | // used if allowCustomScopes is true 50 | customScope: '此次更改影响的范围:', 51 | subject: '本次 commit 简短描述,不超过50个字符:\n', 52 | body: '本次 commit 的详细描述(可选). 使用 "|" 进行换行:\n', 53 | breaking: '如果本次变动与上个版本不兼容, 请详细列出(可选):\n', 54 | footer: '如果当前 commit 针对某个 issue, 请列出关闭的 issue(可选). 例如: ISSUES CLOSED: #123, #245, #992:\n', 55 | confirmCommit: '确认提交?', 56 | }, 57 | }; 58 | -------------------------------------------------------------------------------- /scripts/init-appcast.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const fs = require('fs-extra'); 3 | const crypto = require('crypto'); 4 | const package = require('../package.json'); 5 | const plugInfo = require('../src/info.json'); 6 | const plugAppcast = require('../src/appcast.json'); 7 | 8 | const githubRelease = `https://github.roojay.com/roojay520/bobplugin-google-translate/releases/download`; 9 | 10 | module.exports = () => { 11 | const pkgName = 'google-translate'; 12 | const pkgPath = path.resolve(__dirname, `../release/${pkgName}-v${plugInfo.version}.bobplugin`); 13 | const appcastPath = path.join(__dirname, '../src/appcast.json'); 14 | 15 | const fileBuffer = fs.readFileSync(pkgPath); 16 | const sum = crypto.createHash('sha256'); 17 | sum.update(fileBuffer); 18 | const hex = sum.digest('hex'); 19 | 20 | const version = { 21 | version: package.version, 22 | desc: 'https://github.com/roojay520/bobplugin-google-translate/blob/master/CHANGELOG.md', 23 | sha256: hex, 24 | url: `${githubRelease}/v${package.version}/google-translate-v${package.version}.bobplugin`, 25 | minBobVersion: plugInfo.minBobVersion, 26 | }; 27 | 28 | let versions = (plugAppcast && plugAppcast.versions) || []; 29 | if (!Array.isArray(versions)) versions = []; 30 | const index = versions.findIndex((v) => v.version === package.version); 31 | if (index === -1) { 32 | versions.splice(0, 0, version); 33 | } else { 34 | versions.splice(index, 1, version); 35 | } 36 | const appcastData = { identifier: plugInfo.identifier, versions }; 37 | fs.outputJSONSync(appcastPath, appcastData, { spaces: 2 }); 38 | }; 39 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | // import fs from 'fs-extra'; 2 | import path from 'path'; 3 | import copy from 'rollup-plugin-copy'; 4 | import json from '@rollup/plugin-json'; 5 | import esbuild from 'rollup-plugin-esbuild'; 6 | import commonjs from '@rollup/plugin-commonjs'; 7 | import resolve from '@rollup/plugin-node-resolve'; 8 | import nodePolyfills from 'rollup-plugin-polyfill-node'; 9 | 10 | const pkg = 'google-translate.bobplugin'; 11 | 12 | export default { 13 | input: path.join(__dirname, './src/main.ts'), 14 | output: { 15 | format: 'cjs', 16 | exports: 'auto', 17 | file: path.join(__dirname, `./dist/${pkg}/main.js`), 18 | }, 19 | plugins: [ 20 | copy({ 21 | targets: [ 22 | { src: './src/info.json', dest: `dist/${pkg}/` }, 23 | { src: './src/libs', dest: `dist/${pkg}/` }, 24 | ], 25 | }), 26 | json({ namedExports: false }), 27 | resolve({ 28 | extensions: ['.js', '.ts'], 29 | modulesOnly: true, 30 | preferBuiltins: false, 31 | }), 32 | commonjs(), 33 | nodePolyfills(), 34 | esbuild({ 35 | // All options are optional 36 | include: /\.[jt]?s$/, // default, inferred from `loaders` option 37 | exclude: /node_modules/, // default 38 | sourceMap: false, // default 39 | minify: process.env.NODE_ENV === 'production', 40 | target: 'es6', // default, or 'es20XX', 'esnext', 41 | // Add extra loaders 42 | loaders: { 43 | // Add .json files support 44 | // require @rollup/plugin-commonjs 45 | '.json': 'json', 46 | }, 47 | }), 48 | ], 49 | external: ['crypto-js', '$util', '$http', '$info', '$option', '$log', '$data', '$file'], 50 | }; 51 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import * as Bob from '@bob-plug/core'; 2 | import { getSupportLanguages, standardToNoStandard } from './lang'; 3 | import { _translate as translateByWeb } from './google-translate'; 4 | import { _translate as translateByRPC } from './google-translate-rpc'; 5 | import { _translate as translateByMobile } from './google-translate-mobile'; 6 | 7 | var formatString = require('./libs/human-string'); 8 | 9 | function supportLanguages(): Bob.supportLanguages { 10 | return getSupportLanguages(); 11 | } 12 | 13 | // https://ripperhe.gitee.io/bob/#/plugin/quickstart/translate 14 | function translate(query: Bob.TranslateQuery, completion: Bob.Completion) { 15 | const { text = '', detectFrom, detectTo } = query; 16 | 17 | // https://github.com/roojay520/bobplugin-google-translate/issues/21 18 | // 是否开启字符串分隔处理, 默认关闭(现在 Google Translate API 已经能很好的拆分) 19 | const stringFmt = Bob.api.getOption('stringFmt') === 'enable'; 20 | const str = stringFmt ? formatString(text) : text; 21 | 22 | const from = standardToNoStandard(detectFrom); 23 | const to = standardToNoStandard(detectTo); 24 | const params = { from, to, cache: Bob.api.getOption('cache') }; 25 | 26 | const translateVersion = Bob.api.getOption('version'); 27 | let res; 28 | if (translateVersion === 'rpc') { 29 | res = translateByRPC(str, params); 30 | } else { 31 | res = translateByWeb(str, params); 32 | } 33 | 34 | res 35 | .then((result) => completion({ result })) 36 | .catch((error) => { 37 | Bob.api.$log.error(JSON.stringify(error)); 38 | if (error?.type) return completion({ error }); 39 | completion({ error: Bob.util.error('api', '插件出错', error) }); 40 | }); 41 | } 42 | 43 | global.supportLanguages = supportLanguages; 44 | global.translate = translate; 45 | -------------------------------------------------------------------------------- /src/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "identifier": "com.roojay.bobplugin-google-translate", 3 | "category": "translate", 4 | "version": "0.7.1", 5 | "name": "Google 翻译", 6 | "summary": "Bob google 翻译插件", 7 | "author": "roojay ", 8 | "appcast": "https://github-raw.roojay.com/roojay520/bobplugin-google-translate/master/src/appcast.json", 9 | "homepage": "https://github.com/roojay520/bobplugin-google-translate", 10 | "icon": "114", 11 | "minBobVersion": "0.5.0", 12 | "options": [ 13 | { 14 | "identifier": "cache", 15 | "type": "menu", 16 | "title": "缓存", 17 | "defaultValue": "enable", 18 | "menuValues": [ 19 | { 20 | "title": "开启", 21 | "value": "enable" 22 | }, 23 | { 24 | "title": "关闭", 25 | "value": "disable" 26 | } 27 | ] 28 | }, 29 | { 30 | "identifier": "version", 31 | "type": "menu", 32 | "title": "接口版本", 33 | "defaultValue": "tmp", 34 | "menuValues": [ 35 | { 36 | "title": "WEB(模拟调用网页版接口, 翻译结果和官网一致)", 37 | "value": "web" 38 | }, 39 | { 40 | "title": "RPC(直接调用 RPC 接口, 段落翻译不太准确)", 41 | "value": "rpc" 42 | } 43 | ] 44 | }, 45 | { 46 | "identifier": "proxyApi", 47 | "type": "text", 48 | "title": "代理域名", 49 | "desc": "如果你的网络环境需要代理才能访问 Google Translate, 可以在此填写代理域名, 格式形如: google-translate.proxy.com", 50 | "defaultValue": "" 51 | }, 52 | { 53 | "identifier": "stringFmt", 54 | "type": "menu", 55 | "title": "字符串分隔", 56 | "defaultValue": "disable", 57 | "desc": "拆分驼峰/中划线/下划线格式的长字符串, 例如: fooBarBaz-intoString → foo Bar Baz - into String", 58 | "menuValues": [ 59 | { 60 | "title": "开启", 61 | "value": "enable" 62 | }, 63 | { 64 | "title": "关闭", 65 | "value": "disable" 66 | } 67 | ] 68 | } 69 | ] 70 | } 71 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | banner.user.js 106 | 107 | release 108 | -------------------------------------------------------------------------------- /src/common.ts: -------------------------------------------------------------------------------- 1 | import * as querystring from 'querystring'; 2 | import * as Bob from '@bob-plug/core'; 3 | import { userAgent } from './util'; 4 | import { IGoogleLanguage } from './lang'; 5 | 6 | export interface IQueryOption { 7 | timeout?: number; 8 | to?: IGoogleLanguage; 9 | from?: IGoogleLanguage; 10 | cache?: string; 11 | } 12 | 13 | function getBaseApi() { 14 | let baseApi = 'translate.google.com'; 15 | let proxyApi = Bob.api.getOption('proxyApi'); 16 | proxyApi.replace(/^((https?):\/\/)/, ''); 17 | let urlRegexp = /([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)+[a-z]{2,6}\/?/; 18 | if (urlRegexp.test(proxyApi)) { 19 | return proxyApi; 20 | } 21 | return baseApi; 22 | } 23 | 24 | /** 25 | * @description google 语种检测 26 | * @param {string} text 需要查询的文字 27 | * @param {object} [options={}] 28 | * @return {string} 识别的语言类型 29 | */ 30 | async function detectLang(text: string, options: IQueryOption = {}) { 31 | const { timeout = 10000 } = options; 32 | const query = { 33 | client: 'gtx', 34 | sl: 'auto', 35 | dj: '1', 36 | ie: 'UTF-8', 37 | oe: 'UTF-8', 38 | }; 39 | 40 | const [err, res] = await Bob.util.asyncTo( 41 | Bob.api.$http.post({ 42 | url: `https://${getBaseApi()}/translate_a/single?${querystring.stringify(query)}`, 43 | timeout, 44 | header: { 'User-Agent': userAgent }, 45 | body: { q: text }, 46 | }), 47 | ); 48 | if (err) Bob.api.$log.error(err); 49 | let lang = res?.data?.src; 50 | if (lang === 'zh-CN') lang = 'zh-Hans'; 51 | if (lang === 'zh-TW') lang = 'zh-Hant'; 52 | return lang; 53 | } 54 | 55 | /** 56 | * @description google tts 发音 57 | * @param {string} text 需要查询的文字 58 | * @param {object} [options={}] 59 | * @return {string} tts 音频 url 60 | */ 61 | function tts(text: string, options: IQueryOption = {}) { 62 | const { from } = options; 63 | const query = { 64 | client: 'gtx', 65 | tl: from, 66 | ie: 'UTF-8', 67 | q: text, 68 | ttsspeed: 1, 69 | total: 1, 70 | idx: 0, 71 | textlen: text.length, 72 | prev: 'input', 73 | }; 74 | return `https://${getBaseApi()}/translate_tts?${querystring.stringify(query)}`; 75 | } 76 | 77 | export { detectLang, tts, getBaseApi }; 78 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { es6: true, node: true }, 4 | parser: '@typescript-eslint/parser', 5 | parserOptions: { 6 | ecmaVersion: 2020, 7 | sourceType: 'module', 8 | project: './tsconfig.eslint.json', 9 | }, 10 | plugins: ['import', 'prettier'], 11 | extends: [ 12 | 'airbnb-typescript/base', 13 | 'plugin:@typescript-eslint/recommended', 14 | 'plugin:@typescript-eslint/recommended-requiring-type-checking', 15 | ], 16 | settings: { 17 | 'import/parsers': { 18 | '@typescript-eslint/parser': ['.ts', '.tsx'], 19 | }, 20 | }, 21 | globals: { 22 | $log: false, 23 | $info: false, 24 | $option: false, 25 | $http: false, 26 | $file: false, 27 | $data: false, 28 | }, 29 | rules: { 30 | 'no-var': 'off', 31 | 'vars-on-top': 'off', 32 | 'prefer-const': 'off', 33 | 'no-return-assign': 'off', 34 | 'consistent-return': 'off', 35 | 'prefer-destructuring': 'off', 36 | 'no-underscore-dangle': 'off', 37 | 'object-curly-newline': 'off', 38 | // 'import/no-unresolved': 'error', 39 | 'import/no-mutable-exports': 'off', 40 | 'import/prefer-default-export': 'off', 41 | 'import/no-extraneous-dependencies': 'off', 42 | 'import/no-named-as-default-member': 'off', 43 | 'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off', 44 | 'max-len': ['error', { ignoreComments: true, code: 120, ignoreStrings: true }], 45 | '@typescript-eslint/no-unsafe-call': 'off', 46 | '@typescript-eslint/no-explicit-any': 'off', 47 | '@typescript-eslint/no-var-requires': 'off', 48 | '@typescript-eslint/no-unsafe-return': 'off', 49 | '@typescript-eslint/no-throw-literal': 'off', 50 | '@typescript-eslint/naming-convention': 'off', 51 | '@typescript-eslint/no-unsafe-argument': 'off', 52 | '@typescript-eslint/no-floating-promises': 'off', 53 | '@typescript-eslint/no-unsafe-assignment': 'off', 54 | '@typescript-eslint/no-unsafe-member-access': 'off', 55 | '@typescript-eslint/restrict-template-expressions': 'off', 56 | '@typescript-eslint/explicit-module-boundary-types': 'off', 57 | '@typescript-eslint/quotes': ['error', 'single', { allowTemplateLiterals: true }], 58 | }, 59 | }; 60 | -------------------------------------------------------------------------------- /src/google-translate-mobile.ts: -------------------------------------------------------------------------------- 1 | // 此接口来源于: https://github.com/tingv/bobplugin-google-translate/blob/main/src/translate.ts 2 | import * as querystring from 'querystring'; 3 | import { unescape } from 'lodash-es'; 4 | import * as Bob from '@bob-plug/core'; 5 | import { userAgentMobile } from './util'; 6 | import { IQueryOption } from './common'; 7 | import { noStandardToStandard } from './lang'; 8 | import { getBaseApi } from './common'; 9 | 10 | var resultCache = new Bob.CacheResult(); 11 | // 接口请求频率过快导致错误, 隔三分钟再请求 12 | var API_LIMIT_TIME: number = 1000 * 60 * 3; 13 | var apiLimitErrorTime = 0; 14 | /** 15 | * @description google 翻译 16 | * @param {string} text 需要翻译的文字内容 17 | * @param {object} [options={}] 18 | * @return {object} 一个符合 bob 识别的翻译结果对象 19 | */ 20 | async function _translate(text: string, options: IQueryOption = {}) { 21 | if (text?.length > 5000) { 22 | throw Bob.util.error('param', '翻译文本过长, 单次翻译字符上限为5000'); 23 | } 24 | if (apiLimitErrorTime + API_LIMIT_TIME > Date.now()) throw Bob.util.error('api', '请求频率过快, 请稍后再试'); 25 | apiLimitErrorTime = 0; 26 | const { from = 'auto', to = 'auto', cache = 'enable', timeout = 10000 } = options; 27 | const cacheKey = `${text}${from}${to}${getBaseApi()}`; 28 | if (cache === 'enable') { 29 | const _cacheData = resultCache.get(cacheKey); 30 | if (_cacheData) return _cacheData; 31 | } else { 32 | resultCache.clear(); 33 | } 34 | 35 | const data = { 36 | sl: from, 37 | tl: to, 38 | hl: to, 39 | q: text, 40 | }; 41 | 42 | const [err, res] = await Bob.util.asyncTo( 43 | Bob.api.$http.get({ 44 | url: `https://${getBaseApi()}/m?${querystring.stringify(data)}`, 45 | timeout, 46 | header: { 47 | 'User-Agent': userAgentMobile, 48 | }, 49 | }), 50 | ); 51 | if (res?.response.statusCode === 429) { 52 | apiLimitErrorTime = Date.now(); 53 | throw Bob.util.error('api', '接口请求频率过快', err); 54 | } 55 | 56 | if (err) throw Bob.util.error('network', '接口网络错误', err); 57 | 58 | const resData = res?.data; 59 | if (!Bob.util.isString(resData)) throw Bob.util.error('api', '接口返回数据出错', res); 60 | 61 | const result: Bob.Result = { from: noStandardToStandard(from), to: noStandardToStandard(to), toParagraphs: [] }; 62 | 63 | try { 64 | const resultRegex = /]*?class="result-container"[^>]*>[\s\S]*?<\/div>/gi; 65 | let _result = resultRegex.exec(resData)?.[0]?.replace(/(<\/?[^>]+>)/gi, ''); 66 | _result = unescape(_result); 67 | result.toParagraphs = _result?.split('\n') || ['暂无结果']; 68 | result.fromParagraphs = text.split('\n'); 69 | } catch (error) { 70 | throw Bob.util.error('api', '接口返回数据解析错误出错', error); 71 | } 72 | 73 | if (cache === 'enable') { 74 | resultCache.set(cacheKey, result); 75 | } 76 | // raw 77 | // result.raw = resData; 78 | return result; 79 | } 80 | 81 | export default { 82 | _translate, 83 | }; 84 | 85 | export { _translate }; 86 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@feq/bobplugin-google-translate", 3 | "version": "0.7.1", 4 | "description": "Bob google 翻译插件", 5 | "homepage": "https://github.com/roojay520/bobplugin-google-translate", 6 | "repository": "https://github.com/roojay520/bobplugin-google-translate.git", 7 | "author": "roojay ", 8 | "license": "MIT", 9 | "main": "src/main.js", 10 | "keywords": [ 11 | "bobplugin", 12 | "translate", 13 | "google-translate" 14 | ], 15 | "scripts": { 16 | "clear": "rimraf ./dist && rimraf ./release", 17 | "initInfo": "node ./scripts/init-info.js", 18 | "install": "npm run initInfo", 19 | "dev": "cross-env NODE_ENV=development rollup -c rollup.config.js --watch", 20 | "build": "npm run clear && npm run initInfo && cross-env NODE_ENV=production rollup -c && node ./scripts/build-zip.js", 21 | "type-check": "tsc --noEmit --allowJs", 22 | "type-check:watch": "tsc --noEmit --allowJs --watch", 23 | "prettier:fix": "prettier --config .prettierrc.js --write .", 24 | "eslint": "eslint . -c .eslintrc.js --ext .ts,.tsx,.js", 25 | "eslint:fix": "eslint . -c .eslintrc.js --fix --ext .ts,.tsx,.js", 26 | "commit": "git-cz", 27 | "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s", 28 | "version": "npm run initInfo && npm run changelog && git add CHANGELOG.md src/info.json", 29 | "prepare": "husky install" 30 | }, 31 | "config": { 32 | "commitizen": { 33 | "path": "node_modules/cz-customizable" 34 | }, 35 | "cz-customizable": { 36 | "config": ".cz-config.js" 37 | } 38 | }, 39 | "lint-staged": { 40 | "**/*.{js, ts, json}": [ 41 | "npm run prettier:fix", 42 | "npm run eslint:fix" 43 | ] 44 | }, 45 | "dependencies": { 46 | "@bob-plug/core": "^0.1.4", 47 | "lodash-es": "^4.17.21", 48 | "querystring": "^0.2.1" 49 | }, 50 | "devDependencies": { 51 | "@commitlint/cli": "^12.1.4", 52 | "@rollup/plugin-commonjs": "^21.0.1", 53 | "@rollup/plugin-json": "^4.1.0", 54 | "@rollup/plugin-node-resolve": "^13.0.6", 55 | "@types/eslint-plugin-prettier": "^3.1.0", 56 | "@types/lodash-es": "^4.17.5", 57 | "@typescript-eslint/eslint-plugin": "^5.2.0", 58 | "@typescript-eslint/parser": "^5.2.0", 59 | "adm-zip": "^0.5.9", 60 | "commitizen": "^4.2.4", 61 | "commitlint-config-cz": "^0.13.2", 62 | "conventional-changelog-cli": "^2.1.1", 63 | "cross-env": "^7.0.3", 64 | "cz-customizable": "^6.3.0", 65 | "esbuild": "^0.13.10", 66 | "eslint": "^8.1.0", 67 | "eslint-config-airbnb-typescript": "^14.0.1", 68 | "eslint-import-resolver-typescript": "^2.5.0", 69 | "eslint-plugin-import": "^2.25.2", 70 | "eslint-plugin-prettier": "^4.0.0", 71 | "fs-extra": "^10.0.0", 72 | "husky": "^7.0.4", 73 | "lint-staged": "^11.2.6", 74 | "prettier": "^2.4.1", 75 | "rimraf": "^3.0.2", 76 | "rollup": "^2.58.3", 77 | "rollup-plugin-copy": "^3.4.0", 78 | "rollup-plugin-esbuild": "^4.6.0", 79 | "rollup-plugin-polyfill-node": "^0.7.0", 80 | "typescript": "^4.4.4" 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/lang.ts: -------------------------------------------------------------------------------- 1 | import { Language } from '@bob-plug/core'; 2 | 3 | type ILang = [Language, string]; 4 | 5 | // https://ripperhe.gitee.io/bob/#/plugin/addtion/language 6 | // Bob 语种标识和第三方语种标识符映射关系 [['bob语种, '第三方接口语种']] 7 | var languageList: ILang[] = [ 8 | ['auto', 'auto'], 9 | ['zh-Hans', 'zh-CN'], 10 | ['zh-Hant', 'zh-TW'], 11 | ['en', 'en'], 12 | ['yue', 'zh'], 13 | ['wyw', 'zh'], 14 | ['en', 'en'], 15 | ['ja', 'ja'], 16 | ['ko', 'ko'], 17 | ['fr', 'fr'], 18 | ['de', 'de'], 19 | ['es', 'es'], 20 | ['it', 'it'], 21 | ['ru', 'ru'], 22 | ['pt', 'pt'], 23 | ['nl', 'nl'], 24 | ['pl', 'pl'], 25 | ['ar', 'ar'], 26 | ['af', 'af'], 27 | ['am', 'am'], 28 | ['az', 'az'], 29 | ['be', 'be'], 30 | ['bg', 'bg'], 31 | ['bn', 'bn'], 32 | ['bs', 'bs'], 33 | ['ca', 'ca'], 34 | ['ceb', 'ceb'], 35 | ['co', 'co'], 36 | ['cs', 'cs'], 37 | ['cy', 'cy'], 38 | ['da', 'da'], 39 | ['el', 'el'], 40 | ['eo', 'eo'], 41 | ['et', 'et'], 42 | ['eu', 'eu'], 43 | ['fa', 'fa'], 44 | ['fi', 'fi'], 45 | ['fj', 'fj'], 46 | ['fy', 'fy'], 47 | ['ga', 'ga'], 48 | ['gd', 'gd'], 49 | ['gl', 'gl'], 50 | ['gu', 'gu'], 51 | ['ha', 'ha'], 52 | ['haw', 'haw'], 53 | ['he', 'he'], 54 | ['hi', 'hi'], 55 | ['hmn', 'hmn'], 56 | ['hr', 'hr'], 57 | ['ht', 'ht'], 58 | ['hu', 'hu'], 59 | ['hy', 'hy'], 60 | ['id', 'id'], 61 | ['ig', 'ig'], 62 | ['is', 'is'], 63 | ['jw', 'jw'], 64 | ['ka', 'ka'], 65 | ['kk', 'kk'], 66 | ['km', 'km'], 67 | ['kn', 'kn'], 68 | ['ku', 'ku'], 69 | ['ky', 'ky'], 70 | ['la', 'lo'], 71 | ['lb', 'lb'], 72 | ['lo', 'lo'], 73 | ['lt', 'lt'], 74 | ['lv', 'lv'], 75 | ['mg', 'mg'], 76 | ['mi', 'mi'], 77 | ['mk', 'mk'], 78 | ['ml', 'ml'], 79 | ['mn', 'mn'], 80 | ['mr', 'mr'], 81 | ['ms', 'ms'], 82 | ['mt', 'mt'], 83 | ['my', 'my'], 84 | ['ne', 'ne'], 85 | ['no', 'no'], 86 | ['ny', 'ny'], 87 | ['or', 'or'], 88 | ['pa', 'pa'], 89 | ['ps', 'ps'], 90 | ['ro', 'ro'], 91 | ['rw', 'rw'], 92 | ['si', 'si'], 93 | ['sk', 'sk'], 94 | ['sl', 'sl'], 95 | ['sm', 'sm'], 96 | ['sn', 'sn'], 97 | ['so', 'so'], 98 | ['sq', 'sq'], 99 | ['sr', 'sr'], 100 | ['sr-Cyrl', 'sr'], 101 | ['sr-Latn', 'sr'], 102 | ['st', 'st'], 103 | ['su', 'su'], 104 | ['sv', 'sv'], 105 | ['sw', 'sw'], 106 | ['ta', 'ta'], 107 | ['te', 'te'], 108 | ['tg', 'tg'], 109 | ['th', 'th'], 110 | ['tk', 'tk'], 111 | ['tl', 'tl'], 112 | ['tr', 'tr'], 113 | ['tt', 'tt'], 114 | ['ug', 'ug'], 115 | ['uk', 'uk'], 116 | ['ur', 'ur'], 117 | ['uz', 'uz'], 118 | ['vi', 'vi'], 119 | ['xh', 'xh'], 120 | ['yi', 'yi'], 121 | ['yo', 'yo'], 122 | ['zu', 'zu'], 123 | ]; 124 | 125 | type IGoogleLanguage = typeof languageList[number][1]; 126 | export type { IGoogleLanguage }; 127 | 128 | // Bob 语种标识符 129 | var standardLangMap = new Map(languageList); 130 | // 第三方语种标识符 131 | var noStandardLangMap = new Map(languageList.map(([standardLang, lang]) => [lang, standardLang])); 132 | 133 | // Bob 语种标识符转服务商语种标识符 134 | function standardToNoStandard(lang: Language): IGoogleLanguage { 135 | return standardLangMap.get(lang) || 'auto'; 136 | } 137 | 138 | // 服务商语种标识符转 Bob 语种标识符 139 | function noStandardToStandard(lang: string): Language { 140 | return noStandardLangMap.get(lang) || 'auto'; 141 | } 142 | 143 | // 获取支持的语种 144 | function getSupportLanguages(): Language[] { 145 | return languageList.map(([standardLang]) => standardLang); 146 | } 147 | 148 | export { getSupportLanguages, standardToNoStandard, noStandardToStandard }; 149 | -------------------------------------------------------------------------------- /src/google-translate.ts: -------------------------------------------------------------------------------- 1 | import * as querystring from 'querystring'; 2 | import * as Bob from '@bob-plug/core'; 3 | import { userAgent } from './util'; 4 | import { IQueryOption, detectLang, tts } from './common'; 5 | import { noStandardToStandard } from './lang'; 6 | import { getBaseApi } from './common'; 7 | 8 | var resultCache = new Bob.CacheResult(); 9 | // 接口请求频率过快导致错误, 隔三分钟再请求 10 | var API_LIMIT_TIME: number = 1000 * 60 * 3; 11 | var apiLimitErrorTime = 0; 12 | 13 | /** 14 | * @description google 翻译 15 | * @param {string} text 需要翻译的文字内容 16 | * @param {object} [options={}] 17 | * @return {object} 一个符合 bob 识别的翻译结果对象 18 | */ 19 | async function _translate(text: string, options: IQueryOption = {}) { 20 | if (text?.length > 5000) { 21 | throw Bob.util.error('param', '翻译文本过长, 单次翻译字符上限为5000'); 22 | } 23 | if (apiLimitErrorTime + API_LIMIT_TIME > Date.now()) throw Bob.util.error('api', '请求频率过快, 请稍后再试'); 24 | apiLimitErrorTime = 0; 25 | const { from = 'auto', to = 'auto', cache = 'enable', timeout = 10000 } = options; 26 | const cacheKey = `${text}${from}${to}${getBaseApi()}`; 27 | if (cache === 'enable') { 28 | const _cacheData = resultCache.get(cacheKey); 29 | if (_cacheData) return _cacheData; 30 | } else { 31 | resultCache.clear(); 32 | } 33 | 34 | const lang = await detectLang(text, options); 35 | const data = { 36 | client: 'gtx', 37 | sl: lang || from, 38 | tl: to, 39 | hl: to, 40 | dt: ['at', 'bd', 'ex', 'ld', 'md', 'qca', 'rw', 'rm', 'ss', 't'], 41 | ie: 'UTF-8', 42 | oe: 'UTF-8', 43 | otf: 1, 44 | ssel: 0, 45 | tsel: 0, 46 | kc: 7, 47 | }; 48 | 49 | const [err, res] = await Bob.util.asyncTo( 50 | Bob.api.$http.post({ 51 | url: `https://${getBaseApi()}/translate_a/single?${querystring.stringify(data)}`, 52 | timeout, 53 | header: { 54 | 'User-Agent': userAgent, 55 | }, 56 | body: { q: text }, 57 | }), 58 | ); 59 | if (res?.response.statusCode === 429) { 60 | apiLimitErrorTime = Date.now(); 61 | throw Bob.util.error('api', '接口请求频率过快', err); 62 | } 63 | 64 | if (err) throw Bob.util.error('network', '接口网络错误', err); 65 | 66 | const resData = res?.data; 67 | Bob.api.$log.info(JSON.stringify(res)); 68 | if (!Bob.util.isArray(resData)) throw Bob.util.error('api', '接口返回数据出错', res); 69 | 70 | const result: Bob.Result = { from: noStandardToStandard(from), to: noStandardToStandard(to), toParagraphs: [] }; 71 | 72 | try { 73 | const [paragraphs, dict] = resData; 74 | if (Bob.util.isArrayAndLenGt(paragraphs, 1)) { 75 | let _paragraphs = ''; 76 | let _fromParagraphs = ''; 77 | paragraphs.slice(0, -1).forEach((_paragraph: string[]) => { 78 | if (!Bob.util.isArrayAndLenGt(_paragraph, 1)) return; 79 | const [targetStr, sourceStr] = _paragraph; 80 | if (Bob.util.isString(targetStr)) _paragraphs += targetStr; 81 | if (Bob.util.isString(sourceStr)) _fromParagraphs += sourceStr; 82 | }); 83 | result.toParagraphs = _paragraphs.split('\n'); 84 | result.fromParagraphs = _fromParagraphs.split('\n'); 85 | } 86 | if (Bob.util.isArrayAndLenGt(dict, 0)) { 87 | result.toDict = { parts: [], phonetics: [] }; 88 | const parts = dict 89 | .filter((item: Bob.PartObject) => Bob.util.isArrayAndLenGt(item, 0)) 90 | .map(([part, means]: [string, string[]]) => Bob.util.isArrayAndLenGt(means, 0) && { part, means }) 91 | .filter((item: Bob.PartObject) => !!item); 92 | if (Bob.util.isArrayAndLenGt(parts, 0)) result.toDict.parts = parts; 93 | const ttsUrl = tts(text, { from: lang || from }); 94 | result.fromTTS = { type: 'url', value: ttsUrl }; 95 | result.toDict.phonetics = [{ type: 'us', value: '发音', tts: { type: 'url', value: ttsUrl, raw: {} } }]; 96 | } 97 | } catch (error) { 98 | throw Bob.util.error('api', '接口返回数据解析错误出错', error); 99 | } 100 | 101 | if (cache === 'enable') { 102 | resultCache.set(cacheKey, result); 103 | } 104 | // raw 105 | // result.raw = resData; 106 | return result; 107 | } 108 | 109 | export default { 110 | _translate, 111 | }; 112 | 113 | export { _translate }; 114 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [0.7.1](https://github.com/roojay520/bobplugin-google-translate/compare/v0.7.0...v0.7.1) (2023-04-09) 2 | 3 | 4 | ### Bug Fixes 5 | 6 | * 修正版本更新文件地址的错误 ([6243b7e](https://github.com/roojay520/bobplugin-google-translate/commit/6243b7ec74ee960cbb308e410aa546c131a69ca7)) 7 | 8 | 9 | 10 | # [0.7.0](https://github.com/roojay520/bobplugin-google-translate/compare/v0.6.1...v0.7.0) (2023-04-09) 11 | 12 | 13 | ### Bug Fixes 14 | 15 | * 将特殊字符串分隔作为可配置项, 默认关闭 issues [#21](https://github.com/roojay520/bobplugin-google-translate/issues/21) ([13fea9f](https://github.com/roojay520/bobplugin-google-translate/commit/13fea9f6bd168d7181af60a81a7e2edd01c6b435)) 16 | 17 | 18 | 19 | ## [0.6.1](https://github.com/roojay520/bobplugin-google-translate/compare/v0.6.0...v0.6.1) (2022-11-06) 20 | 21 | 22 | 23 | # [0.6.0](https://github.com/roojay520/bobplugin-google-translate/compare/v0.5.0...v0.6.0) (2022-11-06) 24 | 25 | ### Features 26 | 27 | - 去掉一些失效的配置项, 新增基础 URL 自定义功能; ([47ae6e6](https://github.com/roojay520/bobplugin-google-translate/commit/47ae6e6efff87730dbf689f43970e74119957975)) 28 | 29 | # [0.5.0](https://github.com/roojay520/bobplugin-google-translate/compare/v0.4.2...v0.5.0) (2021-10-29) 30 | 31 | ## [0.4.2](https://github.com/roojay520/bobplugin-google-translate/compare/v0.4.1...v0.4.2) (2021-05-20) 32 | 33 | ### Features 34 | 35 | - 新增汉语拼音注释 ([28c20fa](https://github.com/roojay520/bobplugin-google-translate/commit/28c20facc2dff823d3ccf50cc3e48973650430dc)) 36 | 37 | ## [0.4.1](https://github.com/roojay520/bobplugin-google-translate/compare/v0.4.0...v0.4.1) (2021-05-17) 38 | 39 | # [0.4.0](https://github.com/roojay520/bobplugin-google-translate/compare/v0.3.5...v0.4.0) (2021-05-17) 40 | 41 | ### Features 42 | 43 | - 新增 RPC 方式调用翻译接口 ([c88266c](https://github.com/roojay520/bobplugin-google-translate/commit/c88266c690b206b096688f5c1d67a736d5e1df82)) 44 | 45 | ## [0.3.5](https://github.com/roojay520/bobplugin-google-translate/compare/v0.3.4...v0.3.5) (2020-12-02) 46 | 47 | ## [0.3.4](https://github.com/roojay520/bobplugin-google-translate/compare/v0.3.3...v0.3.4) (2020-12-02) 48 | 49 | ### Bug Fixes 50 | 51 | - 临时过渡方案, 解决 google 接口升级导致 token 不可用问题 ([28e4e5d](https://github.com/roojay520/bobplugin-google-translate/commit/28e4e5db5034d0d43abf151443050951ff5fbe5d)) 52 | - 优化结果缓存方式,修复切换源或目标语言时翻译结果不更新的问题 ([f904290](https://github.com/roojay520/bobplugin-google-translate/commit/f904290bdad307e7711e8972e6c34dcd5044909e)) 53 | 54 | ## [0.3.3](https://github.com/roojay520/bobplugin-google-translate/compare/v0.3.2...v0.3.3) (2020-11-05) 55 | 56 | ### Bug Fixes 57 | 58 | - 修复秘钥获取出错的问题 issues [#3](https://github.com/roojay520/bobplugin-google-translate/issues/3) ([a0cfd05](https://github.com/roojay520/bobplugin-google-translate/commit/a0cfd05ce1a1ad04c0c98bc3c9fbef830f35747f)) 59 | 60 | ## [0.3.2](https://github.com/roojay520/bobplugin-google-translate/compare/v0.3.1...v0.3.2) (2020-10-12) 61 | 62 | ### Bug Fixes 63 | 64 | - 修复截图翻译换行失效问题, 优化特殊字符分隔 ([9d368e5](https://github.com/roojay520/bobplugin-google-translate/commit/9d368e5a848359dbe900c72847d6de32823fcbc2)) 65 | 66 | ## [0.3.1](https://github.com/roojay520/bobplugin-google-translate/compare/v0.3.0...v0.3.1) (2020-10-10) 67 | 68 | # [0.3.0](https://github.com/roojay520/bobplugin-google-translate/compare/v0.2.2...v0.3.0) (2020-10-10) 69 | 70 | ### Features 71 | 72 | - 新增插件检查更新 ([6cffdd4](https://github.com/roojay520/bobplugin-google-translate/commit/6cffdd483bed143ea23e3961ac4837d1f5fc61ec)) 73 | 74 | ## [0.2.2](https://github.com/roojay520/bobplugin-google-translate/compare/v0.2.1...v0.2.2) (2020-09-30) 75 | 76 | ### Bug Fixes 77 | 78 | - 修正 http hander 字段 ([57190e0](https://github.com/roojay520/bobplugin-google-translate/commit/57190e071344d9c5f59a5a3487a48bc7f81f5800)) 79 | 80 | ## [0.2.1](https://github.com/roojay520/bobplugin-google-translate/compare/v0.2.0...v0.2.1) (2020-09-30) 81 | 82 | ### Bug Fixes 83 | 84 | - 修复 libs 打包问题 ([baca2f1](https://github.com/roojay520/bobplugin-google-translate/commit/baca2f1d450aad92e7e724352c928c6e7ee9176c)) 85 | 86 | # [0.2.0](https://github.com/roojay520/bobplugin-google-translate/compare/v0.1.3...v0.2.0) (2020-09-30) 87 | 88 | ## [0.1.3](https://github.com/roojay520/bobplugin-google-translate/compare/v0.1.2...v0.1.3) (2020-09-16) 89 | 90 | ### Bug Fixes 91 | 92 | - 修复 issues[#1](https://github.com/roojay520/bobplugin-google-translate/issues/1) 长文本分段展示不全的问题,修复缓存禁用失效的问题 ([385e017](https://github.com/roojay520/bobplugin-google-translate/commit/385e0175def739b0a39dad336cf0203ca4cea94c)) 93 | 94 | ## [0.1.2](https://github.com/roojay520/bobplugin-google-translate/compare/v0.1.1...v0.1.2) (2020-08-19) 95 | 96 | ## 0.1.1 (2020-08-19) 97 | -------------------------------------------------------------------------------- /src/appcast.json: -------------------------------------------------------------------------------- 1 | { 2 | "identifier": "com.roojay.bobplugin-google-translate", 3 | "versions": [ 4 | { 5 | "version": "0.7.1", 6 | "desc": "https://github.com/roojay520/bobplugin-google-translate/blob/master/CHANGELOG.md", 7 | "sha256": "c631a283772bab5536c51d661c6061798df5c9651b1fcf0d741017ad2ed37619", 8 | "url": "https://github.roojay.com/roojay520/bobplugin-google-translate/releases/download/v0.7.1/google-translate-v0.7.1.bobplugin", 9 | "minBobVersion": "0.5.0" 10 | }, 11 | { 12 | "version": "0.7.0", 13 | "desc": "https://github.com/roojay520/bobplugin-google-translate/blob/master/CHANGELOG.md", 14 | "sha256": "66e4f6b027fd1127cac4bc76abf91be26bd76e4795a88c1dae7b43b356aa7c5d", 15 | "url": "https://github.roojay.com/roojay520/bobplugin-google-translate/releases/download/v0.7.0/google-translate-v0.7.0.bobplugin", 16 | "minBobVersion": "0.5.0" 17 | }, 18 | { 19 | "version": "0.6.1", 20 | "desc": "https://github.com/roojay520/bobplugin-google-translate/blob/master/CHANGELOG.md", 21 | "sha256": "2eaf461d23adaa3c6fdcaf8cba8c9105d2fba99932787143f89cacaa6e5ad0fa", 22 | "url": "https://github.roojay.com/roojay520/bobplugin-google-translate/releases/download/v0.6.1/google-translate-v0.6.1.bobplugin", 23 | "minBobVersion": "0.5.0" 24 | }, 25 | { 26 | "version": "0.6.0", 27 | "desc": "https://github.com/roojay520/bobplugin-google-translate/blob/master/CHANGELOG.md", 28 | "sha256": "2f931701d23a1d31a0ca9610b78ec42b9a1060f3eb1f674bc56d06ae592d5ead", 29 | "url": "https://github.roojay.com/roojay520/bobplugin-google-translate/releases/download/v0.6.0/google-translate-v0.6.0.bobplugin", 30 | "minBobVersion": "0.5.0" 31 | }, 32 | { 33 | "version": "0.5.0", 34 | "desc": "https://github.com/roojay520/bobplugin-google-translate/blob/master/CHANGELOG.md", 35 | "sha256": "a9349c67a6adcaac299c4a335e4d14fefdea4b7ca95d0a7ec6c732fd541881d9", 36 | "url": "https://github.roojay.com/roojay520/bobplugin-google-translate/releases/download/v0.5.0/google-translate-v0.5.0.bobplugin", 37 | "minBobVersion": "0.5.0" 38 | }, 39 | { 40 | "version": "0.4.2", 41 | "desc": "https://github.com/roojay520/bobplugin-google-translate/blob/master/CHANGELOG.md", 42 | "sha256": "d6260e96c70b40768e053732eff2f4b72dbc4a60dc9ce3bf6222c261e0bc96e8", 43 | "url": "https://github.roojay.com/roojay520/bobplugin-google-translate/releases/download/v0.4.2/google-translate-v0.4.2.bobplugin", 44 | "minBobVersion": "0.5.0" 45 | }, 46 | { 47 | "version": "0.4.1", 48 | "desc": "https://github.com/roojay520/bobplugin-google-translate/blob/master/CHANGELOG.md", 49 | "sha256": "8e76926967e71545e9a8e706ed263a76cbf78f1d7598ba5db0d47950d6a1cd36", 50 | "url": "https://github.roojay.com/roojay520/bobplugin-google-translate/releases/download/v0.4.1/google-translate-v0.4.1.bobplugin", 51 | "minBobVersion": "0.5.0" 52 | }, 53 | { 54 | "version": "0.3.5", 55 | "desc": "https://github.com/roojay520/bobplugin-google-translate/blob/master/CHANGELOG.md", 56 | "sha256": "77b2dfe1491acb14bd3e65a2e58d58a4746a36764b7bd0c2d0d299069855a8e4", 57 | "url": "https://github.roojay.com/roojay520/bobplugin-google-translate/releases/download/v0.3.5/google-translate-v0.3.5.bobplugin", 58 | "minBobVersion": "0.5.0" 59 | }, 60 | { 61 | "version": "0.3.3", 62 | "desc": "https://github.com/roojay520/bobplugin-google-translate/blob/master/CHANGELOG.md", 63 | "sha256": "96920c6ada9575cac8a140107f7caafba36f9a294f1d05c687c25b49ecfe0a3a", 64 | "url": "https://github.roojay.com/roojay520/bobplugin-google-translate/releases/download/v0.3.3/google-translate-v0.3.3.bobplugin", 65 | "minBobVersion": "0.5.0" 66 | }, 67 | { 68 | "version": "0.3.2", 69 | "desc": "https://github.com/roojay520/bobplugin-google-translate/blob/master/CHANGELOG.md", 70 | "sha256": "0a9c9ecd06542a0cf8d192de1dbc3fc8b6133963d7851173ae34d5392cd243f0", 71 | "url": "https://github.roojay.com/roojay520/bobplugin-google-translate/releases/download/v0.3.2/google-translate-v0.3.2.bobplugin", 72 | "minBobVersion": "0.5.0" 73 | }, 74 | { 75 | "version": "0.3.1", 76 | "desc": "https://github.com/roojay520/bobplugin-google-translate/blob/master/CHANGELOG.md", 77 | "sha256": "f9b753d894cf076274cd2ce152c3a34bf8266c577e1964e21f52b51e5c865b93", 78 | "url": "https://github.roojay.com/roojay520/bobplugin-google-translate/releases/download/v0.3.1/google-translate-v0.3.1.bobplugin", 79 | "minBobVersion": "0.5.0" 80 | } 81 | ] 82 | } 83 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["src/**/*.ts", "types/**/*.ts"], 3 | "exclude": ["node_modules", "dist"], 4 | "compilerOptions": { 5 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 6 | /* Basic Options */ 7 | // "incremental": true, /* Enable incremental compilation */ 8 | "target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, 9 | "module": "ESNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, 10 | // "lib": [], /* Specify library files to be included in the compilation. */ 11 | "allowJs": true /* Allow javascript files to be compiled. */, 12 | // "checkJs": true, /* Report errors in .js files. */ 13 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 14 | "declaration": true /* Generates corresponding '.d.ts' file. */, 15 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 16 | "sourceMap": true /* Generates corresponding '.map' file. */, 17 | // "outFile": "./", /* Concatenate and emit output to single file. */ 18 | "outDir": "./dist" /* Redirect output structure to the directory. */, 19 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 20 | // "composite": true, /* Enable project compilation */ 21 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 22 | // "removeComments": true, /* Do not emit comments to output. */ 23 | // "noEmit": true, /* Do not emit outputs. */ 24 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 25 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 26 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 27 | 28 | /* Strict Type-Checking Options */ 29 | "strict": true /* Enable all strict type-checking options. */, 30 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 31 | "strictNullChecks": true /* Enable strict null checks. */, 32 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 33 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 34 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 35 | "noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */, 36 | "alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */, 37 | 38 | /* Additional Checks */ 39 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 40 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 41 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 42 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 43 | 44 | /* Module Resolution Options */ 45 | "moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */, 46 | "baseUrl": "./" /* Base directory to resolve non-absolute module names. */, 47 | // "paths": { } /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */, 48 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 49 | // "typeRoots": ["node_modules/@types", "./types", "types"] /* List of folders to include type definitions from. */, 50 | // "types": ["node"] /* Type declaration files to be included in compilation. */, 51 | "allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */, 52 | "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, 53 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 54 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 55 | 56 | /* Source Map Options */ 57 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 58 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 59 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 60 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 61 | 62 | /* Experimental Options */ 63 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 64 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 65 | 66 | /* Advanced Options */ 67 | "skipLibCheck": true /* Skip type checking of declaration files. */, 68 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/google-translate-rpc.ts: -------------------------------------------------------------------------------- 1 | import * as querystring from 'querystring'; 2 | import * as Bob from '@bob-plug/core'; 3 | import { tts as _audio, IQueryOption } from './common'; 4 | import { userAgent } from './util'; 5 | import { noStandardToStandard } from './lang'; 6 | import { getBaseApi } from './common'; 7 | 8 | enum Rpc { 9 | translate = 'MkEWBc', 10 | tts = 'jQ1olc', 11 | } 12 | 13 | // 参考自: https://github.com/vitalets/google-translate-api/blob/master/index.js 14 | function parseTranslateRes(text: string) { 15 | var json = text.slice(6); 16 | var length = ''; 17 | 18 | var result = { 19 | text: '', 20 | pronunciation: '', 21 | from: { 22 | language: '', 23 | }, 24 | dict: { 25 | parts: [], 26 | }, 27 | raw: '', 28 | }; 29 | 30 | try { 31 | length = /^\d+/.exec(json)?.[0] || ''; 32 | if (!length) return result; 33 | json = JSON.parse(json.slice(length?.length, parseInt(length, 10) + length.length)); 34 | json = JSON.parse(json[0][2]); 35 | result.raw = json; 36 | } catch (e) { 37 | return result; 38 | } 39 | 40 | if (Bob.util.isNil(json?.[1]?.[0]?.[0]?.[5])) { 41 | // translation not found, could be a hyperlink or gender-specific translation? 42 | result.text = json?.[1]?.[0]?.[0]?.[0] || ''; 43 | } else { 44 | const mean = json[1][0][0][5] as any; 45 | result.text = mean 46 | .map((obj: any[]) => obj[0]) 47 | .filter(Boolean) 48 | // Google api seems to split text per sentences by 49 | // So we join text back with spaces. 50 | // See: https://github.com/vitalets/google-translate-api/issues/73 51 | .join(' '); 52 | } 53 | const dict = json?.[3]?.[5]?.[0] as any; 54 | if (Bob.util.isArrayAndLenGt(dict, 0)) { 55 | const parts = dict 56 | .filter((item: Bob.PartObject) => Bob.util.isArrayAndLenGt(item, 0)) 57 | .map(([part, means]: [string, string[]]) => { 58 | if (!Bob.util.isArrayAndLenGt(means, 0)) { 59 | return false; 60 | } 61 | const meanList = means.map((mean) => mean[0]); 62 | return { part: `${part}.`, means: meanList }; 63 | }) 64 | .filter((item: Bob.PartObject) => !!item); 65 | if (Bob.util.isArrayAndLenGt(parts, 0)) result.dict.parts = parts; 66 | } 67 | 68 | result.pronunciation = json[1][0][0][1]; 69 | 70 | // From language 71 | if (json[0] && json[0][1] && json[0][1][1]) { 72 | result.from.language = json[0][1][1][0]; 73 | } else if (json[1][3] === 'auto') { 74 | result.from.language = json[2]; 75 | } else { 76 | result.from.language = json[1][3]; 77 | } 78 | return result; 79 | } 80 | 81 | function extract(key: string, res: Bob.HttpResponse) { 82 | const re = new RegExp(`"${key}":".*?"`); 83 | const result = re.exec(res.data as string); 84 | if (result !== null) { 85 | return result[0].replace(`"${key}":"`, '').slice(0, -1); 86 | } 87 | return ''; 88 | } 89 | 90 | var config = new Bob.Cache('google-translate-api'); 91 | async function getRpcParams(rpcids: Rpc, opts: IQueryOption) { 92 | const updateTime = Date.now(); 93 | const cacheUpdateTime = 1000 * 60 * 60 * 24 * 1; // 缓存时间一天 94 | let { translate = {} } = config.getAll(); 95 | let { params, time } = translate; 96 | if (updateTime - cacheUpdateTime < time && params?.bl && params?.['f.sid']) { 97 | return params; 98 | } 99 | const { timeout = 10000 } = opts; 100 | const [err, res] = await Bob.util.asyncTo( 101 | Bob.api.$http.get({ 102 | timeout, 103 | url: `https://${getBaseApi()}`, 104 | header: { 105 | 'User-Agent': userAgent, 106 | Cookie: '', 107 | }, 108 | }), 109 | ); 110 | if (err) throw Bob.util.error('network', '秘钥接口网络错误', err); 111 | if (!res) throw Bob.util.error('api', '秘钥返回数据出错', res); 112 | 113 | params = { 114 | rpcids, 115 | 'f.sid': extract('FdrFJe', res), 116 | bl: extract('cfb2h', res), 117 | hl: 'en-US', 118 | 'soc-app': 1, 119 | 'soc-platform': 1, 120 | 'soc-device': 1, 121 | _reqid: Math.floor(1000 + Math.random() * 9000), 122 | rt: 'c', 123 | }; 124 | if (params) { 125 | config.set('translate', { params, updateTime }); 126 | return params; 127 | } 128 | throw Bob.util.error('api', '秘钥获取失败', res); 129 | } 130 | 131 | var resultCache = new Bob.CacheResult(); 132 | // 接口请求频率过快导致错误, 隔三分钟再请求 133 | var API_LIMIT_TIME: number = 1000 * 60 * 3; 134 | var apiLimitErrorTime = 0; 135 | 136 | async function _translate(text: string, opts: IQueryOption = {}) { 137 | if (text?.length > 5000) { 138 | throw Bob.util.error('param', '翻译文本过长, 单次翻译字符上限为5000'); 139 | } 140 | const { from = 'auto', to = 'auto', cache = 'enable', timeout = 10000 } = opts; 141 | const baseApi = `https://${getBaseApi()}`; 142 | if (apiLimitErrorTime + API_LIMIT_TIME > Date.now()) throw Bob.util.error('api', '请求频率过快, 请稍后再试'); 143 | apiLimitErrorTime = 0; 144 | const cacheKey = `${text}${from}${to}${getBaseApi()}`; 145 | if (cache === 'enable') { 146 | const _cacheData = resultCache.get(cacheKey); 147 | if (_cacheData) return _cacheData; 148 | } else { 149 | resultCache.clear(); 150 | } 151 | const params = await getRpcParams(Rpc.translate, opts); 152 | const url = `${baseApi}/_/TranslateWebserverUi/data/batchexecute?${querystring.stringify(params)}`; 153 | const [err, res] = await Bob.util.asyncTo( 154 | Bob.api.$http.post({ 155 | timeout, 156 | url, 157 | header: { 158 | 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 159 | 'User-Agent': userAgent, 160 | Cookie: '', 161 | }, 162 | body: { 163 | 'f.req': JSON.stringify([[[Rpc.translate, JSON.stringify([[text, from, to, true], [null]]), null, 'generic']]]), 164 | }, 165 | }), 166 | ); 167 | 168 | if (res?.response.statusCode === 429) { 169 | apiLimitErrorTime = Date.now(); 170 | throw Bob.util.error('api', '接口请求频率过快', err); 171 | } 172 | 173 | if (err || !res) throw Bob.util.error('network', '接口网络错误', err); 174 | 175 | const resData = res?.data; 176 | const data = parseTranslateRes(resData as string); 177 | const result: Bob.Result = { from: noStandardToStandard(from), to: noStandardToStandard(to), toParagraphs: [] }; 178 | 179 | try { 180 | result.toParagraphs = [data.text]; 181 | 182 | const dict = data.raw?.[3]?.[5]?.[0] as any; 183 | if (Bob.util.isArrayAndLenGt(dict, 0)) { 184 | result.toDict = { parts: data.dict.parts, phonetics: [] }; 185 | 186 | const ttsUrl = _audio(text, { from: from }); 187 | result.fromTTS = { type: 'url', value: ttsUrl }; 188 | const zh = ['zh-Hans', 'zh-Hant', 'zh-CN']; 189 | let pinyin = '发音'; 190 | if (zh.includes(from)) { 191 | pinyin = data.raw?.[0]?.[0] || '发音'; 192 | } 193 | result.toDict.phonetics = [{ type: 'us', value: pinyin, tts: { type: 'url', value: ttsUrl, raw: {} } }]; 194 | } 195 | } catch (error) { 196 | throw Bob.util.error('api', '接口返回数据解析错误出错', error); 197 | } 198 | 199 | if (cache === 'enable') { 200 | resultCache.set(cacheKey, result); 201 | } 202 | return result; 203 | } 204 | 205 | export { _translate }; 206 | --------------------------------------------------------------------------------