├── .babelrc ├── .editorconfig ├── .eslintignore ├── .eslintrc.js ├── .github └── workflows │ └── release.yml ├── .gitignore ├── .prettierrc.js ├── CHANGELOG.md ├── LICENSE ├── README.md ├── package.json ├── rollup.config.js ├── scripts ├── build-zip.js ├── config.js ├── init-appcast.js └── init-info.js ├── src ├── appcast.json ├── info.json ├── lang.ts ├── libs │ └── human-string.js ├── main.ts ├── translate.ts └── util.ts ├── tsconfig.eslint.json ├── tsconfig.json └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "modules": false, 7 | "targets": { 8 | "esmodules": true 9 | } 10 | } 11 | ], 12 | "@babel/preset-typescript" 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /.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 -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | dist/ 3 | 4 | .DS_Store 5 | 6 | *.log 7 | 8 | .vscode -------------------------------------------------------------------------------- /.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/require-await': 'off', 46 | '@typescript-eslint/no-unsafe-call': 'off', 47 | '@typescript-eslint/no-explicit-any': 'off', 48 | '@typescript-eslint/no-var-requires': 'off', 49 | '@typescript-eslint/no-unsafe-return': 'off', 50 | '@typescript-eslint/no-throw-literal': 'off', 51 | '@typescript-eslint/naming-convention': '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 | -------------------------------------------------------------------------------- /.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.GITHUB_TOKEN }} 15 | 16 | - uses: actions/setup-node@v2-beta 17 | with: 18 | node-version: '14' 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 'TingV' 28 | git config --global user.email 'TingV@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.GITHUB_TOKEN }} 35 | 36 | - uses: ncipollo/release-action@v1 37 | with: 38 | artifacts: 'release/*.bobplugin' 39 | token: ${{ secrets.GITHUB_TOKEN }} 40 | -------------------------------------------------------------------------------- /.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 -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingv/bobplugin-google-translate/ca2050e29e03b2bb6a0135ed543e2d8a03aaf94e/CHANGELOG.md -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 TingV 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # bobplugin-google-translate 2 | 3 | > 这是 [Bob](https://github.com/ripperhe/Bob) 的 Google 翻译插件,使用它无需申请 API 秘钥。 4 | 5 | ## 特性 6 | 7 | - 支持缓存查询结果(默认缓存过期时间为一周); 8 | 9 | ## 安装 10 | 11 | 1. 安装 [Bob](https://github.com/ripperhe/Bob/releases) (version >= 0.50) 12 | 2. 下载插件: [bobplugin-google-translate](https://github.com/TingV/bobplugin-google-translate/releases) 13 | 3. 插件安装: [Bob 插件安装文档说明](https://github.com/ripperhe/Bob/blob/master/docs/general/quickstart/plugin.md#%E5%AE%89%E8%A3%85%E6%8F%92%E4%BB%B6) 14 | 15 | ## 开发 16 | 17 | 方法见 [这篇教程](https://github.com/roojay520/bob-plug/blob/master/packages/cli/README.md) -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "bobplugin-google-translate", 3 | "version": "1.1.0", 4 | "description": "Google 翻译插件,无需申请 API 秘钥", 5 | "homepage": "https://github.com/tingv/bobplugin-google-translate", 6 | "repository": "https://github.com/tingv/bobplugin-google-translate.git", 7 | "author": "TingV", 8 | "license": "MIT", 9 | "main": "src/main.js", 10 | "keywords": [ 11 | "bobplugin", 12 | "translate" 13 | ], 14 | "scripts": { 15 | "clear": "rimraf ./dist && rimraf ./release", 16 | "initInfo": "node ./scripts/init-info.js", 17 | "install": "npm run initInfo", 18 | "dev": "cross-env NODE_ENV=development rollup -c rollup.config.js --watch", 19 | "build": "npm run clear && npm run initInfo && cross-env NODE_ENV=production rollup -c && node ./scripts/build-zip.js", 20 | "type-check": "tsc --noEmit --allowJs", 21 | "type-check:watch": "tsc --noEmit --allowJs --watch", 22 | "prettier:fix": "prettier --config .prettierrc.js --write .", 23 | "eslint": "eslint . -c .eslintrc.js --ext .ts,.tsx,.js", 24 | "eslint:fix": "eslint . -c .eslintrc.js --fix --ext .ts,.tsx,.js", 25 | "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s", 26 | "version": "npm run initInfo && npm run changelog && git add CHANGELOG.md src/info.json" 27 | }, 28 | "dependencies": { 29 | "@bob-plug/core": "^0.1.3", 30 | "querystring": "^0.2.1" 31 | }, 32 | "devDependencies": { 33 | "@babel/core": "^7.14.6", 34 | "@babel/preset-env": "^7.14.7", 35 | "@babel/preset-typescript": "^7.14.5", 36 | "@rollup/plugin-babel": "^5.3.0", 37 | "@rollup/plugin-commonjs": "^19.0.0", 38 | "@rollup/plugin-json": "^4.1.0", 39 | "@rollup/plugin-node-resolve": "^13.0.0", 40 | "@types/eslint-plugin-prettier": "^3.1.0", 41 | "@typescript-eslint/eslint-plugin": "^4.28.2", 42 | "@typescript-eslint/parser": "^4.28.2", 43 | "adm-zip": "^0.5.5", 44 | "conventional-changelog-cli": "^2.1.1", 45 | "cross-env": "^7.0.3", 46 | "esbuild": "^0.12.15", 47 | "eslint": "^7.30.0", 48 | "eslint-config-airbnb-typescript": "^12.3.1", 49 | "eslint-import-resolver-typescript": "^2.4.0", 50 | "eslint-plugin-import": "^2.23.4", 51 | "eslint-plugin-prettier": "^3.4.0", 52 | "fs-extra": "^10.0.0", 53 | "prettier": "^2.3.2", 54 | "rimraf": "^3.0.2", 55 | "rollup": "^2.52.8", 56 | "rollup-plugin-copy": "^3.4.0", 57 | "rollup-plugin-esbuild": "^4.5.0", 58 | "rollup-plugin-polyfill-node": "^0.6.2", 59 | "typescript": "^4.3.5" 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import path from 'path'; 2 | import copy from 'rollup-plugin-copy'; 3 | import json from '@rollup/plugin-json'; 4 | import babel from '@rollup/plugin-babel'; 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 | import packageJson from './package.json'; 10 | 11 | const pkg = `${packageJson.name}.bobplugin`; 12 | 13 | const RollupConfig = { 14 | input: path.join(__dirname, './src/main.ts'), 15 | output: { 16 | format: 'cjs', 17 | exports: 'auto', 18 | file: path.join(__dirname, `./dist/${pkg}/main.js`), 19 | globals: { 20 | $util: '$util', 21 | $http: '$http', 22 | $info: '$info', 23 | $option: '$option', 24 | $log: '$log', 25 | $data: '$data', 26 | $file: '$file', 27 | } 28 | }, 29 | plugins: [ 30 | copy({ 31 | targets: [ 32 | { src: './src/info.json', dest: `dist/${pkg}/` }, 33 | { src: './src/libs', dest: `dist/${pkg}/` }, 34 | ], 35 | }), 36 | json({ namedExports: false }), 37 | resolve({ 38 | extensions: ['.js', '.ts', '.json'], 39 | preferBuiltins: false, 40 | }), 41 | commonjs(), 42 | nodePolyfills(), 43 | babel({ 44 | extensions: ['.js', '.ts'], 45 | babelHelpers: 'bundled', 46 | exclude: 'node_modules/**', 47 | }), 48 | esbuild({ 49 | // All options are optional 50 | include: /\.[jt]?s$/, // default, inferred from `loaders` option 51 | exclude: /node_modules/, // default 52 | sourceMap: false, // default 53 | minify: process.env.NODE_ENV === 'production', 54 | target: 'es6', // default, or 'es20XX', 'esnext', 55 | // Add extra loaders 56 | loaders: { 57 | // Add .json files support 58 | // require @rollup/plugin-commonjs 59 | '.json': 'json', 60 | }, 61 | }), 62 | ], 63 | external: ['crypto-js'] 64 | }; 65 | 66 | export default RollupConfig; -------------------------------------------------------------------------------- /scripts/build-zip.js: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: roojay 3 | * @Description: 生成最终以 .bobplugin 结尾的安装包文件 4 | */ 5 | 6 | const path = require('path'); 7 | const AdmZip = require('adm-zip'); 8 | const initAppcast = require('./init-appcast'); 9 | const plugInfo = require('../src/info.json'); 10 | const config = require('./config'); 11 | 12 | const pkg = `${config.pkgName}-v${plugInfo.version}.bobplugin`; 13 | const pkgPath = path.resolve(__dirname, `../release/${pkg}`); 14 | 15 | const zip = new AdmZip(); 16 | zip.addLocalFolder(path.resolve(__dirname, `../dist/${config.pkgName}.bobplugin`)); 17 | zip.writeZip(pkgPath); 18 | 19 | initAppcast(); 20 | -------------------------------------------------------------------------------- /scripts/config.js: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: roojay 3 | * @Description: 打包相关的配置文件 4 | */ 5 | 6 | const config = { 7 | pkgName: 'bobplugin-google-translate', 8 | github:{ 9 | username: 'tingv', 10 | repository: 'bobplugin-google-translate' 11 | } 12 | }; 13 | 14 | module.exports = config; 15 | -------------------------------------------------------------------------------- /scripts/init-appcast.js: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: roojay 3 | * @Description: 根据配置文件(config.js,info.json) 生成 appcast.json 版本更新文件 4 | */ 5 | 6 | const path = require('path'); 7 | const fs = require('fs-extra'); 8 | const crypto = require('crypto'); 9 | 10 | const config = require('./config'); 11 | const plugInfo = require('../src/info.json'); 12 | const plugAppcast = require('../src/appcast.json'); 13 | 14 | const pkg = `${config.pkgName}-v${plugInfo.version}.bobplugin`; 15 | const repositoryUrl = `https://github.com/${config.github.username}/${config.github.repository}`; 16 | const releaseUrl = `${repositoryUrl}/releases/download`; 17 | 18 | module.exports = () => { 19 | const pkgPath = path.resolve(__dirname, `../release/${pkg}`); 20 | const appcastPath = path.join(__dirname, '../src/appcast.json'); 21 | 22 | const fileBuffer = fs.readFileSync(pkgPath); 23 | const sum = crypto.createHash('sha256'); 24 | sum.update(fileBuffer); 25 | const hex = sum.digest('hex'); 26 | 27 | const version = { 28 | version: plugInfo.version, 29 | desc: `${repositoryUrl}/blob/master/CHANGELOG.md`, 30 | sha256: hex, 31 | url: `${releaseUrl}/v${plugInfo.version}/${pkg}`, 32 | minBobVersion: plugInfo.minBobVersion, 33 | }; 34 | 35 | let versions = (plugAppcast && plugAppcast.versions) || []; 36 | if (!Array.isArray(versions)) versions = []; 37 | const index = versions.findIndex((v) => v.version === plugInfo.version); 38 | if (index === -1) { 39 | versions.splice(0, 0, version); 40 | } else { 41 | versions.splice(index, 1, version); 42 | } 43 | const appcastData = { identifier: plugInfo.identifier, versions }; 44 | fs.outputJSONSync(appcastPath, appcastData, { spaces: 2 }); 45 | }; 46 | -------------------------------------------------------------------------------- /scripts/init-info.js: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: roojay 3 | * @Description: 使用 package.json 里面的部分字段(version, author, homepage, description)覆盖 info.json 里面的数据 4 | */ 5 | const path = require('path'); 6 | const fs = require('fs-extra'); 7 | 8 | const config = require('./config'); 9 | const info = require('../src/info.json'); 10 | const packageJson = require('../package.json'); 11 | 12 | const appcast = `https://raw.githubusercontent.com/${config.github.username}/${config.github.repository}/master/src/appcast.json`; 13 | 14 | const { version, author = '', homepage = '', description = '' } = packageJson; 15 | const infoData = { ...info, version, author, homepage, summary: description, appcast }; 16 | const infoPath = path.join(__dirname, '../src/info.json'); 17 | 18 | fs.outputJSONSync(infoPath, infoData, { spaces: 2 }); 19 | -------------------------------------------------------------------------------- /src/appcast.json: -------------------------------------------------------------------------------- 1 | { 2 | "identifier": "com.tingv.bobplugin.googletranslate", 3 | "versions": [ 4 | { 5 | "version": "1.1.0", 6 | "desc": "https://github.com/tingv/bobplugin-google-translate/blob/master/CHANGELOG.md", 7 | "sha256": "df3fe9157a6fff14bdb39408d5cc70664dad6b854981dd135b43ea5cc6b34090", 8 | "url": "https://github.com/tingv/bobplugin-google-translate/releases/download/v1.1.0/bobplugin-google-translate-v1.1.0.bobplugin", 9 | "minBobVersion": "0.5.0" 10 | }, 11 | { 12 | "version": "1.0.2", 13 | "desc": "https://github.com/tingv/bobplugin-google-translate/blob/master/CHANGELOG.md", 14 | "sha256": "b3e8c58bd140338c8585b3c15f51fe8b16fdf76925ec3a23698fb8cbe4c6ad66", 15 | "url": "https://github.com/tingv/bobplugin-google-translate/releases/download/v1.0.2/bobplugin-google-translate-v1.0.2.bobplugin", 16 | "minBobVersion": "0.5.0" 17 | }, 18 | { 19 | "version": "1.0.1", 20 | "desc": "https://github.com/tingv/bobplugin-google-translate/blob/master/CHANGELOG.md", 21 | "sha256": "a7c46839b5287251be5fb37780f31b20c1b2daa4baff9a0a268fdefed8a8a5dd", 22 | "url": "https://github.com/tingv/bobplugin-google-translate/releases/download/v1.0.1/bobplugin-google-translate-v1.0.1.bobplugin", 23 | "minBobVersion": "0.5.0" 24 | } 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /src/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "identifier": "com.tingv.bobplugin.googletranslate", 3 | "category": "translate", 4 | "version": "1.1.0", 5 | "name": "Google 翻译", 6 | "summary": "Google 翻译插件,无需申请 API 秘钥", 7 | "author": "TingV", 8 | "appcast": "https://raw.githubusercontent.com/tingv/bobplugin-google-translate/master/src/appcast.json", 9 | "homepage": "https://github.com/tingv/bobplugin-google-translate", 10 | "icon": "113", 11 | "minBobVersion": "0.5.0", 12 | "options": [ 13 | { 14 | "identifier": "cache", 15 | "type": "menu", 16 | "title": "缓存", 17 | "defaultValue": "disable", 18 | "menuValues": [ 19 | { 20 | "title": "开启", 21 | "value": "enable" 22 | }, 23 | { 24 | "title": "关闭", 25 | "value": "disable" 26 | } 27 | ] 28 | }, 29 | { 30 | "identifier": "tld", 31 | "type": "menu", 32 | "title": "接口域名", 33 | "defaultValue": "com", 34 | "menuValues": [ 35 | { 36 | "title": "google.com (国际)", 37 | "value": "com" 38 | }, 39 | { 40 | "title": "google.cn (国内)", 41 | "value": "cn" 42 | } 43 | ] 44 | }, 45 | { 46 | "identifier": "iBooksCleanup", 47 | "type": "menu", 48 | "title": "iBooks 清理", 49 | "defaultValue": "disable", 50 | "menuValues": [ 51 | { 52 | "title": "开启", 53 | "value": "enable" 54 | }, 55 | { 56 | "title": "关闭", 57 | "value": "disable" 58 | } 59 | ] 60 | } 61 | ] 62 | } 63 | -------------------------------------------------------------------------------- /src/lang.ts: -------------------------------------------------------------------------------- 1 | import { Language } from '@bob-plug/core'; 2 | 3 | type ILang = [Language, string]; 4 | 5 | // https://github.com/ripperhe/Bob/blob/master/docs/plugin/addtion/language.md 6 | // https://cloud.google.com/translate/docs/languages 7 | // Bob 语种标识和第三方语种标识符映射关系 [['bob语种, '第三方接口语种']] 8 | var languageList: ILang[] = [ 9 | ['auto', 'auto'], 10 | ['zh-Hans', 'zh-CN'], 11 | ['zh-Hant', 'zh-TW'], 12 | ['en', 'en'], 13 | ['de', 'de'], 14 | ['fr', 'fr'], 15 | ['it', 'it'], 16 | ['ja', 'ja'], 17 | ['ko', 'ko'], 18 | ['es', 'es'], 19 | ['nl', 'nl'], 20 | ['pl', 'pl'], 21 | ['pt', 'pt'], 22 | ['ru', 'ru'], 23 | ]; 24 | 25 | // Bob 语种标识符 26 | var standardLangMap = new Map(languageList); 27 | // 第三方语种标识符 28 | var noStandardLangMap = new Map(languageList.map(([standardLang, lang]) => [lang, standardLang])); 29 | 30 | // Bob 语种标识符转服务商语种标识符 31 | function standardToNoStandard(lang: Language) { 32 | return standardLangMap.get(lang); 33 | } 34 | 35 | // 服务商语种标识符转 Bob 语种标识符 36 | function noStandardToStandard(lang: string) { 37 | return noStandardLangMap.get(lang); 38 | } 39 | 40 | // 获取支持的语种 41 | function getSupportLanguages() { 42 | return languageList.map(([standardLang]) => standardLang); 43 | } 44 | 45 | export { getSupportLanguages, standardToNoStandard, noStandardToStandard }; 46 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import * as Bob from '@bob-plug/core'; 2 | import { getSupportLanguages } from './lang'; 3 | import { _translate } from './translate'; 4 | 5 | // 使用 bob 实现的 require 方法加载本地库, 6 | var formatString = require('./libs/human-string'); 7 | 8 | 9 | export function supportLanguages(): Bob.supportLanguages { 10 | return getSupportLanguages(); 11 | } 12 | 13 | 14 | // https://ripperhe.gitee.io/bob/#/plugin/quickstart/translate 15 | export function translate(query: Bob.TranslateQuery, completion: Bob.Completion) { 16 | const { text = '', detectFrom, detectTo } = query; 17 | const str = formatString(text); 18 | const params = { from: detectFrom, to: detectTo, cache: Bob.api.getOption('cache'), tld: Bob.api.getOption('tld'), iBooksCleanup: Bob.api.getOption('iBooksCleanup'), }; 19 | let res = _translate(str, params); 20 | 21 | res 22 | .then((result) => completion({ result })) 23 | .catch((error) => { 24 | Bob.api.$log.error(JSON.stringify(error)); 25 | if (error?.type) return completion({ error }); 26 | completion({ error: Bob.util.error('api', '插件出错', error) }); 27 | }); 28 | } 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/translate.ts: -------------------------------------------------------------------------------- 1 | import querystring from 'querystring'; 2 | import * as Bob from '@bob-plug/core'; 3 | import { userAgent } from './util'; 4 | import { standardToNoStandard } from './lang'; 5 | 6 | var CryptoJS = require("crypto-js"); 7 | 8 | interface QueryOption { 9 | to?: Bob.Language; 10 | from?: Bob.Language; 11 | cache?: string; 12 | tld?: string; 13 | timeout?: number; 14 | iBooksCleanup?: string; 15 | } 16 | 17 | var resultCache = new Bob.CacheResult('translate-result'); 18 | 19 | /** 20 | * @description 翻译 21 | * @param {string} text 需要翻译的文字内容 22 | * @param {object} [options={}] 23 | * @return {object} 一个符合 bob 识别的翻译结果对象 24 | */ 25 | async function _translate(text: string, options: QueryOption = {}): Promise { 26 | const { from = 'auto', to = 'auto', cache = 'disable', tld = 'com', timeout = 10000, iBooksCleanup = 'disable' } = options; 27 | 28 | const sourceLanguage = standardToNoStandard(from); 29 | const targetLanguage = standardToNoStandard(to); 30 | 31 | // 清理从 iBooks 中提取的内容 32 | if (iBooksCleanup === 'enable') { 33 | const matchText = text.match(/^“([\s\S]*)”\n+摘录来自:/); 34 | if (matchText && typeof matchText[1] !== "undefined") { 35 | text = matchText[1]; 36 | } 37 | } 38 | 39 | const cacheKey = CryptoJS.MD5(`${text}${from}${to}`); 40 | if (cache === 'enable') { 41 | const _cacheData = resultCache.get(cacheKey); 42 | if (_cacheData) return _cacheData; 43 | } else { 44 | resultCache.clear(); 45 | } 46 | 47 | const result: Bob.TranslateResult = { from, to, toParagraphs: [] }; 48 | 49 | try { 50 | // 在此处实现翻译的具体处理逻辑 51 | 52 | // 查询参数 53 | const data = { 54 | sl: sourceLanguage, 55 | tl: targetLanguage, 56 | hl: targetLanguage, 57 | q: text, 58 | }; 59 | 60 | // 查询 61 | const [err, res] = await Bob.util.asyncTo( 62 | Bob.api.$http.get({ 63 | url: `https://translate.google.${tld}/m?${querystring.stringify(data)}`, 64 | timeout, 65 | header: { 'User-Agent': userAgent }, 66 | }), 67 | ); 68 | 69 | if (res?.response.statusCode !== 200) throw Bob.util.error('api', '接口响应状态错误', err); 70 | if (err) throw Bob.util.error('api', '接口网络错误', err); 71 | 72 | const html = res?.data; // 获取 HTML 73 | 74 | if (!Bob.util.isString(html)) throw Bob.util.error('api', '接口返回数据类型出错', res); 75 | if (html.indexOf('"result-container"') == -1 ) throw Bob.util.error('api', '接口返回数据不存在', res); 76 | 77 | const matchResults = html.match(/"result-container">([\s\S]*)<\/div>