Repository: windingwind/zotero-pdf-translate
Branch: main
Commit: ac9657c77066
Files: 128
Total size: 445.3 KB
Directory structure:
gitextract_bhxnv728/
├── .gitattributes
├── .github/
│ ├── FUNDING.yml
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.yml
│ │ ├── config.yml
│ │ └── feature_request.yml
│ ├── dependabot.yml
│ └── workflows/
│ ├── issuebot.yml
│ ├── prbot.yml
│ └── release.yml
├── .gitignore
├── .husky/
│ └── pre-commit
├── .prettierignore
├── .prettierrc.json
├── .vscode/
│ ├── extensions.json
│ ├── launch.json
│ ├── settings.json
│ └── toolkit.code-snippets
├── LICENSE
├── README.md
├── addon/
│ ├── bootstrap.js
│ ├── chrome/
│ │ └── content/
│ │ ├── preferences.xhtml
│ │ ├── standalone.xhtml
│ │ └── styles/
│ │ ├── mathTextbox.css
│ │ ├── panel.css
│ │ └── standalone.css
│ ├── locale/
│ │ ├── en-US/
│ │ │ ├── addon.ftl
│ │ │ ├── mainWindow.ftl
│ │ │ ├── panel.ftl
│ │ │ ├── preferences.ftl
│ │ │ └── standalone.ftl
│ │ ├── it-IT/
│ │ │ ├── addon.ftl
│ │ │ ├── mainWindow.ftl
│ │ │ ├── panel.ftl
│ │ │ ├── preferences.ftl
│ │ │ └── standalone.ftl
│ │ └── zh-CN/
│ │ ├── addon.ftl
│ │ ├── mainWindow.ftl
│ │ ├── panel.ftl
│ │ ├── preferences.ftl
│ │ └── standalone.ftl
│ ├── manifest.json
│ └── prefs.js
├── eslint.config.mjs
├── package.json
├── src/
│ ├── addon.ts
│ ├── api.ts
│ ├── elements/
│ │ ├── base.ts
│ │ ├── mathTextbox.ts
│ │ └── panel.ts
│ ├── extras/
│ │ └── customElements.ts
│ ├── hooks.ts
│ ├── index.ts
│ ├── modules/
│ │ ├── defaultPrefs.ts
│ │ ├── fields.ts
│ │ ├── infoBox.ts
│ │ ├── itemTree.ts
│ │ ├── menu.ts
│ │ ├── notify.ts
│ │ ├── popup.ts
│ │ ├── preferenceWindow.ts
│ │ ├── prompt.ts
│ │ ├── reader.ts
│ │ ├── services/
│ │ │ ├── _template.ts
│ │ │ ├── aliyun.ts
│ │ │ ├── baidu.ts
│ │ │ ├── baidufield.ts
│ │ │ ├── base.ts
│ │ │ ├── bing.ts
│ │ │ ├── bingdict.ts
│ │ │ ├── caiyun.ts
│ │ │ ├── cambridgedict.ts
│ │ │ ├── claude.ts
│ │ │ ├── cnki.ts
│ │ │ ├── collinsdict.ts
│ │ │ ├── deepl.ts
│ │ │ ├── deeplcustom.ts
│ │ │ ├── deeplx.ts
│ │ │ ├── freedictionaryapi.ts
│ │ │ ├── gemini.ts
│ │ │ ├── google.ts
│ │ │ ├── gpt.ts
│ │ │ ├── haici.ts
│ │ │ ├── haicidict.ts
│ │ │ ├── huoshan.ts
│ │ │ ├── huoshanweb.ts
│ │ │ ├── index.ts
│ │ │ ├── libretranslate.ts
│ │ │ ├── microsoft.ts
│ │ │ ├── mtranserver.ts
│ │ │ ├── niutrans.ts
│ │ │ ├── nllb.ts
│ │ │ ├── openl.ts
│ │ │ ├── pot.ts
│ │ │ ├── qwenmt.ts
│ │ │ ├── tencent.ts
│ │ │ ├── tencenttransmart.ts
│ │ │ ├── webliodict.ts
│ │ │ ├── xftrans.ts
│ │ │ ├── youdao.ts
│ │ │ ├── youdaodict.ts
│ │ │ ├── youdaozhiyun.ts
│ │ │ └── youdaozhiyunllm.ts
│ │ ├── settings/
│ │ │ ├── manageKeys.ts
│ │ │ └── renameServices.ts
│ │ ├── shortcuts.ts
│ │ └── tabpanel.ts
│ └── utils/
│ ├── config.ts
│ ├── crypto.ts
│ ├── index.ts
│ ├── llmPrompt.ts
│ ├── locale.ts
│ ├── mathRenderer.ts
│ ├── prefs.ts
│ ├── secret.ts
│ ├── settingsDialog.ts
│ ├── str.ts
│ ├── task.ts
│ ├── wait.ts
│ ├── window.ts
│ └── ztoolkit.ts
├── tsconfig.json
├── typings/
│ ├── global.d.ts
│ ├── i10n.d.ts
│ └── prefs.d.ts
├── update-beta.json
├── update.json
├── update.rdf
└── zotero-plugin.config.ts
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
* text=auto eol=lf
================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms
github: [windingwind]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
custom: ["https://paypal.me/windingwind"]
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.yml
================================================
name: Bug report
description: File a bug / issue
title: "[Bug] "
labels:
- bug
# - Needs Triage
assignees: windingwind
body:
- type: checkboxes
id: check-search
attributes:
label: Is there an existing issue for this?
description: Please search to see if an issue already exists for the bug you encountered.
options:
- label: I have searched the existing issues
required: true
- type: checkboxes
id: check-frequent
attributes:
label: Have you checked the FAQ (https://github.com/windingwind/zotero-pdf-translate/issues/6)?
description: Please check the FAQ to see if your question has already been answered.
options:
- label: I have checked the FAQ
required: true
- type: checkboxes
id: check-version
attributes:
label: Are you using the latest Zotero and the latest plugin?
description: Only bug reports that can be reproduced on the latest Zotero and plugin will be considered.
options:
- label: I have confirmed I'm using the latest Zotero and the latest plugin
required: true
- type: textarea
attributes:
label: Environment
description: |
examples:
- **OS**: Windows 11 22H2
- **Zotero Version**: 7.0.0
- **Plugin Version**: 1.0.0
value: |
- OS:
- Zotero Version:
- Plugin Version:
validations:
required: true
- type: textarea
id: description
attributes:
label: Describe the bug
description: |
A clear and concise description of what the bug is.
If applicable, add screenshots and log to help explain your problem.
validations:
required: true
- type: textarea
id: debug-output
attributes:
label: Debug Output
description: |
Steps to get debug output:
1. Disable all other plugins, exit Zotero, and restart Zotero
2. menu -> `Help` -> `Debug Output` -> `View Output`
3. Do steps to reproduce the bug
4. In the debug output window, press `Ctrl/Cmd + S`
5. Upload the debug output here
validations:
required: true
- type: textarea
id: additional-context
attributes:
label: Anything else?
description: |
Links? References? Anything that will give us more context about the issue you are encountering!
Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in.
validations:
required: false
================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
contact_links:
- name: Documentation in Chinese (中文文档)
url: https://zotero.yuque.com/staff-gkhviy/pdf-trans
about: 如果你是中文用户,请先阅读中文文档。文档中已经说明的问题不会回复。
================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.yml
================================================
name: Feature request
description: Suggest an idea for this project
title: "[Feature] "
labels:
- enhancement
assignees: windingwind
body:
- type: checkboxes
id: check-search
attributes:
label: Is there an existing issue for this?
description: Please search to see if an issue already exists for this feature request.
options:
- label: I have searched the existing issues
required: true
- type: textarea
attributes:
label: Environment
description: |
examples:
- **OS**: Windows 11 22H2
- **Zotero Version**: 7.0.0
- **Plugin Version**: 1.0.0
value: |
- OS:
- Zotero Version:
- Plugin Version:
validations:
required: true
- type: textarea
id: description
attributes:
label: Describe the feature request
value: |
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Why do you need this feature?**
A clear and concise description of why you need this feature.
validations:
required: false
- type: textarea
id: solution
attributes:
label: Describe the solution you'd like
value: |
**The solution you'd like**
A clear and concise description of what you want to happen.
**Alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
validations:
required: false
- type: textarea
id: additional-context
attributes:
label: Anything else?
description: |
Links? References? Anything that will give us more context about the issue you are encountering!
Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in.
validations:
required: false
================================================
FILE: .github/dependabot.yml
================================================
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "npm" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"
groups:
all-non-major:
update-types:
- "minor"
- "patch"
================================================
FILE: .github/workflows/issuebot.yml
================================================
name: Close inactive issues
on:
schedule:
- cron: "30 1 * * *"
issues:
types:
- labeled
jobs:
close-issues:
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- uses: actions/stale@v9
with:
days-before-issue-stale: 30
days-before-issue-close: 7
stale-issue-label: "stale"
stale-issue-message: "This issue is stale because it has been open for 30 days with no activity."
close-issue-message: "This issue was closed because it has been inactive for 7 days since being marked as stale."
exempt-issue-labels: "help wanted"
days-before-pr-stale: -1
days-before-pr-close: -1
repo-token: ${{ secrets.GITHUB_TOKEN }}
issue-invalid:
name: close invalid issue
if: github.event.label.name == 'invalid'
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- uses: actions-cool/issues-helper@v3
with:
actions: close-issue, create-comment
token: ${{ secrets.GITHUB_TOKEN }}
body: |
Hello @${{ github.event.issue.user.login }}. This issue is marked as `invalid` and closed. Please make sure you are reporting an issue and following the issue template.
issue-duplicate:
name: close duplicate issue
if: github.event.label.name == 'duplicate'
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- uses: actions-cool/issues-helper@v3
with:
actions: close-issue, create-comment
token: ${{ secrets.GITHUB_TOKEN }}
body: |
Hello @${{ github.event.issue.user.login }}. This issue is marked as `duplicate` and closed. Please make sure you have searched to see if an issue already exists for the bug you encountered.
================================================
FILE: .github/workflows/prbot.yml
================================================
name: Pull Request
on:
pull_request_target:
types: [opened, synchronize, reopened]
permissions:
contents: write # allow pushing code
pull-requests: write # allow commenting on PRs
jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: true
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
- name: Install dependencies
run: npm ci
- name: Run lint
run: npm run lint
- name: Commit & push fixes
id: git_push
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
if ! git diff --quiet; then
git add .
git commit -m "chore: apply lint fixes"
if git push "https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git" \
HEAD:${{ github.head_ref }}; then
echo "push_succeeded=true" >> $GITHUB_OUTPUT
else
echo "push_succeeded=false" >> $GITHUB_OUTPUT
fi
else
echo "push_succeeded=true" >> $GITHUB_OUTPUT
fi
- name: Comment on PR if push failed
if: steps.git_push.outputs.push_succeeded == 'false'
uses: peter-evans/create-or-update-comment@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
issue-number: ${{ github.event.pull_request.number }}
body: |
@${{ github.event.pull_request.user.login }}
I automatically applied lint fixes but couldn’t push to your branch—could you please run:
```bash
npm run lint
```
and push the results? Thanks!
================================================
FILE: .github/workflows/release.yml
================================================
name: Release
on:
push:
tags:
- v**
permissions:
contents: write
issues: write
pull-requests: write
jobs:
release:
runs-on: ubuntu-latest
env:
GITHUB_TOKEN: ${{ secrets.GitHub_TOKEN }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
- name: Install deps
run: npm install -f
- name: Build
run: |
npm run build
- name: Release to GitHub
run: |
npm run release
# cp build/update.json update.json
# cp build/update-beta.json update-beta.json
# git add update.json
# git add update-beta.json
# git commit -m 'chore(publish): synchronizing `update.json`'
# git push
sleep 1s
- name: Notify release
uses: apexskier/github-release-commenter@v1
continue-on-error: true
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
comment-template: |
:rocket: _This ticket has been resolved in {release_tag}. See {release_link} for release notes._
================================================
FILE: .gitignore
================================================
build
logs
node_modules
pnpm-lock.yaml
yarn.lock
tsconfig.tsbuildinfo
zotero-cmd.json
.DS_Store
.env
.scaffold
================================================
FILE: .husky/pre-commit
================================================
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx lint-staged
================================================
FILE: .prettierignore
================================================
.vscode
build
logs
node_modules
package-lock.json
yarn.lock
pnpm-lock.yaml
# zotero-cmd.json
================================================
FILE: .prettierrc.json
================================================
{
"printWidth": 80,
"tabWidth": 2,
"endOfLine": "lf",
"overrides": [
{
"files": ["*.xhtml"],
"options": {
"htmlWhitespaceSensitivity": "css"
}
}
]
}
================================================
FILE: .vscode/extensions.json
================================================
{
"recommendations": [
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"macabeus.vscode-fluent"
]
}
================================================
FILE: .vscode/launch.json
================================================
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Restart",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "restart-dev"]
},
{
"type": "node",
"request": "launch",
"name": "Restart in Prod Mode",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "restart-prod"]
}
]
}
================================================
FILE: .vscode/settings.json
================================================
{
"editor.formatOnType": false,
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"typescript.tsdk": "node_modules/typescript/lib"
}
================================================
FILE: .vscode/toolkit.code-snippets
================================================
{
"appendElement - full": {
"scope": "javascript,typescript",
"prefix": "appendElement",
"body": [
"appendElement({",
"\ttag: '${1:div}',",
"\tid: '${2:id}',",
"\tnamespace: '${3:html}',",
"\tclassList: ['${4:class}'],",
"\tstyles: {${5:style}: '$6'},",
"\tproperties: {},",
"\tattributes: {},",
"\t[{ '${7:onload}', (e: Event) => $8, ${9:false} }],",
"\tcheckExistanceParent: ${10:HTMLElement},",
"\tignoreIfExists: ${11:true},",
"\tskipIfExists: ${12:true},",
"\tremoveIfExists: ${13:true},",
"\tcustomCheck: (doc: Document, options: ElementOptions) => ${14:true},",
"\tchildren: [$15]",
"}, ${16:container});",
],
},
"appendElement - minimum": {
"scope": "javascript,typescript",
"prefix": "appendElement",
"body": "appendElement({ tag: '$1' }, $2);",
},
"register Notifier": {
"scope": "javascript,typescript",
"prefix": "registerObserver",
"body": [
"registerObserver({",
"\t notify: (",
"\t\tevent: _ZoteroTypes.Notifier.Event,",
"\t\ttype: _ZoteroTypes.Notifier.Type,",
"\t\tids: string[],",
"\t\textraData: _ZoteroTypes.anyObj",
"\t) => {",
"\t\t$0",
"\t}",
"});",
],
},
}
================================================
FILE: LICENSE
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
.
================================================
FILE: README.md
================================================
# Translate for Zotero
[](https://www.zotero.org)
[](https://github.com/windingwind/zotero-plugin-template)
_Translate for Zotero_, a.k.a. _Zotero PDF Translate_, is a [Zotero](https://www.zotero.org/) plugin.
Translate PDF, EPub, webpage, metadata, annotations, notes to the target language. Support 20+ translate services.
[中文文档](https://zotero.yuque.com/books/share/4443494c-c698-4e08-9d1e-ed253390346d)

# Quick Start Guide
## Install
- Download the plugin (.xpi file) from below.
- [Latest Stable](https://github.com/windingwind/zotero-pdf-translate/releases/latest)
- [All Releases](https://github.com/windingwind/zotero-pdf-translate/releases)
_Note_ If you're using Firefox as your browser, right-click the `.xpi` and select "Save As.."
- In Zotero click `Tools` in the top menu bar and then click `Plugins`
- Go to the Extensions page and then click the gear icon in the top right.
- Select `Install Plugin from file`.
- Browse to where you downloaded the `.xpi` file and select it.
- Finish!
## Usage
Open any PDF/EPub/webpage in the Zotero reader.
- Select text, the translations are shown on the pop-up and the item pane(v0.2.0).

- Highlight/Underline some text, the translations are added to the annotation comment(v0.3.0); Modify & retranslate the annotation text in the item pane and click the `Update Annotation` to modify the annotation text and translation(v0.6.6);
- Add selected text along with translation to note(v0.4.0); _Only works when a note editor is active._

- Translate item titles with right-click menu or shortcut `Ctrl+T`(v0.6.0).
- Translate item abstract with right-click menu(v0.8.0). Thanks @iShareStuff
- Standalone translation window available(v0.7.0). View & compare translations from multiply services in one window!

- Dictionary for single word translation(v0.7.1).
- SentenceBySentence Translation(v1.1.0). After a translation, press `shift`+`P` and select `Translate Sentences`. _Only for en2zh and en2en now_. Thanks @MuiseDestiny
- Since v2.2.0, the concat mode shortcut is ctrl (on Windows/Linux) or ⌘ (on macOS).
### Q&A
**Q** I want to translate manually.
**A** Go to `Edit->Settings->Translate->General`, uncheck the `Automatically Translate Selection`. Click the `Translate` button on the pop-up or item pane to translate.
**Q** I want a translate shortcut.
**A**
Press shortcut `Ctrl+T` after you selected some text. If you are in the collection view, the titles' translation will show/hide.
**Q** I want to concat different selections and translate them together.
**A** Press `Ctrl/⌘` or select the `Concat Mode` check box on item pane when selecting text in PDF/EPub/webpage.
**Q** Not the language I want.
**A** The default target language is the same as your Zotero language. Go to `Edit->Settings->Translate->Service` and change the language settings.
**Q** Translation not correct or report an error.
**A** See _Language Settings_ above and FAQ([#6](https://github.com/windingwind/zotero-pdf-translate/issues/6)). Make sure you use the right secret.
**Q** I want to change the font size.
**A** Go to `Edit->Settings->Translate->User Interface` and set the font size.
**Q** I want to resize the raw and result text area in the translate panel.
**A** Drag the separator up and down to adjust the size. Double-click the separator to reset the size.
## Settings
### General
- Automatically Translate Selection, default `true`
- Automatically Translate Annotation: Save annotation's translation to annotation comment or annotation body, default `false`
- Automatically Translate Annotation from Sync: Automatically translate annotations synced from other devices if `true`, default `false`
- Enable Reader Selection Pop-up: Show results in the pop-up panel or only in the item pane, default `true`
- Show "Add Translation to Note" in Pop-up: default `true`
> Invisible if no active note editor opened.
- Replace Raw: Use translation to replace the raw text when adding to note, default `false`
- Enable Dictionary: Single word will be translated using dictionary service instead of translate service, default `true`
- Show Play Buttons: Show the word pronunciation play buttons if available, default `true`
- Auto-play Pronunciation, default `false`
### Service
The default service is Google Translate. Currently, we support:
| Translate Service | Require Secret | Supported Languages |
| ---------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Google Translate | No **[Free]** | [100+](https://translate.google.com/about/languages/) |
| Google Translate(API) | No **[Free]** | Use `translate.googleapis.com` |
| CNKI | No **[Free]** | |
| Haici Translate | No **[Free]** | |
| Youdao Translate | No **[Free]** | [100+?](https://ai.youdao.com/DOCSIRMA/html/trans/api/wbfy/index.html) |
| Bing | No **[Free]** | [en-zh](https://learn.microsoft.com/en-us/azure/ai-services/translator/text-translation/reference/v3/reference) |
| DeepLX | No **[Free]** | Based on [DeepLX](https://github.com/OwO-Network/DeepLX?tab=readme-ov-file) |
| DeepLX(API) | No **[Require config]** | [DeepLX](https://github.com/OwO-Network/DeepLX?tab=readme-ov-file) related projects |
| LibreTranslate | Optional **[Require config]** | [LibreTranslate](https://github.com/LibreTranslate/LibreTranslate) |
| MTranServer | Optional **[Require config]** | [MTranServer](https://github.com/xxnuo/MTranServer) |
| NLLB | No **[Require config]** | [nllb-api](https://github.com/winstxnhdw/nllb-api?tab=readme-ov-file#self-hosting) or [NLLB Serve](https://github.com/thammegowda/nllb-serve?tab=readme-ov-file#setup) |
| Pot | No **[Require config]** | [Pot](https://github.com/pot-app/pot-desktop) _Translate results show in Pot_ |
| Huoshan | Yes | [50+](https://www.volcengine.com/docs/4640/127681) |
| Volcengine Web | No **[Free]** | [en, zh, and more (auto-detect, web version)](https://translate.volcengine.com/) |
| Youdao Zhiyun | Yes | [100+](https://ai.youdao.com/DOCSIRMA/html/trans/api/wbfy/index.html) |
| Youdao LLM | Yes | [LLM-based](https://ai.youdao.com/DOCSIRMA/html/trans/api/dmxfy/index.html)(en-zh) |
| Niu Trans | Yes | [400+](https://niutrans.com/documents/contents/trans_text#accessMode) |
| Microsoft Translate | Yes(free 2M) | [200+](https://docs.microsoft.com/en-us/azure/cognitive-services/translator/language-support) |
| LingoCloud(Caiyun) Translate | Yes | [10+](https://docs.caiyunapp.com/lingocloud-api/index.html) |
| DeepL Translate | Yes(free 500k) | [100+](https://www.deepl.com/pro?cta=header-prices/#developer) |
| Aliyun Translate | Yes(free-1M) | [200+](https://help.aliyun.com/document_detail/158269.html) |
| Baidu Translate | Yes(free-QPS1/free-2M) | [200+](https://fanyi-api.baidu.com/product/11) |
| Baidu Field | Yes(free-QPS1/free-2M) | [en-zh](https://fanyi-api.baidu.com/product/12) |
| OpenL | Yes | [11](https://docs.openl.club/#/API/format) |
| Tencent Translate | Yes(QPS5, free-5M) | [15](https://cloud.tencent.com/document/product/551/7372) |
| Tencent Transmart | No **[Free]** | [en, zh, and more (auto-detect, web version)](https://transmart.qq.com/) |
| Xftrans | Yes(free 2M) | [Xftrans API](https://www.xfyun.cn/doc/nlp/xftrans/API.html)(70+), [NiuTrans API](https://www.xfyun.cn/doc/nlp/niutrans/API.html)(100+) |
| GPT | Yes(free-$18) | [OpenAI](https://openai.com/pricing#chat)(ChatGPT), [AzureGPT](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/reference#chat-completions), compatible GPT-like LLM (Custom GPT) |
| Gemini | Yes(free-) | [LLM-based](https://ai.google.dev/available_regions#available_languages) |
| Qwen-MT | Yes(free-) | [LLM-based](https://help.aliyun.com/zh/model-studio/user-guide/machine-translation) |
| Claude | Yes | [LLM-based](https://docs.anthropic.com/claude/docs/getting-started-with-the-claude-api) |
> If the service you want is not yet supported, please post an issue.
**Google**
Google does not require a secret, but you can put your own API URL in the secret to replace the default URL (translate.google.com/translate.googleapi.com).
**Huoshan**
Apply [here](https://www.volcengine.com/docs/4640/65067).
The secret format is `accessKeyId#accessKeySecret`
**Youdao Zhiyun Translate 有道智云**
Apply [here](https://ai.youdao.com/login.s).
The secret format is `MY_APPID#MY_SECRET#MY_VOCABID(optional)`.
> About `VOCABID`
> 登录控制台,选择文本翻译服务,点击右侧的术语表,选择新建,填写表名称和语言方向,添加需要的术语表,然后获取对应词表 id 即可。
> About `Config -> Domain`
> 登录控制台,点击创建应用,输入应用名称,在*选择服务*一栏勾选**文本翻译**,然后勾选**领域化翻译**即可开通领域化翻译。领域化翻译仅支持中英互译。
>
> [Official Document](https://ai.youdao.com/DOCSIRMA/html/trans/api/wbfy/index.html)
**Youdao LLM Translate 有道智云子曰大模型**
Apply [here](https://ai.youdao.com/login.s).
The secret format is `MY_APPID#MY_SECRET`.
> 登录控制台,点击创建应用,输入应用名称,在*选择服务*一栏勾选**大模型翻译**,大模型翻译仅支持中英互译。
>
> [Official Document](https://ai.youdao.com/DOCSIRMA/html/trans/api/dmxfy/index.html)
**NiuTrans**
Apply [here](https://niutrans.com/NiuTransAuthCenter/login).
The secret format is `MY_APIKEY#dictNo(optional)#memoryNo(optional)`.
> [Chinese Document](https://doc.tern.1c7.me/zh/folder/setting/#%E5%B0%8F%E7%89%9B)
**Microsoft Translate**
Apply [here](https://docs.microsoft.com/en-us/azure/cognitive-services/translator/quickstart-translator?tabs=csharp). Copy your secret and paste it into the settings.
The secret format is `serviceKEY#region(required if the region is not global)`.
> See [this issue](https://github.com/windingwind/zotero-pdf-translate/issues/3#issuecomment-1064688597) for detailed steps to set up the Microsoft Translate.
**LingoCloud(Caiyun) Translate**
Apply [here](https://docs.caiyunapp.com/lingocloud-api/index.html#%E7%94%B3%E8%AF%B7%E8%AE%BF%E9%97%AE%E4%BB%A4%E7%89%8C).
**DeepL Translate**
Apply [official API](https://www.deepl.com/pro?cta=header-prices/#developer) or [third-party API](https://deepl-pro.com/#/translate).
The secret format is `secretToken` or `secretToken#glossaryId` (if you want to specify some translate glossary).
**Aliyun Translate**
Apply [here](https://www.aliyun.com/product/ai/base_alimt).
The secret format is `accessKeyId#accessKeySecret#endpoint(optional)`.
> The endpoint is the region of the service, default `https://mt.aliyuncs.com`. For `cn-hangzhou`, the endpoint is `mt.cn-hangzhou.aliyuncs.com`. See also [here](https://help.aliyun.com/zh/machine-translation/developer-reference/api-alimt-2018-10-12-endpoint?spm=a2c4g.11186623.help-menu-30396.d_4_1_0.6c702fa7WlNkX1).
> [Chinese Document](https://help.aliyun.com/document_detail/158269.html)
**Baidu Translate**
Apply [here](https://fanyi-api.baidu.com/product/11).
The secret format is `MY_APPID#MY_KEY#ACTION(optional, see https://api.fanyi.baidu.com/doc/21, default 0)`(split with '#').
**Baidu Field Translate 百度垂直领域翻译**
Apply [here](https://fanyi-api.baidu.com/product/12).
The secret format is `MY_APPID#MY_KEY#DOMAIN_CODE`(split with '#').
| Domain Code | 领域 | 支持语言方向 |
| ----------- | ------------ | ------------------------------------- |
| it | 信息技术领域 | 中文(简)-> 英语、英语 -> 中文(简) |
| finance | 金融财经领域 | 中文(简)-> 英语、英语 -> 中文(简) |
| machinery | 机械制造领域 | 中文(简)-> 英语、英语 -> 中文(简) |
| senimed | 生物医药领域 | 中文(简)-> 英语、英语 -> 中文(简) |
| novel | 网络文学领域 | 中文(简)-> 英语 |
| academic | 学术论文领域 | 中文(简)-> 英语、英语 -> 中文(简) |
| aerospace | 航空航天领域 | 中文(简)-> 英语、英语 -> 中文(简) |
| wiki | 人文社科领域 | 中文(简)-> 英语 |
| news | 新闻资讯领域 | 中文(简)-> 英语、英语 -> 中文(简) |
| law | 法律法规领域 | 中文(简)-> 英语、英语 -> 中文(简) |
| contract | 合同领域 | 中文(简)-> 英语、英语 -> 中文(简) |
> [Chinese Document](https://doc.tern.1c7.me/zh/folder/setting/#%E8%85%BE%E8%AE%AF%E4%BA%91)
**OpenL Translate**
Apply [here](https://my.openl.club/).
The secret format is `service1,service2,...#apikey`(split with '#'; split service codes with ',').
Supported service codes are: `deepl,youdao,tencent,aliyun,baidu,caiyun,wechat,sogou,azure,ibm,aws,google`, See [Service Code](https://docs.openl.club/#/API/format?id=%e7%bf%bb%e8%af%91%e6%9c%8d%e5%8a%a1%e4%bb%a3%e7%a0%81%e5%90%8d)
> [Chinese Document](https://docs.openl.club/#/)
**Tencent Translate**
Apply [here](https://cloud.tencent.com/product/tmt).
The secret format is `secretId#SecretKey#Region(optional, default ap-shanghai)#ProjectId(optional, default 0)`(split with '#').
> [Chinese Document](https://doc.tern.1c7.me/zh/folder/setting/#%E8%85%BE%E8%AE%AF%E4%BA%91)
**Xftrans 讯飞翻译**
Apply [here](https://www.xfyun.cn/doc/authentication/personal.html#%E6%93%8D%E4%BD%9C%E6%AD%A5%E9%AA%A4).
**GPT**
Apply [OpenAI ChatGPT API](https://auth.openai.com/create-account) or [Azure OpenAI REST API](https://azure.microsoft.com/free/cognitive-services).
The secret format is `sk-*` for ChatGPT, and `MY_APIKEY` for AzureGPT and Custom GPT.
Support third-party or self-deployed compatible APIs.
> [Chinese Document](https://gist.github.com/GrayXu/f1b72353b4b0493d51d47f0f7498b67b)
**Gemini**
Apply [here](https://ai.google.dev/gemini-api/docs).
The secret format is `MY_APIKEY`.
**Qwen-MT**
Apply [here](https://help.aliyun.com/zh/model-studio/user-guide/machine-translation).
The secret format is `MY_APIKEY`.
**Claude**
Apply [here](https://docs.anthropic.com/claude/docs/getting-started-with-the-claude-api).
**LibreTranslate**
See [LibreTranslate](https://github.com/LibreTranslate/LibreTranslate). API Key is optional.
**MTranServer**
See [MTranServer](https://github.com/xxnuo/MTranServer). Token is optional.
> MTranServer only supports `zh`-`en` language pairs for v2.1.1 and previous versions. For MTranServer v3.0.0+, please check the checkbox in the Config panel to use `zh-Hans` or `zh-Hant` language. See [explanation of the supported languages](https://github.com/xxnuo/MTranServer/issues/59#issuecomment-3131551779).
**NLLB**
See [nllb-api](https://github.com/winstxnhdw/nllb-api?tab=readme-ov-file#self-hosting) or [NLLB Serve](https://github.com/thammegowda/nllb-serve?tab=readme-ov-file#setup).
**Pot**
See [Pot](https://github.com/pot-app/pot-desktop?tab=readme-ov-file#%E5%A4%96%E9%83%A8%E8%B0%83%E7%94%A8). _Translate results show in Pot._
### User Interface
- `Font Size`: The font size of result text, default `12`
- `Line Height`: The line height of result text, default `1.5`
- `Item Context Menu: Show xxx`: Show or hide Title/Abstract tanslation, default `true`
- `Item Pane Section: Show xxx`: Show or hide elements in the item pane, default `true`
- `Item Pane Section: Hold down Ctrl/⌘`: Press key to enable concat mode when selecting text in PDF/EPub/webpage if `true`, default `true`
- `Item Pane Section: Reverse Raw/Result`: Reverse the order of Raw/Result in the item pane if `true`, default `false`
- `Item Pane Info: Show xxx`: Show or hide Title/Abstract tanslation in the item info rows
- `Standalone: Keep Windows on Top`: Top the standalone translate panel if `true`, default `false`
- `Pop-up: Remember Size`: Remember size of pop-up if `true`, else automatically adjust the size, default `false`
### Advanced
- Strip empty lines and thinking from translation results: Automatically remove empty lines or thinking labels from translation results, especially for some LLM translation services.
- Automatically Detect Item Language
- Disable Automatic Translation when File Language is(comma-separated): If you want to disable automatic translation in `zh` and `ja` files, set `zh,ja`. Default `zh,zh-CN,中文`.
- Delimiter (between text and translation): When translating annotations, the result will be wrapped inside this character to allow safe re-translate. If set to empty, re-translating annotations will replace the annotation comment/body with the new translate result.
- Regex for removing extra text from translation results (leave empty to disable): Automatically remove text from translation results using regex. You need to understand how to use regex in advance.
- Reset field of selected items in library: Batch reset the _Title Translation_ or _Abstract Translation_ of selected items. Please select the items in Library or Collection panel and then click the button.
## Development & Contributing
This plugin is built based on the [Zotero Plugin Template](https://github.com/windingwind/zotero-plugin-template). See the setup and debug details there.
To startup, run
```bash
git clone https://github.com/windingwind/zotero-pdf-translate.git
cd zotero-pdf-translate
npm install
npm run build
```
The plugin is built to `./build/*.xpi`.
### Contributing
**Add new translate service**
1. Copy `src/modules/services/_template.ts` > `src/services/.ts`;
2. Fill in the required fields (id, type, and translate) and optional fields (name, helpUrl, defaultSecret, secretValidator(secret), and config(settings)) following the introduction. The translation function sets the translation result to `data.result` if runs successfully and throws an error if fails;
3. Import the new service object in `src/modules/services/index.ts`.
4. Add locale string `service.${serviceId}` and `service--dialog-xxx`(if necessary) in `addon/locale/${lang}/addon.ftl`.
5. Build and test.
## Disclaimer
Use this code under AGPL. No warranties are provided. Keep the laws of your locality in mind!
## My Zotero Plugins
- [Better Notes for Zotero](https://github.com/windingwind/zotero-better-notes): Everything about note management. All in Zotero.
- [Actions & Tags for Zotero](https://github.com/windingwind/zotero-tag): Customize your Zotero workflow.
- [Bionic for Zotero](https://github.com/windingwind/bionic-for-zotero): Bionic reading experience with Zotero.
## Sponsors
Thanks
[peachgirl100](https://github.com/peachgirl100),
[youngfish42](https://github.com/youngfish42),
and other anonymous sponsors!
If you want to leave your name here, please email me or leave a message with the donation.
## Contributors
================================================
FILE: addon/bootstrap.js
================================================
/**
* Most of this code is from Zotero team's official Make It Red example[1]
* or the Zotero 7 documentation[2].
* [1] https://github.com/zotero/make-it-red
* [2] https://www.zotero.org/support/dev/zotero_7_for_developers
*/
var chromeHandle;
function install(data, reason) {}
async function startup({ id, version, resourceURI, rootURI }, reason) {
await Zotero.initializationPromise;
// String 'rootURI' introduced in Zotero 7
if (!rootURI) {
rootURI = resourceURI.spec;
}
var aomStartup = Components.classes[
"@mozilla.org/addons/addon-manager-startup;1"
].getService(Components.interfaces.amIAddonManagerStartup);
var manifestURI = Services.io.newURI(rootURI + "manifest.json");
chromeHandle = aomStartup.registerChrome(manifestURI, [
["content", "__addonRef__", rootURI + "chrome/content/"],
]);
/**
* Global variables for plugin code.
* The `_globalThis` is the global root variable of the plugin sandbox environment
* and all child variables assigned to it is globally accessible.
* See `src/index.ts` for details.
*/
const ctx = {
rootURI,
};
ctx._globalThis = ctx;
Services.scriptloader.loadSubScript(
`${rootURI}/chrome/content/scripts/__addonRef__.js`,
ctx,
);
}
async function onMainWindowLoad({ window }, reason) {
Zotero.__addonInstance__?.hooks.onMainWindowLoad(window);
}
async function onMainWindowUnload({ window }, reason) {
Zotero.__addonInstance__?.hooks.onMainWindowUnload(window);
}
function shutdown({ id, version, resourceURI, rootURI }, reason) {
if (reason === APP_SHUTDOWN) {
return;
}
Zotero.__addonInstance__?.hooks.onShutdown();
Cc["@mozilla.org/intl/stringbundle;1"]
.getService(Components.interfaces.nsIStringBundleService)
.flushBundles();
if (chromeHandle) {
chromeHandle.destruct();
chromeHandle = null;
}
}
function uninstall(data, reason) {}
================================================
FILE: addon/chrome/content/preferences.xhtml
================================================
================================================
FILE: addon/chrome/content/standalone.xhtml
================================================
================================================
FILE: addon/chrome/content/styles/mathTextbox.css
================================================
math-textbox[hidden] {
display: none;
}
================================================
FILE: addon/chrome/content/styles/panel.css
================================================
translator-plugin-panel {
display: flex;
flex-direction: column;
gap: 6px;
height: var(--details-height, 450px);
}
translator-plugin-panel linkset {
display: none;
}
translator-plugin-panel .separator {
border-top: var(--material-border);
}
translator-plugin-panel .icon-button {
width: 24px;
height: 24px;
fill: var(--fill-secondary);
stroke: var(--fill-secondary);
-moz-context-properties: fill, fill-opacity, stroke, stroke-opacity;
list-style-image: url(chrome://__addonRef__/content/icons/swap.svg);
}
translator-plugin-panel #__addonRef__-translate {
flex: 1;
min-width: auto;
}
translator-plugin-panel .lang-menulist {
flex: 1;
}
translator-plugin-panel editable-text {
flex: 1;
min-height: 100px;
}
/* Minimal styles for math-textbox to match editable-text without intruding */
translator-plugin-panel math-textbox {
display: flex;
flex-direction: column;
width: 100%;
min-height: 100px;
flex: 1;
position: relative;
}
translator-plugin-panel math-textbox editable-text {
flex: 1;
min-height: 100px;
}
translator-plugin-panel math-textbox[overlay-visible] editable-text {
visibility: hidden;
}
translator-plugin-panel math-textbox .math-overlay {
position: absolute;
inset: 0;
overflow: auto;
display: block; /* ensure layout box for HTML namespace */
}
translator-plugin-panel .editor-container {
display: flex;
flex: 1;
min-height: 213px;
flex-direction: column;
position: relative;
}
translator-plugin-panel .draggable-container {
height: 13px;
cursor: ns-resize;
display: flex;
flex-direction: column;
position: relative;
justify-content: center;
}
translator-plugin-panel .draggable-container[hidden] {
display: none;
}
translator-plugin-panel .options-container {
display: grid;
grid-template-columns: max-content 1fr;
column-gap: 8px;
row-gap: 2px;
width: inherit;
}
translator-plugin-panel .options-grid:not([hidden]) {
display: grid;
grid-template-columns: subgrid;
grid-column: span 2;
}
translator-plugin-panel .options-label {
display: flex;
flex-direction: column;
justify-content: center;
color: var(--fill-secondary);
}
translator-plugin-panel .options-content {
display: flex;
flex-direction: row;
gap: 4px;
}
translator-plugin-panel #__addonRef__-copy-container button {
min-width: auto;
flex: 1;
}
================================================
FILE: addon/chrome/content/styles/standalone.css
================================================
window {
display: flex;
flex-direction: column;
gap: 8px;
padding: 20px;
}
linkset {
display: none;
}
.separator {
border-top: var(--material-border);
}
translator-plugin-panel {
width: 100%;
flex-grow: 1;
}
#extra-buttons button {
flex: 1;
}
#extra-container {
display: flex;
flex-direction: column;
flex-grow: 1;
gap: 8px;
}
#extra-container:empty {
display: none;
}
#extra-container editable-text {
min-height: 60px;
height: 100px;
flex-shrink: 1;
flex-grow: 1;
}
================================================
FILE: addon/locale/en-US/addon.ftl
================================================
service-huoshanweb=Volcengine Web
service-tencenttransmart=Tencent Transmart
service-huoshan=Huoshan
service-googleapi=Google(API)
service-google=Google
service-cnki=CNKI
service-youdao=Youdao
service-youdaozhiyun=Youdao Zhiyun
service-youdaozhiyunllm=Youdao LLM
service-niutranspro=Niu Trans
service-microsoft=Microsoft
service-caiyun=Caiyun
service-libretranslate=LibreTranslate
service-mtranserver=MTranServer
service-deeplfree=DeepL(Free Plan)
service-deeplpro=DeepL(Pro Plan)
service-deeplcustom=DeepLX(API)
service-deeplx=DeepLX
service-baidu=Baidu
service-baidufield=Baidu Field
service-openl=OpenL
service-tencent=Tencent
service-aliyun=Aliyun
service-xftrans=Xftrans
service-chatgpt=ChatGPT
service-customgpt1=Custom GPT 1
service-customgpt2=Custom GPT 2
service-customgpt3=Custom GPT 3
service-azuregpt=AzureGPT
service-gemini=Gemini
service-qwenmt=Qwen-MT
service-claude=Claude
service-haici=Haici
service-bing=Bing
service-pot=Pot
service-nllb=NLLB
service-bingdict=Bing Dict(en→zh)🔊
service-cambridgedict=Cambridge Dict(en→other)🔊
service-haicidict=Haici Dict(en→zh)🔊
service-collinsdict=Collins Dict(en→zh)🔊
service-youdaodict=Youdao Dict(en→zh)🔊
service-freedictionaryapi=FreeDictionaryAPI(en→en)
service-webliodict=Weblio Dict(en→ja)
service-errorPrefix=[Request Error]
Service not available, invalid secret, or request too fast.
Use another translation service or post the issue here:
https://github.com/windingwind/zotero-pdf-translate/issues
The message below is not Zotero or the Translate plugin, but from
service-dialog-config=Config
service-dialog-title={ $service } Config
service-dialog-save=Save
service-dialog-close=Close
service-dialog-help=Help
service-dialog-custom-request-description=Refer to API documentation of service provider, add custom parameters. These will be merged with the standard parameters (model, messages, temperature, stream).
service-dialog-custom-request-title=Custom Request Parameters
service-dialog-custom-request-add-param=Add Parameter
service-niutranspro-dialog-endpoint=Endpoint
service-niutranspro-dialog-username=Username
service-niutranspro-dialog-password=Password
service-niutranspro-dialog-signup=Sign up
service-niutranspro-dialog-forget=Forget
service-niutranspro-dialog-dictLib=Dict Lib
service-niutranspro-dialog-memoryLib=Memory Lib
service-niutranspro-dialog-tip0=Please go to the
service-niutranspro-dialog-tip1=Niutrans Cloud Platform
service-niutranspro-dialog-tip2=to add the term dictionary library
service-niutranspro-dialog-signin=Sign In
service-niutranspro-dialog-refresh=Refresh
service-niutranspro-dialog-signout=Sign Out
service-deeplcustom-dialog-endPoint=EndPoint
service-deeplx-dialog-endPoint=EndPoint
service-chatgpt-dialog-endPoint=API
service-chatgpt-dialog-model=Model
service-chatgpt-dialog-temperature=Temp
service-chatgpt-dialog-prompt=Prompt
service-chatgpt-dialog-stream=Stream
service-chatgpt-dialog-custom-request=Custom Request
service-azuregpt-dialog-endPoint=EndPoint
service-azuregpt-dialog-model=Name
service-azuregpt-dialog-temperature=Temp
service-azuregpt-dialog-apiVersion=Version
service-azuregpt-dialog-prompt=Prompt
service-azuregpt-dialog-stream=Stream
service-azuregpt-dialog-custom-request=Custom Request
service-xftrans-dialog-engine=API Engine
service-gemini-dialog-endPoint=EndPoint
service-gemini-dialog-prompt=Prompt
service-gemini-dialog-stream=Stream
service-qwenmt-dialog-endPoint=EndPoint
service-qwenmt-dialog-model=Model
service-qwenmt-dialog-domains=Domains
service-claude-dialog-endPoint=EndPoint
service-claude-dialog-model=Model
service-claude-dialog-temperature=Temp
service-claude-dialog-prompt=Prompt
service-claude-dialog-stream=Stream
service-claude-dialog-maxTokens=Max Tokens
service-cnki-settings=Settings
service-cnki-dialog-regex=CNKI Addvertisements Regex
service-cnki-dialog-split=Automatically split translation for more than 800 characters
service-aliyun-dialog-action=Action
service-aliyun-dialog-scene=Scene
service-tencent-dialog-secretid=Secret ID
service-tencent-dialog-secretkey=Secret Key
service-tencent-dialog-region=Region
service-tencent-dialog-projectid=Project ID
service-tencent-dialog-termrepoid=Term Repo IDs (optional)
service-tencent-dialog-sentrepoid=Sent Repo IDs (optional)
service-youdaozhiyun-dialog-domain=Domain
service-youdaozhiyunllm-dialog-model=Model
service-youdaozhiyunllm-dialog-pro=Youdao LLM Pro-14B
service-youdaozhiyunllm-dialog-lite=Youdao LLM Lite-1.5B
service-youdaozhiyunllm-dialog-prompt=Prompt
service-youdaozhiyunllm-dialog-stream=Stream
readerpopup-translate-label=Translate
readerpopup-addToNote-label=Add Translation to Note
pref-title=Translate
field-titleTranslation=Title Translation
field-abstractTranslation=Abstract Translation
status-translating=Translating...
sideBarIcon-title=Translate annotation
service-manageKeys-title=Manage Translation Service Keys
service-manageKeys-head=Manage all translation service keys. Edit the JSON directly and click Save.
service-manageKeys-save=Save
service-manageKeys-close=Close
service-renameServices-title=Rename Custom GPT Services
service-renameServices-head=Input the new name and click Save.
service-renameServices-hint=Changes take effect after restarting the plugin or Zotero
service-renameServices-save=Save
service-renameServices-close=Close
service-libretranslate-dialog-endPoint=API Endpoint
service-mtranserver-dialog-endPoint=EndPoint
service-mtranserver-dialog-versionlabel=Use MTranServer v3.0.0+
service-pot-dialog-port=Port
service-nllb-dialog-model=nllb Model
service-nllb-dialog-apiendpoint=nllb-api EndPoint
service-nllb-dialog-apistream=nllb-api Stream
service-nllb-dialog-serveendpoint=nllb-serve EndPoint
service-nllb-dialog-apilabel=nllb-api Docs
service-nllb-dialog-servelabel=nllb-serve Docs
================================================
FILE: addon/locale/en-US/mainWindow.ftl
================================================
itemPaneSection-header =
.label = Translate
itemPaneSection-sidenav =
.tooltiptext = Translate
itemPaneSection-fullHeight =
.tooltiptext = Full height
itemPaneSection-openStandalone =
.tooltiptext = Open in standalone window
field-titleTranslation = Title Translation
field-abstractTranslation = Abstract Translation
itemmenu-translateTitle =
.label = Translate Title
itemmenu-translateAbstract =
.label = Translate Abstract
================================================
FILE: addon/locale/en-US/panel.ftl
================================================
translate =
.label = Translate
.tooltiptext = { PLATFORM() ->
[macos] ⌘
*[other] Ctrl
} + T
swapLanguage =
.tooltiptext = Swap Language
auto = Auto-Trans:
autoTranslateSelection =
.label = Selection
autoTranslateAnnotation =
.label = Annotation
selection = Selection:
enableConcat =
.label = Concat Mode
clearConcat =
.label = Clear
copy = Copy:
copyRaw =
.label = Raw
copyResult =
.label = Result
copyBoth =
.label = Both
================================================
FILE: addon/locale/en-US/preferences.ftl
================================================
pref-general = General
pref-basic-enableAuto =
.label = Automatically Translate Selection
pref-basic-enableComment =
.label = Automatically Translate Annotation
pref-basic-enablePopup =
.label = Enable Reader Selection Pop-up
pref-basic-enableHidePopupTextarea =
.label = Hide Pop-up Text Area
pref-basic-annotationTranslationInComment =
.label = Save Translation in Annotation Comment
pref-basic-annotationTranslationInBody =
.label = Save Translation in Annotation Body
pref-basic-enableAnnotationFromSyncTranslation =
.label = Automatically Translate Annotation from Sync
pref-basic-enableNote =
.label = Show "Add Translation to Note" in Pop-up
pref-basic-enableNoteReplaceMode =
.label = Replace Raw Text When Adding Translation to Note
pref-basic-enableAutoTagAnnotation =
.label = Automatically Tag Annotation After Translation
pref-basic-annotationTagContent =
.value = Tag
pref-audio-autoPlay =
.label = Auto-play Pronunciation
pref-audio-showPlayBtn =
.label = Show Play Buttons🔊 in Pop-up Panel
pref-service = Service
pref-service-sentenceServices =
.value = Translation Services
pref-service-sentenceServicesSecret =
.value = Secret
pref-service-attachPaperContext =
.label = Feed GPT/Claude/Gemini Services with Title and Abstract
pref-service-useWordService =
.label = Use Dictionary Service for Word Translation
pref-service-wordServices =
.value = Dictionary Services
pref-service-wordServicesSecret =
.value = Secret
pref-service-langfrom =
.value = Translate From
pref-service-langto =
.value = To
pref-service-hint =
.value = Service📍requires custom configuration; 🗝️requires a secret key. See GitHub for details
pref-service-manageKeys =
.label = Manage Secret Keys
pref-service-manageKeys-hint =
.value = Display saved secret keys for bulk import and export:
pref-service-renameServices =
.label = Rename Custom GPT🗝️ Services
pref-service-renameServices-hint =
.value = Show Services to rename or view mappings:
pref-interface = User Interface
pref-interface-fontSize =
.value = Font Size
pref-interface-lineHeight =
.value = Line Height
pref-interface-showItemMenu =
.label = Show Item Context Menu
pref-interface-showItemMenuTitleTranslation =
.label = Item Context Menu: Show Title Translation
pref-interface-showItemMenuAbstractTranslation =
.label = Item Context Menu: Show Abstract Translation
pref-interface-showSidebarEngine =
.label = Item Pane Section: Show Service Selection Menu
pref-interface-hideUnconfiguredServices =
.label = Item Pane Section: Hide Unconfigured Services from Menu
pref-interface-showSidebarLanguage =
.label = Item Pane Section: Show Language Selection Menu
pref-interface-showSidebarSettings =
.label = Item Pane Section: Show Auto-Trans Settings
pref-interface-showSidebarConcat =
.label = Item Pane Section: Show Concatenated Translation Menu
pref-interface-enableConcatKey =
.label = Item Pane Section: Hold down { PLATFORM() ->
[macos] ⌘
*[other] Ctrl
} to enable Concat Mode
pref-interface-showSidebarRaw =
.label = Item Pane Section: Show Raw
pref-interface-enableMathRendering =
.label = Item Pane Section: Render LaTeX math in translation
pref-interface-showSidebarCopy =
.label = Item Pane Section: Show Copy Buttons
pref-interface-rawResultOrder =
.label = Item Pane Section: Reverse Order of Raw and Translated Text
pref-interface-showItemBoxTitleTranslation =
.label = Item Pane Info: Show Title Translation
pref-interface-showItemBoxAbstractTranslation =
.label = Item Pane Info: Show Abstract Translation
pref-interface-keepWindowTop =
.label = Standalone: Keep Window on Top
pref-interface-keepPopupSize =
.label = Pop-up: Remember Size
pref-advanced = Advanced
pref-advanced-enableAutoDetectLanguage =
.label = Automatically Detect Item Language
pref-advanced-disabledLanguages =
.value = Disable automatic translation for file languages (comma-separated)
pref-advanced-disabledLanguages-alert = Reopen files or restart Zotero to apply changes.
pref-advanced-extraEngines =
.value = Additional services in standalone window (comma-separated)
pref-advanced-splitChar =
.value = Delimiter (between text and translation)
pref-advanced-resultRegex =
.value = Regex for removing extra text from translation results (leave empty to disable)
pref-advanced-reset =
.value = Reset field of selected items in library:
pref-advanced-reset-titleTranslation =
.label = Title Translation
pref-advanced-reset-abstractTranslation =
.label = Abstract Translation
pref-about = About
pref-about-feedback =
.value = GitHub
pref-about-docs =
.value = Documentation (ZH)
pref-about-version =
.value = { $name } Version { $version } Build { $time }
pref-advanced-stripEmptyLines =
.label = Strip empty lines and thinking from translation results
================================================
FILE: addon/locale/en-US/standalone.ftl
================================================
add-source =
.label = Add Source
remove-source =
.label = Remove
pin-window =
.label = { $mode ->
[pinned] 📌Unpin
*[other] 📍Pin
}
================================================
FILE: addon/locale/it-IT/addon.ftl
================================================
service-huoshanweb=Volcengine Web
service-tencenttransmart=Tencent Transmart
service-huoshan=Huoshan
service-googleapi=Google(API)
service-google=Google
service-cnki=CNKI
service-youdao=Youdao
service-youdaozhiyun=Youdao Zhiyun
service-youdaozhiyunllm=Youdao LLM
service-niutranspro=Niu Trans
service-microsoft=Microsoft
service-caiyun=Caiyun
service-libretranslate=LibreTranslate
service-mtranserver=MTranServer
service-deeplfree=DeepL(Free Plan)
service-deeplpro=DeepL(Pro Plan)
service-deeplcustom=DeepLX(API)
service-deeplx=DeepLx
service-baidu=Baidu
service-baidufield=Baidu Field
service-openl=OpenL
service-tencent=Tencent
service-aliyun=Aliyun
service-xftrans=Xftrans
service-chatgpt=ChatGPT
service-customgpt1=Custom GPT 1
service-customgpt2=Custom GPT 2
service-customgpt3=Custom GPT 3
service-azuregpt=AzureGPT
service-gemini=Gemini
service-qwenmt=Qwen-MT
service-claude=Claude
service-haici=Haici
service-bing=Bing
service-pot=Pot
service-nllb=NLLB
service-bingdict=Bing Dict(en→zh)🔊
service-cambridgedict=Cambridge Dict(en→other)🔊
service-haicidict=Haici Dict(en→zh)🔊
service-collinsdict=Collins Dict(en→zh)🔊
service-youdaodict=Youdao Dict(en→zh)🔊
service-freedictionaryapi=FreeDictionaryAPI(en→en)
service-webliodict=Weblio Dict(en→ja)
service-errorPrefix=[Errore nella richiesta]
Servizio di traduzione non disponibile, segreto non valido, o richiesta troppo rapida.
Si prega di usare un altro servizio di traduzione o di segnalare il problema qui:
https://github.com/windingwind/zotero-pdf-translate/issues
Il messaggio seguente non è di Zotero o dell'estensione Translate ma proviene da
service-dialog-config=Config
service-dialog-title={ $service } Config
service-dialog-save=Save
service-dialog-close=Close
service-dialog-help=Help
service-dialog-custom-request-description=Refer to API documentation of service provider, add custom parameters. These will be merged with the standard parameters (model, messages, temperature, stream).
service-dialog-custom-request-title=Custom Request Parameters
service-dialog-custom-request-add-param=Add Parameter
service-niutranspro-dialog-endpoint=Endpoint
service-niutranspro-dialog-username=Nome utente
service-niutranspro-dialog-password=Password
service-niutranspro-dialog-signup=Registrati
service-niutranspro-dialog-forget=Dimentica
service-niutranspro-dialog-dictLib=Lib. Diz.
service-niutranspro-dialog-memoryLib=Lib. Mem.
service-niutranspro-dialog-tip0=Si prega di collegarsi a
service-niutranspro-dialog-tip1=Niutrans Cloud Platform
service-niutranspro-dialog-tip2=per aggiungere il vocabolo alla libreria dei dizionari
service-niutranspro-dialog-signin=Autenticati
service-niutranspro-dialog-refresh=Aggiorna
service-niutranspro-dialog-signout=Esci
service-deeplcustom-dialog-endPoint=EndPoint
service-deeplx-dialog-endPoint=API
service-chatgpt-dialog-endPoint=API
service-chatgpt-dialog-model=Modello
service-chatgpt-dialog-temperature=Temperatura
service-chatgpt-dialog-prompt=Prompt
service-chatgpt-dialog-stream=Stream
service-chatgpt-dialog-custom-request=Custom Request
service-azuregpt-dialog-endPoint=EndPoint
service-azuregpt-dialog-model=Nome
service-azuregpt-dialog-temperature=Temperatura
service-azuregpt-dialog-apiVersion=Versione
service-azuregpt-dialog-prompt=Prompt
service-azuregpt-dialog-stream=Stream
service-azuregpt-dialog-custom-request=Custom Request
service-xftrans-dialog-engine=API Engine
service-gemini-dialog-endPoint=EndPoint
service-gemini-dialog-prompt=Prompt
service-gemini-dialog-stream=Stream
service-qwenmt-dialog-endPoint=EndPoint
service-qwenmt-dialog-model=Model
service-qwenmt-dialog-domains=Domains
service-claude-dialog-endPoint=EndPoint
service-claude-dialog-model=Model
service-claude-dialog-temperature=Temp
service-claude-dialog-prompt=Prompt
service-claude-dialog-stream=Stream
service-claude-dialog-maxTokens=Max Tokens
service-cnki-settings=Impostazioni
service-cnki-dialog-regex=Regex per gli annunci CNKI
service-cnki-dialog-split=Dividi automaticamente la traduzione per più di 800 caratteri
service-aliyun-dialog-action=Azione
service-aliyun-dialog-scene=Scena
service-tencent-dialog-secretid=Segreto ID
service-tencent-dialog-secretkey=Segreto Key
service-tencent-dialog-region=Regione
service-tencent-dialog-projectid=Progetto ID
service-tencent-dialog-termrepoid=Term Repo IDs (opzionale)
service-tencent-dialog-sentrepoid=Sent Repo IDs (opzionale)
service-youdaozhiyun-dialog-domain=Settore
service-youdaozhiyunllm-dialog-model=Modello
service-youdaozhiyunllm-dialog-pro=Youdao LLM Pro-14B
service-youdaozhiyunllm-dialog-lite=Youdao LLM Lite-1.5B
service-youdaozhiyunllm-dialog-prompt=Prompt
service-youdaozhiyunllm-dialog-stream=Stream
readerpopup-translate-label=Traduci
readerpopup-addToNote-label=Aggiungi traduzione alla nota
pref-title=Translate
field-titleTranslation=Traduzione del titolo
field-abstractTranslation=Traduzione dell'Abstract
status-translating=Traduzione in corso...
sideBarIcon-title=Translate annotation
service-manageKeys-title=Gestione delle chiavi dei segreto di traduzione
service-manageKeys-head=Gestisci tutte le dei segreto di traduzione. Modifica direttamente il file JSON e clicca su Salva.
service-manageKeys-save=Salva
service-manageKeys-close=Chiudi
service-renameServices-title=Rinominare i servizi Custom GPT
service-renameServices-head=Inserisci il nuovo nome e clicca su Salva.
service-renameServices-hint=Le modifiche avranno effetto dopo il riavvio del plugin o di Zotero
service-renameServices-save=Salva
service-renameServices-close=Chiudi
service-libretranslate-dialog-endPoint=API Endpoint
service-mtranserver-dialog-endPoint=EndPoint
service-mtranserver-dialog-versionlabel=Use MTranServer v3.0.0+
service-pot-dialog-port=Port
service-nllb-dialog-model=nllb Modello
service-nllb-dialog-apiendpoint=nllb-api EndPoint
service-nllb-dialog-apistream=nllb-api Stream
service-nllb-dialog-serveendpoint=nllb-serve EndPoint
service-nllb-dialog-apilabel=nllb-api Docs
service-nllb-dialog-servelabel=nllb-serve Docs
================================================
FILE: addon/locale/it-IT/mainWindow.ftl
================================================
itemPaneSection-header =
.label = Translate
itemPaneSection-sidenav =
.tooltiptext = Translate
itemPaneSection-fullHeight =
.tooltiptext = Full height
itemPaneSection-openStandalone =
.tooltiptext = Open in standalone window
field-titleTranslation = Title Translation
field-abstractTranslation = Abstract Translation
itemmenu-translateTitle =
.label = Traduci Titolo
itemmenu-translateAbstract =
.label = Traduci Abstract
================================================
FILE: addon/locale/it-IT/panel.ftl
================================================
translate =
.label = Translate
.tooltiptext = { PLATFORM() ->
[macos] ⌘
*[other] Ctrl
} + T
swapLanguage =
.tooltiptext = Swap Language
auto = Auto-Trans:
autoTranslateSelection =
.label = Selection
autoTranslateAnnotation =
.label = Annotation
selection = Selection:
enableConcat =
.label = Concat Mode
clearConcat =
.label = Clear
copy = Copy:
copyRaw =
.label = Raw
copyResult =
.label = Result
copyBoth =
.label = Both
================================================
FILE: addon/locale/it-IT/preferences.ftl
================================================
pref-general = Generale
pref-basic-enableAuto =
.label = Traduci automaticamente la selezione
pref-basic-enableComment =
.label = Traduci automaticamente le annotazioni
pref-basic-enablePopup =
.label = Attiva popup di selezione nel lettore
pref-basic-enableHidePopupTextarea =
.label = Nascondi l'area del testo del popup
pref-basic-annotationTranslationInComment =
.label = Salva traduzione nel commento dell'annotazione
pref-basic-annotationTranslationInBody =
.label = Salva traduzione nel corpo dell'annotazione
pref-basic-enableAnnotationFromSyncTranslation =
.label = Auto-traduci annotazioni da Sync
pref-basic-enableNote =
.label = Mostra "Aggiungi traduzione alla nota" nel popup
pref-basic-enableNoteReplaceMode =
.label = Sostituisci il testo d'origine quando aggiungi traduzione alla nota
pref-basic-enableAutoTagAnnotation =
.label = Tagga automaticamente l'annotazione dopo la traduzione
pref-basic-annotationTagContent =
.value = Tag
pref-audio-autoPlay =
.label = Riproduci automaticamente la pronuncia
pref-audio-showPlayBtn =
.label = Mostra i pulsanti di riproduzione🔊 nel pannello del popup
pref-service = Servizio
pref-service-sentenceServices =
.value = Servizi di traduzione
pref-service-sentenceServicesSecret =
.value = Segreto
pref-service-attachPaperContext =
.label = Fornisci servizi GPT/Claude/Gemini con titolo e abstract
pref-service-useWordService =
.label = Usa un dizionario online per la traduzione di termini
pref-service-wordServices =
.value = Dizionari online
pref-service-wordServicesSecret =
.value = Segreto
pref-service-langfrom =
.value = Traduci da
pref-service-langto =
.value = A
pref-service-hint =
.value = Servizio📍richiede configurazione personalizzata; 🗝️richiede un segreto. Vedi GitHub per maggiori dettagli
pref-service-manageKeys =
.label = Gestisci segreto
pref-service-manageKeys-hint =
.value = Visualizza le segreto salvate per l'importazione e l'esportazione in blocco:
pref-service-renameServices =
.label = Rinominare i servizi Custom GPT🗝️
pref-service-renameServices-hint =
.value = Mostra servizi per rinominare o visualizzare le mappature:
pref-interface = Interfaccia utente
pref-interface-fontSize =
.value = Dimensione font
pref-interface-lineHeight =
.value = Altezza delle linee
pref-interface-showItemMenu =
.label = Mostra menu contestuale dell'elemento
pref-interface-showItemMenuTitleTranslation =
.label = Menu contestuale: Mostra la traduzione del titolo
pref-interface-showItemMenuAbstractTranslation =
.label = Menu contestuale: Mostra la traduzione dell'abstract
pref-interface-showSidebarEngine =
.label = Sezione del pannello dell'elemento: Mostra il menu di selezione della Servizi
pref-interface-hideUnconfiguredServices =
.label = Sezione del pannello dell'elemento: Nascondi servizi non configurati dal menu
pref-interface-showSidebarLanguage =
.label = Sezione del pannello dell'elemento: Mostra il menu di selezione della lingua
pref-interface-showSidebarSettings =
.label = Sezione del pannello dell'elemento: Mostra le Traduci automaticamente impostazioni
pref-interface-showSidebarConcat =
.label = Sezione del pannello dell'elemento: Mostra il menu per la traduzione concatenata
pref-interface-enableConcatKey =
.label = Sezione del pannello dell'elemento: Tenere premuto il tasto { PLATFORM() ->
[macos] ⌘
*[other] Ctrl
} per attivare la modalità di giunzione
pref-interface-showSidebarRaw =
.label = Sezione del pannello dell'elemento: Mostra il testo originale
pref-interface-enableMathRendering =
.label = Sezione del pannello: Render LaTeX nella traduzione
pref-interface-showSidebarCopy =
.label = Sezione del pannello dell'elemento: Mostra i pulsanti di copia
pref-interface-rawResultOrder =
.label = Sezione del pannello dell'elemento: Inverti l'ordine del testo originale e della traduzione
pref-interface-showItemBoxTitleTranslation =
.label = Pannello informazioni: Mostra la traduzione del titolo
pref-interface-showItemBoxAbstractTranslation =
.label = Pannello informazioni: Mostra la traduzione dell'abstract
pref-interface-keepWindowTop =
.label = Finestra indipendente: Mantieni in primo piano
pref-interface-keepPopupSize =
.label = Popup: Ricorda la dimensione
pref-advanced = Avanzate
pref-advanced-enableAutoDetectLanguage =
.label = Rilevamento automatico della lingua dell'elemento
pref-advanced-disabledLanguages =
.value = Disabilita la traduzione automatica per i file in lingue specifiche (separare con ',')
pref-advanced-disabledLanguages-alert = Riapri i file o riavvia Zotero per applicare le modifiche.
pref-advanced-extraEngines =
.value = Servizi extra nella finestra indipendente (separare con ',')
pref-advanced-splitChar =
.value = Carattere di divisione (tra testo e traduzione)
pref-advanced-resultRegex =
.value = Regex per rimuovere il testo extra dai risultati della traduzione (lasciare vuoto per disabilitare)
pref-advanced-reset =
.value = Reimposta il campo degli elementi selezionati nella libreria:
pref-advanced-reset-titleTranslation =
.label = Traduzione del titolo
pref-advanced-reset-abstractTranslation =
.label = Traduzione dell'abstract
pref-about = Informazioni
pref-about-feedback =
.value = GitHub
pref-about-docs =
.value = Documentazione (ZH)
pref-about-version =
.value = { $name } Versione { $version } Build { $time }
pref-advanced-stripEmptyLines =
.label = Rimuovi le righe vuote e pensieri dai risultati della traduzione
================================================
FILE: addon/locale/it-IT/standalone.ftl
================================================
add-source =
.label = Aggiungi servizio di traduzione
remove-source =
.label = Rimuovi
pin-window =
.label = { $mode ->
[pinned] 📌Sblocca
*[other] 📍Fissa
}
================================================
FILE: addon/locale/zh-CN/addon.ftl
================================================
service-huoshanweb=火山网页翻译
service-tencenttransmart=腾讯TranSmart
service-huoshan=火山翻译
service-googleapi=Google(API)
service-google=Google
service-cnki=CNKI
service-youdao=有道
service-youdaozhiyun=有道智云
service-youdaozhiyunllm=有道子曰
service-niutranspro=小牛
service-microsoft=微软
service-caiyun=彩云
service-libretranslate=LibreTranslate
service-mtranserver=MTranServer
service-deeplfree=DeepL(免费订阅)
service-deeplpro=DeepL(Pro订阅)
service-deeplcustom=DeepLX(API)
service-deeplx=DeepLX
service-baidu=百度
service-baidufield=百度垂直领域
service-openl=OpenL
service-tencent=腾讯
service-aliyun=阿里
service-xftrans=讯飞
service-chatgpt=ChatGPT
service-customgpt1=自定义GPT1
service-customgpt2=自定义GPT2
service-customgpt3=自定义GPT3
service-azuregpt=AzureGPT
service-gemini=Gemini
service-qwenmt=Qwen-MT
service-claude=Claude
service-haici=海词
service-bing=必应
service-pot=Pot
service-nllb=NLLB
service-bingdict=必应词典(en→zh)🔊
service-cambridgedict=剑桥词典(en→other)🔊
service-haicidict=海词词典(en→zh)🔊
service-collinsdict=科林斯词典(en→zh)🔊
service-youdaodict=有道词典(en→zh)🔊
service-freedictionaryapi=FreeDictionaryAPI(en→en)
service-webliodict=Weblio Dict(en→ja)
service-errorPrefix=[请求错误]
此翻译服务不可用,可能是密钥错误,也可能是请求过快。
可以尝试其他翻译服务,或者来此查看相关回答:
https://zotero.yuque.com/staff-gkhviy/pdf-trans/age09f
请注意,这些错误与 Zotero 和本翻译插件无关,由该翻译服务引起:
service-dialog-config=配置
service-dialog-title={ $service } 配置
service-dialog-save=保存
service-dialog-close=关闭
service-dialog-help=帮助
service-dialog-custom-request-description=参考服务提供商的API文档,添加自定义参数。这些参数将与标准参数合并。
service-dialog-custom-request-title=自定义请求参数
service-dialog-custom-request-add-param=添加参数
service-niutranspro-dialog-endpoint=接口
service-niutranspro-dialog-username=用户名
service-niutranspro-dialog-password=密码
service-niutranspro-dialog-signup=注册
service-niutranspro-dialog-forget=忘记密码
service-niutranspro-dialog-dictLib=术语词典
service-niutranspro-dialog-memoryLib=翻译记忆
service-niutranspro-dialog-tip0=请到
service-niutranspro-dialog-tip1=小牛翻译云平台
service-niutranspro-dialog-tip2=进行添加术语词典库
service-niutranspro-dialog-signin=登录
service-niutranspro-dialog-refresh=刷新
service-niutranspro-dialog-signout=退出登录
service-deeplcustom-dialog-endPoint=接口
service-deeplx-dialog-endPoint=接口
service-chatgpt-dialog-endPoint=接口
service-chatgpt-dialog-model=模型
service-chatgpt-dialog-temperature=温度
service-chatgpt-dialog-prompt=提示词
service-chatgpt-dialog-stream=流式输出
service-chatgpt-dialog-custom-request=自定义请求
service-azuregpt-dialog-endPoint=接口
service-azuregpt-dialog-model=部署名
service-azuregpt-dialog-temperature=温度
service-azuregpt-dialog-stream=流式输出
service-azuregpt-dialog-apiVersion=版本
service-azuregpt-dialog-prompt=提示词
service-azuregpt-dialog-custom-request=自定义请求
service-xftrans-dialog-engine=翻译引擎
service-gemini-dialog-endPoint=接口
service-gemini-dialog-prompt=提示词
service-gemini-dialog-stream=流式输出
service-qwenmt-dialog-endPoint=API地址
service-qwenmt-dialog-model=模型
service-qwenmt-dialog-domains=领域提示词
service-claude-dialog-endPoint=接口
service-claude-dialog-model=模型
service-claude-dialog-temperature=温度
service-claude-dialog-prompt=提示词
service-claude-dialog-stream=流式输出
service-claude-dialog-maxTokens=最大输出长度
service-cnki-settings=设置
service-cnki-dialog-regex=CNKI广告移除正则表达式
service-cnki-dialog-split=超过800字符自动拆分翻译
service-aliyun-dialog-action=版本
service-aliyun-dialog-scene=场景
service-tencent-dialog-secretid=密钥ID
service-tencent-dialog-secretkey=密钥Key
service-tencent-dialog-region=地域
service-tencent-dialog-projectid=项目ID
service-tencent-dialog-termrepoid=术语库IDs (可选)
service-tencent-dialog-sentrepoid=例句库IDs (可选)
service-youdaozhiyun-dialog-domain=领域
service-youdaozhiyunllm-dialog-model=模型
service-youdaozhiyunllm-dialog-pro=有道智云子曰大模型Pro-14B
service-youdaozhiyunllm-dialog-lite=有道智云子曰大模型Lite-1.5B
service-youdaozhiyunllm-dialog-prompt=提示词
service-youdaozhiyunllm-dialog-stream=流式输出
readerpopup-translate-label=翻译
readerpopup-addToNote-label=添加翻译至笔记
pref-title=翻译
field-titleTranslation=标题翻译
field-abstractTranslation=摘要翻译
status-translating=正在翻译...
sideBarIcon-title=翻译注释
service-manageKeys-title=管理翻译服务密钥
service-manageKeys-head=管理所有翻译服务密钥,直接编辑 JSON 文件并点击保存。
service-manageKeys-save=保存
service-manageKeys-close=关闭
service-renameServices-title=重命名自定义GPT服务
service-renameServices-head=输入新的服务名称并点击保存。
service-renameServices-hint=所做更改将在插件或Zotero重启后生效
service-renameServices-save=保存
service-renameServices-close=关闭
service-libretranslate-dialog-endPoint=API 地址
service-mtranserver-dialog-endPoint=接口
service-mtranserver-dialog-versionlabel=使用MTranServer v3.0.0+
service-pot-dialog-port=端口
service-nllb-dialog-model=nllb 模型
service-nllb-dialog-apiendpoint=nllb-api 接口
service-nllb-dialog-apistream=nllb-api 流式输出
service-nllb-dialog-serveendpoint=nllb-serve 接口
service-nllb-dialog-apilabel=nllb-api 文档
service-nllb-dialog-servelabel=nllb-serve 文档
================================================
FILE: addon/locale/zh-CN/mainWindow.ftl
================================================
itemPaneSection-header =
.label = 翻译
itemPaneSection-sidenav =
.tooltiptext = 翻译
itemPaneSection-fullHeight =
.tooltiptext = 自适应高度
itemPaneSection-openStandalone =
.tooltiptext = 在独立窗口中打开
field-titleTranslation = 标题翻译
field-abstractTranslation = 摘要翻译
itemmenu-translateTitle =
.label = 翻译标题
itemmenu-translateAbstract =
.label = 翻译摘要
================================================
FILE: addon/locale/zh-CN/panel.ftl
================================================
translate =
.label = 翻译
.tooltiptext = { PLATFORM() ->
[macos] ⌘
*[other] Ctrl
} + T
swapLanguage =
.tooltiptext = 交换语言
auto = 自动翻译:
autoTranslateSelection =
.label = 选择内容
autoTranslateAnnotation =
.label = 注释
selection = 选区:
enableConcat =
.label = 拼接模式
clearConcat =
.label = 清空
copy = 复制:
copyRaw =
.label = 源文本
copyResult =
.label = 结果
copyBoth =
.label = 两者
================================================
FILE: addon/locale/zh-CN/preferences.ftl
================================================
pref-general = 通用
pref-basic-enableAuto =
.label = 自动翻译选择内容
pref-basic-enableComment =
.label = 自动翻译注释
pref-basic-enablePopup =
.label = 启用阅读器选择弹窗
pref-basic-enableHidePopupTextarea =
.label = 隐藏弹窗文本区域
pref-basic-annotationTranslationInComment =
.label = 保存翻译至注释评论
pref-basic-annotationTranslationInBody =
.label = 保存翻译至注释正文
pref-basic-enableAnnotationFromSyncTranslation =
.label = 自动翻译来自同步的注释
pref-basic-enableNote =
.label = 在弹窗中显示“添加翻译至笔记”
pref-basic-enableNoteReplaceMode =
.label = 添加翻译至笔记时替换原始文本
pref-basic-enableAutoTagAnnotation =
.label = 翻译后自动为注释添加标签
pref-basic-annotationTagContent =
.value = 标签
pref-audio-autoPlay =
.label = 自动播放发音
pref-audio-showPlayBtn =
.label = 弹窗中显示播放按钮🔊
pref-service = 服务
pref-service-sentenceServices =
.value = 翻译服务
pref-service-sentenceServicesSecret =
.value = 密钥
pref-service-attachPaperContext =
.label = 向GPT/Claude/Gemini服务提供论文标题和摘要
pref-service-useWordService =
.label = 使用字典服务翻译词语
pref-service-wordServices =
.value = 字典服务
pref-service-wordServicesSecret =
.value = 密钥
pref-service-langfrom =
.value = 从
pref-service-langto =
.value = 翻译到
pref-service-hint =
.value = 服务📍需要自定义配置;🗝️需要密钥。详情请参阅GitHub
pref-service-manageKeys =
.label = 密钥管理
pref-service-manageKeys-hint =
.value = 展示已保存的密钥以便批量导入和导出:
pref-service-renameServices =
.label = 重命名自定义GPT🗝️服务
pref-service-renameServices-hint =
.value = 显示服务以重命名或查看映射:
pref-interface = 用户界面
pref-interface-fontSize =
.value = 字体大小
pref-interface-lineHeight =
.value = 行高
pref-interface-showItemMenu =
.label = 显示条目上下文菜单
pref-interface-showItemMenuTitleTranslation =
.label = 条目上下文菜单:显示标题翻译
pref-interface-showItemMenuAbstractTranslation =
.label = 条目上下文菜单:显示摘要翻译
pref-interface-showSidebarEngine =
.label = 条目面板区块:显示翻译服务选择菜单
pref-interface-hideUnconfiguredServices =
.label = 条目面板区块:在菜单中隐藏未配置的服务
pref-interface-showSidebarLanguage =
.label = 条目面板区块:显示语言选择菜单
pref-interface-showSidebarSettings =
.label = 条目面板区块:显示自动翻译设置
pref-interface-showSidebarConcat =
.label = 条目面板区块:显示拼接翻译菜单
pref-interface-enableConcatKey =
.label = 条目面板区块:按住 { PLATFORM() ->
[macos] ⌘
*[other] Ctrl
} 键激活拼接模式
pref-interface-showSidebarRaw =
.label = 条目面板区块:显示原文
pref-interface-enableMathRendering =
.label = 条目面板区块:在翻译中渲染 LaTeX 公式
pref-interface-showSidebarCopy =
.label = 条目面板区块:显示复制按钮
pref-interface-rawResultOrder =
.label = 条目面板区块:反转原文与翻译文本顺序
pref-interface-showItemBoxTitleTranslation =
.label = 信息栏:显示标题翻译
pref-interface-showItemBoxAbstractTranslation =
.label = 信息栏:显示摘要翻译
pref-interface-keepWindowTop =
.label = 独立窗口:保持最前
pref-interface-keepPopupSize =
.label = 弹窗:记住大小
pref-advanced = 高级
pref-advanced-enableAutoDetectLanguage =
.label = 自动检测条目语言
pref-advanced-disabledLanguages =
.value = 对文件语言禁用自动翻译(用逗号分隔)
pref-advanced-disabledLanguages-alert = 重新打开文件或重启Zotero以应用更改。
pref-advanced-extraEngines =
.value = 独立窗口额外翻译服务(用逗号分隔)
pref-advanced-splitChar =
.value = 分隔符(原文与翻译之间)
pref-advanced-resultRegex =
.value = 用于移除翻译结果中多余文本的正则表达式(留空以禁用)
pref-advanced-reset =
.value = 重置库中选中条目的字段:
pref-advanced-reset-titleTranslation =
.label = 标题翻译
pref-advanced-reset-abstractTranslation =
.label = 摘要翻译
pref-about = 关于
pref-about-feedback =
.value = GitHub
pref-about-docs =
.value = 文档 (中文)
pref-about-version =
.value = { $name } 版本 { $version } Build { $time }
pref-advanced-stripEmptyLines =
.label = 从翻译结果中删除空行和思考内容
================================================
FILE: addon/locale/zh-CN/standalone.ftl
================================================
add-source =
.label = 添加源
remove-source =
.label = 移除
pin-window =
.label = { $mode ->
[pinned] 📌取消置顶
*[other] 📍置顶
}
================================================
FILE: addon/manifest.json
================================================
{
"manifest_version": 2,
"name": "__addonName__",
"version": "__buildVersion__",
"description": "__description__",
"author": "__author__",
"homepage_url": "__homepage__",
"icons": {
"48": "chrome/content/icons/favicon.png",
"96": "chrome/content/icons/favicon@2x.png"
},
"applications": {
"zotero": {
"id": "__addonID__",
"update_url": "__updateURL__",
"strict_min_version": "7.9.9",
"strict_max_version": "9.9.9"
}
}
}
================================================
FILE: addon/prefs.js
================================================
pref("__prefsPrefix__.enableAuto", true);
pref("__prefsPrefix__.enableDict", true);
pref("__prefsPrefix__.attachPaperContext", false);
pref("__prefsPrefix__.enablePopup", true);
pref("__prefsPrefix__.enableComment", false);
pref("__prefsPrefix__.enableAnnotationFromSyncTranslation", false);
pref("__prefsPrefix__.enableAutoTagAnnotation", false);
pref("__prefsPrefix__.annotationTagContent", "");
pref("__prefsPrefix__.annotationTranslationPosition", "comment");
pref("__prefsPrefix__.enableNote", true);
pref("__prefsPrefix__.enableNoteReplaceMode", false);
pref("__prefsPrefix__.translateSource", "");
pref("__prefsPrefix__.dictSource", "");
pref("__prefsPrefix__.sourceLanguage", "en-US");
pref("__prefsPrefix__.targetLanguage", "");
pref("__prefsPrefix__.fontSize", "12");
pref("__prefsPrefix__.lineHeight", "1.5");
pref("__prefsPrefix__.splitChar", "\ud83d\udd24");
pref("__prefsPrefix__.resultRegex", "");
pref("__prefsPrefix__.rawResultOrder", false);
pref("__prefsPrefix__.showItemMenuTitleTranslation", true);
pref("__prefsPrefix__.showItemMenuAbstractTranslation", true);
pref("__prefsPrefix__.showSidebarEngine", true);
pref("__prefsPrefix__.hideUnconfiguredServices", false);
pref("__prefsPrefix__.showSidebarSettings", true);
pref("__prefsPrefix__.showSidebarConcat", true);
pref("__prefsPrefix__.enableConcatKey", true);
pref("__prefsPrefix__.showSidebarLanguage", true);
pref("__prefsPrefix__.showSidebarRaw", true);
pref("__prefsPrefix__.showSidebarCopy", true);
pref("__prefsPrefix__.customRawRatio", "1");
pref("__prefsPrefix__.customResultRatio", "1");
pref("__prefsPrefix__.showItemBoxTitleTranslation", true);
pref("__prefsPrefix__.showItemBoxAbstractTranslation", false);
pref("__prefsPrefix__.keepWindowTop", false);
pref("__prefsPrefix__.keepPopupSize", false);
pref("__prefsPrefix__.popupWidth", 105);
pref("__prefsPrefix__.popupHeight", 30);
pref("__prefsPrefix__.niutransEndpoint", "https://niutrans.com/niuInterface");
pref("__prefsPrefix__.niutransUsername", "");
pref("__prefsPrefix__.niutransPassword", "");
pref("__prefsPrefix__.niutransDictNo", "");
pref("__prefsPrefix__.niutransMemoryNo", "");
pref("__prefsPrefix__.niutransDictLibList", "[]");
pref("__prefsPrefix__.niutransMemoryLibList", "[]");
pref("__prefsPrefix__.autoPlay", false);
pref("__prefsPrefix__.showPlayBtn", true);
pref("__prefsPrefix__.enableAutoDetectLanguage", true);
pref("__prefsPrefix__.disabledLanguages", "");
pref("__prefsPrefix__.extraEngines", "");
pref("__prefsPrefix__.titleColumnMode", "raw");
pref(
"__prefsPrefix__.chatGPT.endPoint",
"https://api.openai.com/v1/chat/completions",
);
pref("__prefsPrefix__.chatGPT.model", "gpt-4o-mini");
pref("__prefsPrefix__.chatGPT.temperature", "1.0");
pref(
"__prefsPrefix__.chatGPT.prompt",
"As an academic expert with specialized knowledge in various fields, please provide a proficient and precise translation from ${langFrom} to ${langTo} of the academic text enclosed in 🔤. It is crucial to maintaining the original phrase or sentence and ensure accuracy while utilizing the appropriate language. The text is as follows: 🔤 ${sourceText} 🔤 Please provide the translated result without any additional explanation and remove 🔤.",
);
pref("__prefsPrefix__.chatGPT.stream", true);
pref("__prefsPrefix__.chatGPT.customParams", "");
pref("__prefsPrefix__.azureGPT.endPoint", "");
pref("__prefsPrefix__.azureGPT.model", "");
pref("__prefsPrefix__.azureGPT.apiVersion", "2023-05-15");
pref("__prefsPrefix__.azureGPT.temperature", "1.0");
pref(
"__prefsPrefix__.azureGPT.prompt",
"As an academic expert with specialized knowledge in various fields, please provide a proficient and precise translation from ${langFrom} to ${langTo} of the academic text enclosed in 🔤. It is crucial to maintaining the original phrase or sentence and ensure accuracy while utilizing the appropriate language. The text is as follows: 🔤 ${sourceText} 🔤 Please provide the translated result without any additional explanation and remove 🔤.",
);
pref("__prefsPrefix__.azureGPT.stream", true);
pref("__prefsPrefix__.azureGPT.customParams", "");
pref(
"__prefsPrefix__.gemini.endPoint",
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite",
);
pref(
"__prefsPrefix__.gemini.prompt",
"As an academic expert with specialized knowledge in various fields, please provide a proficient and precise translation from ${langFrom} to ${langTo} of the academic text enclosed in 🔤. It is crucial to maintaining the original phrase or sentence and ensure accuracy while utilizing the appropriate language. The text is as follows: 🔤 ${sourceText} 🔤 Please provide the translated result without any additional explanation and remove 🔤.",
);
pref("__prefsPrefix__.gemini.stream", true);
pref(
"__prefsPrefix__.cnkiRegex",
"(查看名企职位.+?https://dict.cnki.net[a-zA-Z./]+.html?)",
);
pref("__prefsPrefix__.cnkiSplitSecond", 1);
pref("__prefsPrefix__.cnkiUseSplit", true);
pref("__prefsPrefix__.deeplx.endpoint", "https://www2.deepl.com/jsonrpc");
pref("__prefsPrefix__.deeplcustom.endpoint", "");
pref("__prefsPrefix__.pot.port", 60828);
pref(
"__prefsPrefix__.qwenmt.endPoint",
"https://dashscope.aliyuncs.com/compatible-mode",
);
pref("__prefsPrefix__.qwenmt.model", "qwen-mt-plus");
pref("__prefsPrefix__.qwenmt.domains", "");
pref("__prefsPrefix__.aliyun.action", "TranslateGeneral");
pref("__prefsPrefix__.aliyun.scene", "general");
pref("__prefsPrefix__.enableMathRendering", false);
pref("__prefsPrefix__.stripEmptyLines", false);
pref("__prefsPrefix__.libretranslate.endpoint", "http://localhost:5000");
pref("__prefsPrefix__.mtranserver.endpoint", "http://localhost:8989/translate");
pref("__prefsPrefix__.mtranserver.versionlabel", false);
pref("__prefsPrefix__.claude.stream", true);
pref(
"__prefsPrefix__.claude.endPoint",
"https://api.anthropic.com/v1/messages",
);
pref("__prefsPrefix__.claude.model", "claude-3-7-sonnet-20250219");
pref("__prefsPrefix__.claude.temperature", "0.3");
pref(
"__prefsPrefix__.claude.prompt",
"As an academic expert with specialized knowledge in various fields, please provide a proficient and precise translation from ${langFrom} to ${langTo} of the academic text enclosed in 🔤. It is crucial to maintaining the original phrase or sentence and ensure accuracy while utilizing the appropriate language. The text is as follows: 🔤 ${sourceText} 🔤 Please provide the translated result without any additional explanation and remove 🔤.",
);
pref("__prefsPrefix__.claude.maxTokens", "4000");
pref("__prefsPrefix__.xftrans.engine", "xftrans");
pref("__prefsPrefix__.tencent.region", "ap-shanghai");
pref("__prefsPrefix__.tencent.projectId", "0");
pref("__prefsPrefix__.youdaozhiyun.domain", "general");
pref("__prefsPrefix__.youdaozhiyunllm.model", "0");
pref("__prefsPrefix__.youdaozhiyunllm.stream", true);
pref("__prefsPrefix__.nllb.model", "nllb-api");
pref("__prefsPrefix__.nllb.apiendpoint", "http://localhost:7860");
pref("__prefsPrefix__.nllb.apistream", true);
pref("__prefsPrefix__.nllb.serveendpoint", "http://localhost:6060");
================================================
FILE: eslint.config.mjs
================================================
// @ts-check Let TS check this config file
import eslint from "@eslint/js";
import tseslint from "typescript-eslint";
export default tseslint.config(
{
ignores: ["build/**", "dist/**", "node_modules/**", "scripts/"],
},
{
files: ["**/*.ts"],
extends: [eslint.configs.recommended, ...tseslint.configs.recommended],
rules: {
"no-restricted-globals": [
"error",
{ message: "Use `Zotero.getMainWindow()` instead.", name: "window" },
{
message: "Use `Zotero.getMainWindow().document` instead.",
name: "document",
},
{
message: "Use `Zotero.getActiveZoteroPane()` instead.",
name: "ZoteroPane",
},
"Zotero_Tabs",
],
"@typescript-eslint/ban-ts-comment": [
"warn",
{
"ts-expect-error": "allow-with-description",
"ts-ignore": "allow-with-description",
"ts-nocheck": "allow-with-description",
"ts-check": "allow-with-description",
},
],
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-explicit-any": [
"off",
{
ignoreRestArgs: true,
},
],
"@typescript-eslint/no-non-null-assertion": "off",
},
},
{
// allow to use the `document` and `window` globals directly in CEs
files: ["src/elements/*.ts"],
rules: {
"no-restricted-globals": [
"error",
{
message: "Use `Zotero.getActiveZoteroPane()` instead.",
name: "ZoteroPane",
},
"Zotero_Tabs",
],
},
},
);
================================================
FILE: package.json
================================================
{
"name": "zotero-pdf-translate",
"version": "2.4.3",
"description": "Translate PDF, EPub, webpage, metadata, annotations, notes to the target language. Support 20+ translate services.",
"config": {
"addonName": "Translate for Zotero",
"addonID": "zoteropdftranslate@euclpts.com",
"addonRef": "zoteropdftranslate",
"prefsPrefix": "extensions.zotero.ZoteroPDFTranslate",
"addonInstance": "PDFTranslate"
},
"main": "src/index.ts",
"scripts": {
"start": "zotero-plugin serve",
"build": "tsc --noEmit && zotero-plugin build",
"release": "zotero-plugin release",
"lint": "prettier --write . && eslint . --fix",
"test": "echo \"Error: no test specified\" && exit 1",
"update-deps": "npm update --save"
},
"repository": {
"type": "git",
"url": "git+https://github.com/windingwind/zotero-pdf-translate.git"
},
"author": "windingwind",
"license": "AGPL-3.0-or-later",
"bugs": {
"url": "https://github.com/windingwind/zotero-pdf-translate/issues"
},
"homepage": "https://github.com/windingwind/zotero-pdf-translate#readme",
"dependencies": {
"franc": "^6.2.0",
"iso639-js": "^1.1.3",
"jsencrypt": "^3.5.0",
"katex": "^0.16.25",
"zotero-plugin-toolkit": "^5.1.0-beta.8"
},
"devDependencies": {
"@eslint/js": "^9.39.1",
"@types/node": "^22.16.5",
"chokidar-cli": "^3.0.0",
"concurrently": "^9.2.0",
"cross-env": "^10.1.0",
"eslint": "^9.39.1",
"husky": "^9.1.7",
"lint-staged": "^16.2.7",
"prettier": "^3.7.4",
"typescript": "^5.9.3",
"typescript-eslint": "^8.48.1",
"zotero-plugin-scaffold": "^0.8.2",
"zotero-types": "^4.1.0-beta.3"
}
}
================================================
FILE: src/addon.ts
================================================
import api from "./api";
import hooks from "./hooks";
import { TranslateTask } from "./utils/task";
import { services, TranslationServices } from "./modules/services";
import { createZToolkit } from "./utils/ztoolkit";
import { config } from "../package.json";
class Addon {
public data: {
config: typeof config;
alive: boolean;
// Env type, see build.js
env: "development" | "production";
ztoolkit: ZToolkit;
locale: {
current?: any;
};
prefs: {
window: Window | null;
};
panel: {
tabOptionId: string;
activePanels: Record void>;
windowPanel: Window | null;
};
popup: {
currentPopup: HTMLDivElement | null;
};
translate: {
selectedText: string;
concatKey: boolean;
concatCheckbox: boolean;
queue: TranslateTask[];
maximumQueueLength: number;
batchTaskDelay: number;
services: TranslationServices;
cachedSourceLanguage: Record;
refreshTick: string;
};
};
// Lifecycle hooks
public hooks: typeof hooks;
// APIs
public api: typeof api;
constructor() {
this.data = {
config,
alive: true,
env: __env__,
ztoolkit: createZToolkit(),
locale: {},
prefs: { window: null },
panel: { tabOptionId: "", activePanels: {}, windowPanel: null },
popup: { currentPopup: null },
translate: {
selectedText: "",
concatKey: false,
concatCheckbox: false,
queue: [],
maximumQueueLength: 100,
batchTaskDelay: 1000,
services,
cachedSourceLanguage: {},
refreshTick: "",
},
};
this.hooks = hooks;
this.api = api;
}
}
export default Addon;
================================================
FILE: src/api.ts
================================================
import { getPref } from "./utils/prefs";
import { TranslateTask } from "./utils/task";
import { version } from "../package.json";
/**
* To plugin developers: Please use this API to translate your custom text.
*
* @param raw raw text for translation.
* @param options options.
* @returns TranslateTask object.
*/
async function translate(
raw: string,
options: {
/**
* The caller identifier.
* This is for translate service provider to identify the caller.
* If not provided, the call will fail.
*/
pluginID: string;
/**
* Service id. See src/utils/config.ts > SERVICES
* If not provided, the default service will be used.
* If you want to use multiple services, please provide an array of service ids.
* The first service in the array will be used as the default service.
* Others will be used as fallback services.
*/
service?: string | string[];
/**
* Zotero item id.
*
* For language auto-detect check.
* If not set, use the default value.
*/
itemID?: number;
/**
* From language
*
* If not set, generate at task runtime.
*/
langfrom?: string;
/**
* To language.
*
* If not set, generate at task runtime.
*/
langto?: string;
},
): Promise;
/**
* @deprecated The implementation of call with second parameter `services` will be removed in the future. Please use `translate(raw, options)` instead.
*
* @param raw raw text for translation.
* @param service service id. See src/utils/config.ts > SERVICES
* If not provided, the default service will be used.
* If you want to use multiple services, please provide an array of service ids.
* The first service in the array will be used as the default service.
* Others will be used as fallback services.
* @returns TranslateTask object.
*/
async function translate(
raw: string,
service?: string | string[],
): Promise;
async function translate(
raw: string,
serviceOrOptions?: string | string[] | any,
) {
let currentService: string;
let candidateServices: string[] = [];
let service;
let isDeprecatedCall = false;
if (
!serviceOrOptions ||
typeof serviceOrOptions === "string" ||
Array.isArray(serviceOrOptions)
) {
service = serviceOrOptions;
isDeprecatedCall = true;
} else if (typeof serviceOrOptions === "object") {
service = serviceOrOptions.service;
}
serviceOrOptions = serviceOrOptions || {};
if (!isDeprecatedCall && !(serviceOrOptions as any).pluginID) {
throw `[Translate for Zotero:api.translate] pluginID is required since 1.1.0-23. Please contact the plugin developer for more information.`;
}
if (isDeprecatedCall) {
Zotero.warn(
new Error(
"[Translate for Zotero:api.translate] This call is deprecated. Please use `translate(raw, options)` instead.",
),
);
}
if (typeof service === "string") {
currentService = service;
} else if (Array.isArray(service)) {
currentService = service[0];
candidateServices = service.slice(1);
} else {
currentService = getPref("translateSource") as string;
}
const data: TranslateTask = {
id: `${Zotero.Utilities.randomString()}-${new Date().getTime()}`,
type: "custom",
raw,
result: "",
audio: [],
service: currentService,
candidateServices,
itemId: isDeprecatedCall ? -1 : (serviceOrOptions as any).itemID || -1,
status: "waiting",
extraTasks: [],
silent: true,
langfrom: isDeprecatedCall ? undefined : (serviceOrOptions as any).langfrom,
langto: isDeprecatedCall ? undefined : (serviceOrOptions as any).langto,
callerID: isDeprecatedCall
? "unknown caller with translate for zotero api"
: (serviceOrOptions as any).pluginID,
};
await addon.data.translate.services.runTranslationTask(data, {
noDisplay: true,
});
return data;
}
/**
* Get a temporary refresh handler.
* This handler will refresh the reader popup and item pane section.
* This handler is temporary and will be invalid after another call.
* @returns A temporary refresh handler.
*/
function getTemporaryRefreshHandler(options?: { task?: TranslateTask }) {
const translateTask = options?.task;
if (translateTask && translateTask.type !== "text") {
return () => {};
}
const newTick = `${Zotero.Utilities.randomString()}-${Date.now()}`;
addon.data.translate.refreshTick = newTick;
return () => {
if (addon.data.translate.refreshTick === newTick) {
addon.hooks.onReaderPopupRefresh();
addon.hooks.onReaderTabPanelRefresh();
}
};
}
/**
* Get all available services.
* @returns Array of services.
*/
function getServices() {
return addon.data.translate.services
.getAllServices()
.map((service) => Object.assign({}, service));
}
/**
* Get version of the plugin.
* @returns Version of the plugin.
*/
function getVersion() {
return version;
}
export default {
translate,
getServices,
getVersion,
getTemporaryRefreshHandler,
};
================================================
FILE: src/elements/base.ts
================================================
import { config } from "../../package.json";
export class PluginCEBase extends XULElementBase {
_addon!: typeof addon;
useShadowRoot = false;
connectedCallback(): void {
// @ts-ignore - Plugin instance is not typed
this._addon = Zotero[config.addonInstance];
Zotero.UIProperties.registerRoot(this);
if (!this.useShadowRoot) {
super.connectedCallback();
return;
}
this.attachShadow({ mode: "open" });
// Following the connectedCallback from XULElementBase
let content: Node = this.content;
if (content) {
content = document.importNode(content, true);
this.shadowRoot?.append(content);
}
MozXULElement.insertFTLIfNeeded("branding/brand.ftl");
MozXULElement.insertFTLIfNeeded("zotero.ftl");
if (document.l10n && this.shadowRoot) {
document.l10n.connectRoot(this.shadowRoot);
}
window.addEventListener("unload", this._handleWindowUnload);
this.initialized = true;
this.init();
}
_wrapID(key: string) {
if (key.startsWith(config.addonRef)) {
return key;
}
return `${config.addonRef}-${key}`;
}
_unwrapID(id: string) {
if (id.startsWith(config.addonRef)) {
return id.slice(config.addonRef.length + 1);
}
return id;
}
_queryID(key: string) {
const selector = `#${this._wrapID(key)}`;
return (this.querySelector(selector) ||
this.shadowRoot?.querySelector(selector)) as
| XUL.Element
| HTMLElement
| null;
}
_parseContentID(dom: DocumentFragment) {
dom.querySelectorAll("*[id]").forEach((elem) => {
elem.id = this._wrapID(elem.id);
});
dom.querySelectorAll("*[data-l10n-id]").forEach((elem) => {
elem.setAttribute(
"data-l10n-id",
this._wrapID(elem.getAttribute("data-l10n-id")!),
);
});
return dom;
}
}
================================================
FILE: src/elements/mathTextbox.ts
================================================
import { config } from "../../package.json";
import { renderMathInText, containsMath } from "../utils/mathRenderer";
import { getPref } from "../utils/prefs";
export class MathTextboxElement extends XULElementBase {
private _textbox: XULTextBoxElement | null = null;
private _overlay: HTMLElement | null = null;
private _value: string = "";
get content() {
return MozXULElement.parseXULToFragment(`
`);
}
connectedCallback(): void {
super.connectedCallback();
this.init();
}
init(): void {
this._textbox = this.querySelector("#inner-textbox") as XULTextBoxElement;
if (!this._textbox) return;
this._textbox.addEventListener("input", this._onInput);
this._textbox.addEventListener("focus", this._onFocus);
this._textbox.addEventListener("blur", this._onBlur);
}
set value(v: string) {
this._value = v ?? "";
if (this._textbox) this._textbox.value = this._value;
this._updateOverlay();
}
get value() {
return this._textbox?.value ?? this._value;
}
set placeholder(v: string) {
if (this._textbox) this._textbox.placeholder = v;
}
focus(): void {
this._textbox?.focus();
}
private _onInput = (e: Event) => {
const val = (e.target as HTMLTextAreaElement).value;
this._value = val;
// do not redispatch input; bubble from inner editable-text already reaches panel listener
};
private _onFocus = () => {
this._hideOverlay();
};
private _onBlur = () => {
this._updateOverlay();
};
private _updateOverlay(): void {
// Respect user preference gate
const enabled = (getPref("enableMathRendering") as boolean) === true;
if (!enabled || !this._value || !containsMath(this._value)) {
this._hideOverlay();
return;
}
this._showOverlay();
}
private _showOverlay(): void {
if (this._overlay) this._overlay.remove();
const HTML_NS = "http://www.w3.org/1999/xhtml";
const overlay = document.createElementNS(
HTML_NS,
"div",
) as unknown as HTMLElement;
overlay.className = "math-overlay";
overlay.innerHTML = renderMathInText(document, this._value);
overlay.addEventListener("click", () => {
this._hideOverlay();
this._textbox?.focus();
});
this._overlay = overlay;
this.appendChild(overlay);
this.toggleAttribute("overlay-visible", true);
}
private _hideOverlay(): void {
if (this._overlay) {
this._overlay.remove();
this._overlay = null;
}
this.toggleAttribute("overlay-visible", false);
}
destroy(): void {
this._hideOverlay();
if (this._textbox) {
this._textbox.removeEventListener("input", this._onInput);
this._textbox.removeEventListener("focus", this._onFocus);
this._textbox.removeEventListener("blur", this._onBlur);
}
}
}
================================================
FILE: src/elements/panel.ts
================================================
import { config } from "../../package.json";
import { PluginCEBase } from "./base";
import { getPref, setPref } from "../utils/prefs";
import { LANG_CODE } from "../utils/config";
import {
addTranslateTask,
autoDetectLanguage,
getLastTranslateTask,
putTranslateTaskAtHead,
} from "../utils/task";
import type { TranslationServices } from "../modules/services";
//@ts-expect-error addon instance not typed
const services = Zotero[config.addonInstance].data.translate
.services as TranslationServices;
export class TranslatorPanel extends PluginCEBase {
_item: Zotero.Item | null = null;
_taskID = "";
get item() {
return this._item;
}
set item(val) {
this._item = val;
}
get content() {
return this._parseContentID(
MozXULElement.parseXULToFragment(`
${services
.getAllServicesWithType("sentence")
.map((service) => {
const customName = services.getServiceNameByID(service.id);
return ``;
})
.join("\n")}
${LANG_CODE.map((lang) => ``).join("\n")}
${LANG_CODE.map((lang) => ``).join("\n")}
${
(getPref("enableMathRendering") as boolean)
? ``
: ``
}
${
(getPref("enableMathRendering") as boolean)
? ``
: ``
}
`),
);
}
init(): void {
// Services
this._queryID("services")?.addEventListener("command", (e) => {
const newService = (e.target as XUL.MenuList).value;
setPref("translateSource", newService);
this._addon.hooks.onReaderTabPanelRefresh();
const data = getLastTranslateTask();
if (!data) {
return;
}
data.service = newService;
this._addon.hooks.onTranslate(undefined, {
noCheckZoteroItemLanguage: true,
});
});
// Translate
this._queryID("translate")?.addEventListener("command", () => {
if (!getLastTranslateTask()) {
addTranslateTask(
(
this._queryID(
getPref("rawResultOrder") ? "result-text" : "raw-text",
) as HTMLTextAreaElement
)?.value,
);
}
this._addon.hooks.onTranslate(undefined, {
noCheckZoteroItemLanguage: true,
noCache: true,
});
});
// Language change
this._queryID("langfrom")?.addEventListener("command", (e) => {
const newValue = (e.target as XUL.MenuList).value;
setPref("sourceLanguage", newValue);
const itemID = this.item?.id;
if (itemID) {
this._addon.data.translate.cachedSourceLanguage[Number(itemID)] =
newValue;
}
this._addon.hooks.onReaderTabPanelRefresh();
});
this._queryID("swap-language")?.addEventListener("command", () => {
const langfrom = getPref("sourceLanguage") as string;
const langto = getPref("targetLanguage") as string;
setPref("targetLanguage", langfrom);
setPref("sourceLanguage", langto);
this._addon.hooks.onReaderTabPanelRefresh();
});
this._queryID("langto")?.addEventListener("command", (e) => {
setPref("targetLanguage", (e.target as XUL.MenuList).value);
this._addon.hooks.onReaderTabPanelRefresh();
});
// Text change
this._queryID("raw-text")?.addEventListener("input", (e) => {
let task = getLastTranslateTask({
id: this._taskID,
});
if (!task) {
task = addTranslateTask(
(e.target as HTMLTextAreaElement).value,
this.item?.id,
"text",
);
if (task) this._taskID = task.id;
}
if (!task) {
return;
}
const reverseRawResult = getPref("rawResultOrder");
if (!reverseRawResult) {
task.raw = (e.target as HTMLTextAreaElement).value;
} else {
task.result = (e.target as HTMLTextAreaElement).value;
}
putTranslateTaskAtHead(task.id);
});
this._queryID("result-text")?.addEventListener("input", (e) => {
let task = getLastTranslateTask({
id: this._taskID,
});
if (!task) {
task = addTranslateTask(
(e.target as HTMLTextAreaElement).value,
this.item?.id,
"text",
);
if (task) this._taskID = task.id;
}
if (!task) {
return;
}
const reverseRawResult = getPref("rawResultOrder");
if (!reverseRawResult) {
task.result = (e.target as HTMLTextAreaElement).value;
} else {
task.raw = (e.target as HTMLTextAreaElement).value;
}
putTranslateTaskAtHead(task.id);
});
// Auto translate
this._queryID("auto-trans-selection")?.addEventListener("command", (e) => {
setPref("enableAuto", (e.target as XUL.Checkbox).checked);
this._addon.hooks.onReaderTabPanelRefresh();
});
this._queryID("auto-trans-annotation")?.addEventListener("command", (e) => {
setPref("enableComment", (e.target as XUL.Checkbox).checked);
this._addon.hooks.onReaderTabPanelRefresh();
});
// Concat
this._queryID("concat")?.addEventListener("command", (e) => {
this._addon.data.translate.concatCheckbox = (
e.target as XUL.Checkbox
).checked;
this._addon.hooks.onReaderTabPanelRefresh();
});
this._queryID("clear-concat")?.addEventListener("command", () => {
const task = getLastTranslateTask();
if (task) {
task.raw = "";
task.result = "";
task.extraTasks.forEach((t) => {
t.result = "";
});
this._addon.hooks.onReaderTabPanelRefresh();
}
});
// Copy
this._queryID("copy-raw")?.addEventListener("command", () => {
const task = getLastTranslateTask({
id: this._taskID,
});
if (!task) {
return;
}
new this._addon.data.ztoolkit.Clipboard()
.addText(task.raw, "text/plain")
.copy();
});
this._queryID("copy-result")?.addEventListener("command", () => {
const task = getLastTranslateTask({
id: this._taskID,
});
if (!task) {
return;
}
new this._addon.data.ztoolkit.Clipboard()
.addText(task.result, "text/plain")
.copy();
});
this._queryID("copy-both")?.addEventListener("command", () => {
const task = getLastTranslateTask({
id: this._taskID,
});
if (!task) {
return;
}
new this._addon.data.ztoolkit.Clipboard()
.addText(`${task.raw}\n----\n${task.result}`, "text/plain")
.copy();
});
// Draggable text area
const resizer = this._queryID("resizer") as HTMLElement;
const container = this._queryID("text-container") as HTMLElement;
const rawArea = this._queryID("raw-text") as HTMLElement;
const resultArea = this._queryID("result-text") as HTMLElement;
rawArea.style.flex = `${getPref("customRawRatio")} 1 0%`;
resultArea.style.flex = `${getPref("customResultRatio")} 1 0%`;
let isDragging = false;
let containerRect: DOMRect;
resizer?.addEventListener("mousedown", (e: MouseEvent) => {
if (e.button !== 0) {
return;
}
isDragging = true;
e.preventDefault();
containerRect = container.getBoundingClientRect();
window.document.addEventListener("mousemove", doDrag);
window.document.addEventListener("mouseup", (e: MouseEvent) => {
isDragging = false;
window.document.removeEventListener("mousemove", doDrag);
});
});
function doDrag(e: MouseEvent) {
if (!isDragging) {
return;
}
const newRawHeight = e.clientY - containerRect.top;
const maxRawHeight = containerRect.height - 100 - 13;
if (newRawHeight >= 100 && newRawHeight <= maxRawHeight) {
const newResultHeight = containerRect.height - newRawHeight - 13;
const newRawRatio = (
newRawHeight / Math.min(newRawHeight, newResultHeight)
).toFixed(3);
const newResultRatio = (
newResultHeight / Math.min(newRawHeight, newResultHeight)
).toFixed(3);
rawArea.style.flex = `${newRawRatio} 1 0%`;
resultArea.style.flex = `${newResultRatio} 1 0%`;
setPref("customRawRatio", newRawRatio);
setPref("customResultRatio", newResultRatio);
}
}
resizer?.addEventListener("dblclick", (e: MouseEvent) => {
if (e.button !== 0) {
return;
}
e.preventDefault();
rawArea.style.flex = "1 1 0%";
resultArea.style.flex = "1 1 0%";
setPref("customRawRatio", "1");
setPref("customResultRatio", "1");
});
}
destroy(): void {}
/**
* Filter unconfigured services from the dropdown menu.
* Hides services that require API keys but haven't been configured.
*/
_filterUnconfiguredServices() {
const menuPopup = this._queryID("services")?.querySelector("menupopup");
if (!menuPopup) return;
const menuItems = menuPopup.querySelectorAll("menuitem");
const hideUnconfigured = getPref("hideUnconfiguredServices") as boolean;
const unconfiguredIds = hideUnconfigured
? services.getUnconfiguredServiceIds()
: null;
menuItems.forEach((item) => {
const serviceId = item.getAttribute("value");
(item as HTMLElement).hidden = !!unconfiguredIds?.has(serviceId || "");
});
}
render() {
const updateHidden = (type: string, pref: string) => {
const elem = this._queryID(type) as XUL.Box;
const hidden = !getPref(pref) as boolean;
elem.hidden = hidden;
if (
elem.nextElementSibling?.classList.contains("separator") ||
elem.nextElementSibling?.classList.contains("draggable-container")
) {
(elem.nextElementSibling as HTMLDivElement).hidden = hidden;
}
};
const setCheckBox = (type: string, checked: boolean) => {
const elem = this._queryID(type) as XUL.Checkbox;
elem.checked = checked;
};
const setValue = (type: string, value: string) => {
const elem = this._queryID(type) as XUL.Textbox;
elem.value = value;
};
const setPalceHolder = (type: string, placeholder: string) => {
const elem = this._queryID(type) as XUL.Textbox;
elem.placeholder = placeholder;
};
const setTextBoxStyle = (type: string) => {
const elem = this._queryID(type) as XUL.Textbox;
elem.style.fontSize = `${getPref("fontSize")}px`;
elem.style.lineHeight = getPref("lineHeight") as string;
};
updateHidden("engine", "showSidebarEngine");
updateHidden("language", "showSidebarLanguage");
updateHidden("raw-text", "showSidebarRaw");
updateHidden("auto-container", "showSidebarSettings");
updateHidden("concat-container", "showSidebarConcat");
updateHidden("copy-container", "showSidebarCopy");
// Filter unconfigured services from dropdown if preference is enabled
this._filterUnconfiguredServices();
setValue("services", getPref("translateSource") as string);
const { fromLanguage, toLanguage } = autoDetectLanguage(this.item);
setValue("langfrom", fromLanguage);
setValue("langto", toLanguage);
setCheckBox("auto-trans-selection", getPref("enableAuto") as boolean);
setCheckBox("auto-trans-annotation", getPref("enableComment") as boolean);
setCheckBox("concat", this._addon.data.translate.concatCheckbox);
setTextBoxStyle("raw-text");
setTextBoxStyle("result-text");
const reverseRawResult = getPref("rawResultOrder");
setPalceHolder(
"raw-text",
reverseRawResult ? "" : "Select or type to translate",
);
setPalceHolder(
"result-text",
reverseRawResult ? "Select or type to translate" : "",
);
const lastTask = getLastTranslateTask();
if (!lastTask) {
return;
}
// For manually update translation task
this._taskID = lastTask.id;
if (
lastTask.type === "text" ||
(lastTask.raw === "" && lastTask.result === "")
) {
setValue("raw-text", reverseRawResult ? lastTask.result : lastTask.raw);
setValue(
"result-text",
reverseRawResult ? lastTask.raw : lastTask.result,
);
}
}
}
================================================
FILE: src/extras/customElements.ts
================================================
import { TranslatorPanel } from "../elements/panel";
import { MathTextboxElement } from "../elements/mathTextbox";
const elements = {
"translator-plugin-panel": TranslatorPanel,
"math-textbox": MathTextboxElement,
} as unknown as Record;
for (const [key, constructor] of Object.entries(elements)) {
if (!customElements.get(key)) {
customElements.define(key, constructor);
}
}
================================================
FILE: src/hooks.ts
================================================
import { config } from "../package.json";
import { initLocale } from "./utils/locale";
import {
registerPrefsScripts,
registerPrefsWindow,
} from "./modules/preferenceWindow";
import {
registerReaderTabPanel,
updateReaderTabPanels,
} from "./modules/tabpanel";
import { buildReaderPopup, updateReaderPopup } from "./modules/popup";
import { registerNotify } from "./modules/notify";
import { registerReaderInitializer } from "./modules/reader";
import { getPref } from "./utils/prefs";
import {
addTranslateAnnotationTask,
addTranslateTask,
addTranslateTitleTask,
getLastTranslateTask,
TranslateTask,
} from "./utils/task";
import { setDefaultPrefSettings } from "./modules/defaultPrefs";
import Addon from "./addon";
import { registerMenu } from "./modules/menu";
import { registerExtraColumns } from "./modules/itemTree";
import { registerShortcuts } from "./modules/shortcuts";
import { registerItemPaneInfoRows } from "./modules/infoBox";
import { registerPrompt } from "./modules/prompt";
import { registerCustomFields } from "./modules/fields";
async function onStartup() {
await Promise.all([
Zotero.initializationPromise,
Zotero.unlockPromise,
Zotero.uiReadyPromise,
]);
// TODO: Remove this after zotero#3387 is merged
if (__env__ === "development") {
// Keep in sync with the scripts/startup.mjs
const loadDevToolWhen = `Plugin ${config.addonID} startup`;
ztoolkit.log(loadDevToolWhen);
}
initLocale();
setDefaultPrefSettings();
registerCustomFields();
registerReaderInitializer();
registerShortcuts();
registerNotify(["item"]);
registerPrefsWindow();
registerExtraColumns();
registerItemPaneInfoRows();
registerReaderTabPanel();
await Promise.all(
Zotero.getMainWindows().map((win) => onMainWindowLoad(win)),
);
}
async function onMainWindowLoad(win: Window): Promise {
await new Promise((resolve) => {
if (win.document.readyState !== "complete") {
win.document.addEventListener("readystatechange", () => {
if (win.document.readyState === "complete") {
resolve(void 0);
}
});
}
resolve(void 0);
});
await Promise.all([
Zotero.initializationPromise,
Zotero.unlockPromise,
Zotero.uiReadyPromise,
]);
Services.scriptloader.loadSubScript(
`chrome://${config.addonRef}/content/scripts/customElements.js`,
win,
);
(win as any).MozXULElement.insertFTLIfNeeded(
`${config.addonRef}-mainWindow.ftl`,
);
registerMenu();
registerPrompt();
win.document.addEventListener("focusout", (ev) => {
if (ev.target !== win.document) {
return;
}
addon.data.translate.concatKey = false;
});
}
async function onMainWindowUnload(win: Window): Promise {
win.document
.querySelector(`[href="${config.addonRef}-mainWindow.ftl"]`)
?.remove();
}
function onShutdown(): void {
ztoolkit.unregisterAll();
Zotero.getMainWindows().forEach((win) => {
onMainWindowUnload(win);
});
// Remove addon object
addon.data.alive = false;
// @ts-ignore - Plugin instance is not typed
delete Zotero[config.addonInstance];
}
/**
* This function is just an example of dispatcher for Notify events.
* Any operations should be placed in a function to keep this function clear.
*/
function onNotify(
event: string,
type: string,
ids: Array,
extraData: { [key: string]: any },
) {
if (event === "add" && type === "item") {
if (
!getPref("enableAnnotationFromSyncTranslation") &&
extraData?.skipAutoSync
)
return;
const annotationItems = Zotero.Items.get(ids as number[]).filter((item) =>
item.isAnnotation(),
);
if (annotationItems.length === 0) {
return;
}
if (getPref("enableComment")) {
addon.hooks.onTranslateInBatch(
annotationItems
.map((item) => addTranslateAnnotationTask(item.id))
.filter((task) => task) as TranslateTask[],
{ noDisplay: true },
);
}
} else if (type === "tab" && ["select", "add", "close"].includes(event)) {
addon.data.translate.concatKey = false;
} else {
return;
}
}
function onPrefsLoad(event: Event) {
registerPrefsScripts((event.target as any).ownerGlobal);
}
function onShortcuts(type: string) {
switch (type) {
case "library":
{
addon.hooks.onTranslateInBatch(
Zotero.getActiveZoteroPane()
.getSelectedItems(true)
.map((id) => addTranslateTitleTask(id, true))
.filter((task) => task) as TranslateTask[],
{ noDisplay: true, noCache: true },
);
}
break;
case "reader":
{
addon.hooks.onTranslate(undefined, {
noCheckZoteroItemLanguage: true,
noCache: true,
});
}
break;
default:
break;
}
}
async function onTranslate(): Promise;
async function onTranslate(
options: Parameters<
Addon["data"]["translate"]["services"]["runTranslationTask"]
>["1"],
): Promise;
async function onTranslate(
task: TranslateTask | undefined,
options?: Parameters<
Addon["data"]["translate"]["services"]["runTranslationTask"]
>["1"],
): Promise;
async function onTranslate(...data: any) {
let task = undefined;
let options = {};
if (data.length === 1) {
if (data[0].raw) {
task = data[0];
} else {
options = data[0];
}
} else if (data.length === 2) {
task = data[0];
options = data[1];
}
await addon.data.translate.services.runTranslationTask(task, options);
}
async function onTranslateInBatch(
tasks: TranslateTask[],
options: Parameters<
Addon["data"]["translate"]["services"]["runTranslationTask"]
>["1"] = {},
) {
for (const task of tasks) {
await addon.hooks.onTranslate(task, options);
await Zotero.Promise.delay(addon.data.translate.batchTaskDelay);
}
}
function onReaderPopupShow(
event: _ZoteroTypes.Reader.EventParams<"renderTextSelectionPopup">,
) {
const selection = addon.data.translate.selectedText;
const task = getLastTranslateTask();
if (task?.raw === selection) {
buildReaderPopup(event);
addon.hooks.onReaderPopupRefresh();
return;
}
addTranslateTask(selection, event.reader.itemID);
buildReaderPopup(event);
addon.hooks.onReaderPopupRefresh();
if (getPref("enableAuto")) {
addon.hooks.onTranslate();
}
}
function onReaderPopupRefresh() {
updateReaderPopup();
}
function onReaderTabPanelRefresh() {
updateReaderTabPanels();
}
// Add your hooks here. For element click, etc.
// Keep in mind hooks only do dispatch. Don't add code that does real jobs in hooks.
// Otherwise the code would be hard to read and maintain.
export default {
onStartup,
onMainWindowLoad,
onMainWindowUnload,
onShutdown,
onNotify,
onPrefsLoad,
onShortcuts,
onTranslate,
onTranslateInBatch,
onReaderPopupShow,
onReaderPopupRefresh,
onReaderTabPanelRefresh,
};
================================================
FILE: src/index.ts
================================================
import { BasicTool } from "zotero-plugin-toolkit";
import Addon from "./addon";
import { config } from "../package.json";
const basicTool = new BasicTool();
// @ts-ignore - Plugin instance is not typed
if (!basicTool.getGlobal("Zotero")[config.addonInstance]) {
// Set global variables
_globalThis.Zotero = basicTool.getGlobal("Zotero");
defineGlobal("crypto");
defineGlobal("TextEncoder");
_globalThis.addon = new Addon();
defineGlobal("ztoolkit", () => {
return _globalThis.addon.data.ztoolkit;
});
// @ts-ignore - Plugin instance is not typed
Zotero[config.addonInstance] = addon;
// Trigger addon hook for initialization
addon.hooks.onStartup();
}
function defineGlobal(name: Parameters[0]): void;
function defineGlobal(name: string, getter: () => any): void;
function defineGlobal(name: string, getter?: () => any) {
Object.defineProperty(_globalThis, name, {
get() {
return getter ? getter() : basicTool.getGlobal(name);
},
});
}
================================================
FILE: src/modules/defaultPrefs.ts
================================================
import { clearPref, getPref, getPrefJSON, setPref } from "../utils/prefs";
import { getServiceSecret, setServiceSecret } from "../utils/secret";
import { services } from "./services";
export function setDefaultPrefSettings() {
const isZhCN = Zotero.locale === "zh-CN";
const servicesIds = services.getAllServices().map((service) => service.id);
if (!servicesIds.includes((getPref("translateSource") as string) || "")) {
// Google Translate is not accessible in China mainland
setPref("translateSource", isZhCN ? "cnki" : "googleapi");
}
if (!servicesIds.includes((getPref("dictSource") as string) || "")) {
setPref("dictSource", isZhCN ? "bingdict" : "freedictionaryapi");
}
if (!getPref("targetLanguage")) {
setPref("targetLanguage", Zotero.locale);
}
const secrets = getPrefJSON("secretObj");
for (const serviceId of servicesIds) {
if (typeof secrets[serviceId] === "undefined") {
secrets[serviceId] =
services.getServiceById(serviceId)!.defaultSecret || "";
}
}
setPref("secretObj", JSON.stringify(secrets));
// From v2.2.22, migrate previous settings in secrets to prefs
const deeplxApiSecret = getServiceSecret("deeplcustom");
if (deeplxApiSecret && !getPref("deeplcustom.endpoint")) {
setPref("deeplcustom.endpoint", deeplxApiSecret);
}
if (isZhCN && !getPref("disabledLanguages")) {
setPref("disabledLanguages", "zh,zh-CN,中文;");
}
const extraServices = getPref("extraEngines") as string;
if (extraServices.startsWith(",")) {
setPref("extraEngines", extraServices.slice(1));
}
// For NiuTrans login. niutransLog is deprecated.
const niutransApiKey = getPref("niutransApikey") as string;
if (niutransApiKey) {
setServiceSecret("niutranspro", niutransApiKey);
clearPref("niutransApikey");
}
if (getPref("translateSource") === "niutransLog") {
setPref("translateSource", "niutranspro");
}
try {
const oldDict = JSON.parse(
(getPref("niutransDictLibList") as string) || "{}",
);
if (oldDict?.dlist) {
setPref("niutransDictLibList", JSON.stringify(oldDict.dlist));
} else {
setPref("niutransDictLibList", "[]");
}
const oldMemory = JSON.parse(
(getPref("niutransMemoryLibList") as string) || "{}",
);
if (oldMemory?.mlist) {
setPref("niutransMemoryLibList", JSON.stringify(oldMemory?.mlist));
} else {
setPref("niutransMemoryLibList", "[]");
}
} catch (e) {
setPref("niutransDictLibList", "[]");
setPref("niutransMemoryLibList", "[]");
}
// For xftrans, xftrans.useNiutrans Pref is deprecated.
const useNiutrans = getPref("xftrans.useNiutrans") as boolean;
if (useNiutrans) {
setPref("xftrans.engine", "niutrans");
}
clearPref("xftrans.useNiutrans");
// From v2.3.1 to v2.3.7, Pref customGPTx.temperature has been set as number type
// Change the type from number to string to be compatible with floating-point values
const gptKeys = ["customGPT1", "customGPT2", "customGPT3"];
gptKeys.forEach((key) => {
const prefKey = `${key}.temperature`;
const value = getPref(prefKey);
if (value !== undefined && typeof value === "number") {
clearPref(prefKey);
setPref(prefKey, String(value));
}
});
if (!getPref("annotationTagContent")) {
setPref("annotationTagContent", isZhCN ? "翻译" : "Translation");
}
}
================================================
FILE: src/modules/fields.ts
================================================
export { registerCustomFields };
function registerCustomFields() {
ztoolkit.FieldHook.register(
"getField",
"titleTranslation",
(
field: string,
unformatted: boolean,
includeBaseMapped: boolean,
item: Zotero.Item,
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
original: Function,
) => {
return ztoolkit.ExtraField.getExtraField(item, field) || "";
},
);
ztoolkit.FieldHook.register(
"getField",
"abstractTranslation",
(
field: string,
unformatted: boolean,
includeBaseMapped: boolean,
item: Zotero.Item,
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
original: Function,
) => {
return ztoolkit.ExtraField.getExtraField(item, field) || "";
},
);
}
================================================
FILE: src/modules/infoBox.ts
================================================
import { getPref } from "../utils/prefs";
export { registerItemPaneInfoRows };
function registerItemPaneInfoRows() {
if (!Zotero.ItemPaneManager.registerInfoRow) {
return;
}
if (getPref("showItemBoxTitleTranslation") !== false) {
Zotero.ItemPaneManager.registerInfoRow({
rowID: "titleTranslation",
pluginID: addon.data.config.addonID,
label: {
l10nID: `${addon.data.config.addonRef}-field-titleTranslation`,
},
onGetData: (options) => {
return (
ztoolkit.ExtraField.getExtraField(options.item, "titleTranslation") ||
""
);
},
onSetData: (options) => {
ztoolkit.ExtraField.setExtraField(
options.item,
"titleTranslation",
options.value,
);
},
position: "start",
editable: true,
});
}
if (getPref("showItemBoxAbstractTranslation") !== false) {
Zotero.ItemPaneManager.registerInfoRow({
rowID: "abstractTranslation",
pluginID: addon.data.config.addonID,
label: {
l10nID: `${addon.data.config.addonRef}-field-abstractTranslation`,
},
onGetData: (options) => {
return (
ztoolkit.ExtraField.getExtraField(
options.item,
"abstractTranslation",
) || ""
);
},
onSetData: (options) => {
ztoolkit.ExtraField.setExtraField(
options.item,
"abstractTranslation",
options.value,
);
},
position: "afterCreators",
editable: true,
multiline: true,
});
}
}
================================================
FILE: src/modules/itemTree.ts
================================================
import { config } from "../../package.json";
import { getString } from "../utils/locale";
export function registerExtraColumns() {
// TEMP: Remove after Zotero 7.0.10
const registerColumn =
Zotero.ItemTreeManager.registerColumn ||
Zotero.ItemTreeManager.registerColumns;
registerColumn.apply(Zotero.ItemTreeManager, [
{
dataKey: "titleTranslation",
label: getString("field-titleTranslation"),
dataProvider: (item, dataKey) =>
ztoolkit.ExtraField.getExtraField(item, "titleTranslation") || "",
pluginID: config.addonID,
zoteroPersist: ["width", "hidden", "sortDirection"],
},
]);
}
================================================
FILE: src/modules/menu.ts
================================================
import { config } from "../../package.json";
import { getPref } from "../utils/prefs";
import {
addTranslateAbstractTask,
addTranslateTitleTask,
TranslateTask,
} from "../utils/task";
export function registerMenu() {
const menuIcon = `chrome://${config.addonRef}/content/icons/favicon.png`;
Zotero.MenuManager.registerMenu({
menuID: `${config.addonRef}-translate-title`,
pluginID: config.addonID,
target: "main/library/item",
menus: [
{
menuType: "menuitem",
l10nID: `${config.addonRef}-itemmenu-translateTitle`,
icon: menuIcon,
onCommand: (event, context) => {
if (!context.items?.length) {
return;
}
addon.hooks.onTranslateInBatch(
context.items
.map((item) => addTranslateTitleTask(item.id, true))
.filter((task) => task) as TranslateTask[],
{ noDisplay: true, noCache: true },
);
},
onShowing: (event, context) => {
context.setVisible(
!!(
getPref("showItemMenuTitleTranslation") &&
context.items?.every((item) => item.isRegularItem())
),
);
},
},
{
menuType: "menuitem",
l10nID: `${config.addonRef}-itemmenu-translateAbstract`,
icon: menuIcon,
onCommand: (event, context) => {
if (!context.items?.length) {
return;
}
addon.hooks.onTranslateInBatch(
context.items
.map((item) => addTranslateAbstractTask(item.id, true))
.filter((task) => task) as TranslateTask[],
{ noDisplay: true, noCache: true },
);
},
onShowing: (event, context) => {
context.setVisible(
!!(
getPref("showItemMenuTitleTranslation") &&
context.items?.every((item) => item.isRegularItem())
),
);
},
},
],
});
}
================================================
FILE: src/modules/notify.ts
================================================
export function registerNotify(types: _ZoteroTypes.Notifier.Type[]) {
const callback = {
notify: async (...data: Parameters<_ZoteroTypes.Notifier.Notify>) => {
if (!addon?.data.alive) {
unregisterNotify(notifyID);
return;
}
addon.hooks.onNotify(...data);
},
};
// Register the callback in Zotero as an item observer
const notifyID = Zotero.Notifier.registerObserver(callback, types);
}
function unregisterNotify(notifyID: string) {
Zotero.Notifier.unregisterObserver(notifyID);
}
================================================
FILE: src/modules/popup.ts
================================================
import { SVGIcon } from "../utils/config";
import { config } from "../../package.json";
import { getString } from "../utils/locale";
import { getPref, setPref } from "../utils/prefs";
import { addTranslateTask, getLastTranslateTask } from "../utils/task";
import { slice } from "../utils/str";
export function updateReaderPopup() {
const popup = addon.data.popup.currentPopup;
if (!popup) {
return;
}
const enablePopup = getPref("enablePopup");
const hidePopupTextarea = getPref("enableHidePopupTextarea") as boolean;
Array.from(popup.querySelectorAll(`.${config.addonRef}-readerpopup`)).forEach(
(elem) => ((elem as HTMLElement).hidden = !enablePopup),
);
const idPrefix = popup?.getAttribute(`${config.addonRef}-prefix`);
const makeId = (type: string) => `${idPrefix}-${type}`;
const audiobox = popup?.querySelector(
`#${makeId("audiobox")}`,
) as HTMLDivElement;
const translateButton = popup?.querySelector(
`#${makeId("translate")}`,
) as HTMLDivElement;
const textarea = popup?.querySelector(
`#${makeId("text")}`,
) as HTMLTextAreaElement;
const addToNoteButton = popup?.querySelector(
`#${makeId("addtonote")}`,
) as HTMLDivElement;
const updateHidden = (elem: HTMLElement, hidden: boolean) => {
if (hidden) {
elem.style.display = "none";
} else {
elem.style.removeProperty("display");
}
};
if (!enablePopup) {
updateHidden(audiobox, true);
updateHidden(translateButton, true);
updateHidden(textarea, true);
updateHidden(addToNoteButton, true);
return;
}
const task = getLastTranslateTask({ type: "text" });
if (!task) {
return;
}
popup.setAttribute("translate-task-id", task.id);
if (task.audio.length > 0 && getPref("showPlayBtn")) {
audiobox.innerHTML = "";
updateHidden(audiobox, false);
ztoolkit.UI.appendElement(
{
tag: "fragment",
children: task.audio.map((audioData) => ({
tag: "button",
namespace: "html",
classList: ["toolbar-button", "wide-button"],
attributes: {
tabindex: "-1",
title: audioData.text,
},
properties: {
innerHTML: `🔊 ${audioData.text}`,
onclick: () => {
new (ztoolkit.getGlobal("Audio"))(audioData.url).play();
},
},
styles: { whiteSpace: "nowrap", flexGrow: "1" },
})),
},
audiobox,
);
}
if (task.audio.length > 0 && getPref("showPlayBtn") && getPref("autoPlay")) {
const firstAudio = task.audio[0];
const audio = new (ztoolkit.getGlobal("Audio"))(firstAudio.url);
audio.play();
}
const hideTranslateButton = task.status !== "waiting";
updateHidden(translateButton, hideTranslateButton);
switch (task.langto?.split("-")[0]) {
case "ar":
case "fa":
case "he":
textarea.style.direction = "rtl";
break;
default:
textarea.style.direction = "ltr";
}
textarea.hidden = hidePopupTextarea || !hideTranslateButton;
textarea.value = task.result || task.raw;
textarea.style.fontSize = `${getPref("fontSize")}px`;
textarea.style.lineHeight = `${
Number(getPref("lineHeight")) * Number(getPref("fontSize"))
}px`;
const enableAddToNote = getPref("enableNote") as boolean;
if (
!Zotero.getMainWindow().ZoteroContextPane.activeEditor ||
!enableAddToNote
) {
updateHidden(addToNoteButton, true);
}
updatePopupSize(popup, textarea);
}
export function buildReaderPopup(
event: _ZoteroTypes.Reader.EventParams<"renderTextSelectionPopup">,
) {
const { reader, doc, append } = event;
const annotation = event.params.annotation;
const popup = doc.querySelector(".selection-popup") as HTMLDivElement;
addon.data.popup.currentPopup = popup;
popup.style.maxWidth = "none";
popup.setAttribute(
`${config.addonRef}-prefix`,
`${config.addonRef}-${reader._instanceID}`,
);
const ZoteroContextPane = Zotero.getMainWindow().ZoteroContextPane;
const colors = popup.querySelector(".colors") as HTMLDivElement;
colors.style.width = "100%";
colors.style.justifyContent = "space-evenly";
const keepSize = getPref("keepPopupSize") as boolean;
const makeId = (type: string) =>
`${config.addonRef}-${reader._instanceID}-${type}`;
const hidePopupTextarea = getPref("enableHidePopupTextarea") as boolean;
append(
ztoolkit.UI.createElement(doc, "fragment", {
children: [
{
tag: "div",
id: makeId("audiobox"),
classList: [`${config.addonRef}-readerpopup`],
styles: {
display: "flex",
width: "calc(100% - 4px)",
marginLeft: "2px",
justifyContent: "space-evenly",
},
ignoreIfExists: true,
},
{
tag: "button",
namespace: "html",
id: makeId("translate"),
classList: [
"toolbar-button",
"wide-button",
`${config.addonRef}-readerpopup`,
],
properties: {
innerHTML: `${SVGIcon}${getString("readerpopup-translate-label")}`,
hidden: getPref("enableAuto"),
},
listeners: [
{
type: "click",
listener: (ev: Event) => {
addon.hooks.onTranslate({
noCheckZoteroItemLanguage: true,
noCache: true,
});
const button = ev.target as HTMLDivElement;
button.hidden = true;
(
button.ownerDocument.querySelector(
`#${makeId("text")}`,
) as HTMLTextAreaElement
).hidden = hidePopupTextarea;
},
},
],
ignoreIfExists: true,
},
{
tag: "textarea",
id: makeId("text"),
attributes: {
rows: "3",
columns: "10",
},
classList: [
`${config.addonRef}-popup-textarea`,
`${config.addonRef}-readerpopup`,
],
styles: {
fontSize: `${getPref("fontSize")}px`,
fontFamily: "inherit",
lineHeight: `${
Number(getPref("lineHeight")) * Number(getPref("fontSize"))
}px`,
width: keepSize ? `${getPref("popupWidth")}px` : "-moz-available",
// Minimum width to prevent the textarea from being smaller than the popup
minWidth: "184px",
height: `${Math.max(
keepSize ? Number(getPref("popupHeight")) : 30,
)}px`,
marginInline: "2px",
border: "none",
background: "var(--color-sidepane)",
borderRadius: "6px",
padding: "5px",
},
properties: {
onpointerup: (e: Event) => e.stopPropagation(),
ondragstart: (e: Event) => e.stopPropagation(),
spellcheck: false,
value: addon.data.translate.selectedText,
},
ignoreIfExists: true,
listeners: [
{
type: "mousedown",
listener: (_ev) => {
_ev.target?.addEventListener(
"mousemove",
onTextAreaResize as (ev: Event) => void,
);
},
},
{
type: "mouseup",
listener: (_ev) => {
_ev.target?.removeEventListener(
"mousemove",
onTextAreaResize as (ev: Event) => void,
);
},
},
{
type: "dblclick",
listener: (_ev) => {
const textarea = popup.querySelector(
`#${makeId("text")}`,
) as HTMLTextAreaElement;
textarea.selectionStart = 0;
textarea.selectionEnd = textarea.value.length;
const text = textarea.value.slice(
textarea.selectionStart,
textarea.selectionEnd,
);
new ztoolkit.Clipboard().addText(text, "text/plain").copy();
new ztoolkit.ProgressWindow("Copied to Clipboard")
.createLine({
text: slice(text, 50),
progress: 100,
type: "default",
})
.show();
},
},
],
},
{
tag: "button",
namespace: "html",
id: makeId("addtonote"),
classList: [
"toolbar-button",
"wide-button",
`${config.addonRef}-readerpopup`,
],
styles: {
marginTop: "8px",
},
properties: {
innerHTML: `${SVGIcon}${getString("readerpopup-addToNote-label")}`,
},
ignoreIfExists: true,
listeners: [
{
type: "click",
listener: async (ev) => {
const noteEditor =
ZoteroContextPane && ZoteroContextPane.activeEditor;
if (!noteEditor) {
return;
}
const editorInstance = noteEditor.getCurrentInstance();
if (!editorInstance) {
return;
}
const task = addTranslateTask(
addon.data.translate.selectedText,
reader.itemID,
"addtonote",
);
if (!task) {
return;
}
await addon.hooks.onTranslate(task, {
noCheckZoteroItemLanguage: true,
noDisplay: true,
});
if (task.status !== "success") {
return;
}
const replaceMode = getPref("enableNoteReplaceMode") as boolean;
if (replaceMode) {
annotation.text = task.result;
} else {
annotation.comment = task.result;
}
// @ts-ignore should be fixed in the zotero-types
reader._addToNote([annotation]);
},
},
],
},
],
}),
);
}
function onTextAreaResize(ev: MouseEvent) {
if (getPref("keepPopupSize")) {
const textarea = ev.target as HTMLTextAreaElement;
setPref("popupWidth", textarea.offsetWidth);
setPref("popupHeight", textarea.offsetHeight);
}
}
function getOnTextAreaCopy(selectionMenu: HTMLElement, targetId: string) {
return (ev: KeyboardEvent) => {
const textarea = selectionMenu.querySelector(
`#${targetId}`,
) as HTMLTextAreaElement;
const isMod = ev.ctrlKey || ev.metaKey;
if (ev.key === "c" && isMod) {
ztoolkit.getGlobal("setTimeout")(() => {
new ztoolkit.Clipboard()
.addText(
textarea.value.slice(
textarea.selectionStart,
textarea.selectionEnd,
),
"text/plain",
)
.copy();
}, 10);
ev.stopPropagation();
} else if (ev.key === "a" && isMod) {
textarea.selectionStart = 0;
textarea.selectionEnd = textarea.value.length;
ev.stopPropagation();
} else if (ev.key === "x" && isMod) {
new ztoolkit.Clipboard()
.addText(
textarea.value.slice(textarea.selectionStart, textarea.selectionEnd),
"text/plain",
)
.copy();
textarea.value = `${textarea.value.slice(
0,
textarea.selectionStart,
)}${textarea.value.slice(textarea.selectionEnd)}`;
ev.stopPropagation();
}
};
}
function updatePopupSize(
selectionMenu: HTMLDivElement,
textarea: HTMLTextAreaElement,
resetSize: boolean = true,
): void {
const keepSize = getPref("keepPopupSize") as boolean;
if (keepSize) {
return;
}
if (resetSize) {
textarea.style.width = "-moz-available";
textarea.style.height = "30px";
}
const viewer = selectionMenu.ownerDocument.body;
// Get current H & W
const textHeight = textarea.scrollHeight;
const textWidth = textarea.scrollWidth;
const newWidth = textWidth + 20;
// Check until H/W<0.75 and don't overflow viewer border
if (
textHeight / textWidth > 0.75 &&
selectionMenu.offsetLeft + newWidth < viewer.offsetWidth
) {
// Update width
textarea.style.width = `${newWidth}px`;
updatePopupSize(selectionMenu, textarea, false);
return;
}
// Update height
textarea.style.height = `${textHeight + 3}px`;
}
================================================
FILE: src/modules/preferenceWindow.ts
================================================
import { config, homepage } from "../../package.json";
import { LANG_CODE } from "../utils/config";
import { getString } from "../utils/locale";
import { getPref, setPref } from "../utils/prefs";
import { setServiceSecret, validateServiceSecret } from "../utils/secret";
import { createServiceSettingsDialog } from "../utils";
import { services } from "./services";
export function registerPrefsWindow() {
Zotero.PreferencePanes.register({
pluginID: config.addonID,
src: rootURI + "chrome/content/preferences.xhtml",
label: getString("pref-title"),
image: `chrome://${config.addonRef}/content/icons/favicon.png`,
helpURL: homepage,
});
}
export function registerPrefsScripts(_window: Window) {
// This function is called when the prefs window is opened
addon.data.prefs.window = _window;
buildPrefsPane();
updatePrefsPaneDefault();
}
function buildPrefsPane() {
const doc = addon.data.prefs.window?.document;
if (!doc) {
return;
}
// menus
ztoolkit.UI.replaceElement(
{
tag: "menulist",
id: makeId("sentenceServices"),
attributes: {
value: getPref("translateSource") as string,
native: "true",
},
listeners: [
{
type: "command",
listener: (e: Event) => {
onPrefsEvents("setSentenceService");
},
},
],
children: [
{
tag: "menupopup",
children: services.getAllServicesWithType("sentence").map((s) => ({
tag: "menuitem",
attributes: {
label: services.getServiceNameByID(s.id),
value: s.id,
},
})),
},
],
},
doc.querySelector(`#${makeId("sentenceServices-placeholder")}`)!,
);
ztoolkit.UI.replaceElement(
{
tag: "menulist",
id: makeId("wordServices"),
attributes: {
value: getPref("dictSource") as string,
native: "true",
},
classList: ["use-word-service"],
listeners: [
{
type: "command",
listener: (e: Event) => {
onPrefsEvents("setWordService");
},
},
],
children: [
{
tag: "menupopup",
children: services.getAllServicesWithType("word").map((s) => ({
tag: "menuitem",
attributes: {
label: services.getServiceNameByID(s.id),
value: s.id,
},
})),
},
],
},
doc.querySelector(`#${makeId("wordServices-placeholder")}`)!,
);
ztoolkit.UI.replaceElement(
{
tag: "menulist",
id: makeId("langfrom"),
attributes: {
value: getPref("sourceLanguage") as string,
native: "true",
},
listeners: [
{
type: "command",
listener: (e: Event) => {
onPrefsEvents("setSourceLanguage");
},
},
],
styles: {
maxWidth: "250px",
},
children: [
{
tag: "menupopup",
children: LANG_CODE.map((lang) => ({
tag: "menuitem",
attributes: {
label: lang.name,
value: lang.code,
},
})),
},
],
},
doc.querySelector(`#${makeId("langfrom-placeholder")}`)!,
);
ztoolkit.UI.replaceElement(
{
tag: "menulist",
id: makeId("langto"),
attributes: {
value: getPref("targetLanguage") as string,
native: "true",
},
listeners: [
{
type: "command",
listener: (e: Event) => {
onPrefsEvents("setTargetLanguage");
},
},
],
styles: {
maxWidth: "250px",
},
children: [
{
tag: "menupopup",
children: LANG_CODE.map((lang) => ({
tag: "menuitem",
attributes: {
label: lang.name,
value: lang.code,
},
})),
},
],
},
doc.querySelector(`#${makeId("langto-placeholder")}`)!,
);
doc
.querySelector(`#${makeId("manageKeys")}`)
?.addEventListener("command", (e: Event) => {
onPrefsEvents("manageKeys");
});
doc
.querySelector(`#${makeId("renameServices")}`)
?.addEventListener("command", (e: Event) => {
onPrefsEvents("renameServices");
});
doc
.querySelector(`#${makeId("enableAuto")}`)
?.addEventListener("command", (e: Event) => {
onPrefsEvents("setAutoTranslateSelection");
});
doc
.querySelector(`#${makeId("enableComment")}`)
?.addEventListener("command", (e: Event) => {
onPrefsEvents("setAutoTranslateAnnotation");
});
doc
.querySelector(`#${makeId("enablePopup")}`)
?.addEventListener("command", (e: Event) => {
onPrefsEvents("setEnablePopup");
});
doc
.querySelector(`#${makeId("enableAddToNote")}`)
?.addEventListener("command", (e: Event) => {
onPrefsEvents("setEnableAddToNote");
});
doc
.querySelector(`#${makeId("showPlayBtn")}`)
?.addEventListener("command", (e: Event) => {
onPrefsEvents("setShowPlayBtn");
});
doc
.querySelector(`#${makeId("useWordService")}`)
?.addEventListener("command", (e: Event) => {
onPrefsEvents("setUseWordService");
});
doc
.querySelector(`#${makeId("hideUnconfiguredServices")}`)
?.addEventListener("command", () => {
addon.hooks.onReaderTabPanelRefresh();
});
doc
.querySelector(`#${makeId("sentenceServicesSecret")}`)
?.addEventListener("input", (e: Event) => {
onPrefsEvents("updateSentenceSecret");
});
doc
.querySelector(`#${makeId("wordServicesSecret")}`)
?.addEventListener("input", (e: Event) => {
onPrefsEvents("updateWordSecret");
});
doc
.querySelector(`#${makeId("fontSize")}`)
?.addEventListener("input", (e: Event) => {
onPrefsEvents("updateFontSize");
});
doc
.querySelector(`#${makeId("lineHeight")}`)
?.addEventListener("input", (e: Event) => {
onPrefsEvents("updatelineHeight");
});
doc
.querySelector(`#${makeId("reset-titleTranslation")}`)
?.addEventListener("command", (e: Event) => {
ztoolkit
.getGlobal("ZoteroPane")
.getSelectedItems()
.forEach((item) => {
ztoolkit.ExtraField.setExtraField(item, "titleTranslation", "");
});
});
doc
.querySelector(`#${makeId("reset-abstractTranslation")}`)
?.addEventListener("command", (e: Event) => {
ztoolkit
.getGlobal("ZoteroPane")
.getSelectedItems()
.forEach((item) => {
ztoolkit.ExtraField.setExtraField(item, "abstractTranslation", "");
});
});
doc
.querySelector(`#${makeId("enableAutoTagAnnotation")}`)
?.addEventListener("command", (e: Event) => {
onPrefsEvents("setEnableAutoTagAnnotation");
});
}
function updatePrefsPaneDefault() {
onPrefsEvents("setAutoTranslateAnnotation", false);
onPrefsEvents("setEnablePopup", false);
onPrefsEvents("setShowPlayBtn", false);
onPrefsEvents("setUseWordService", false);
onPrefsEvents("setSentenceSecret", false);
onPrefsEvents("setWordSecret", false);
onPrefsEvents("setEnableAutoTagAnnotation", false);
}
function onPrefsEvents(type: string, fromElement: boolean = true) {
const doc = addon.data.prefs.window?.document;
if (!doc) {
return;
}
const setDisabled = (className: string, disabled: boolean) => {
doc
.querySelectorAll(`.${className}`)
.forEach(
(elem) => ((elem as XUL.Element & XUL.IDisabled).disabled = disabled),
);
};
switch (type) {
case "setAutoTranslateSelection":
addon.hooks.onReaderTabPanelRefresh();
break;
case "setAutoTranslateAnnotation":
{
addon.hooks.onReaderTabPanelRefresh();
}
break;
case "setEnablePopup":
{
const elemValue = fromElement
? (doc.querySelector(`#${makeId("enablePopup")}`) as XUL.Checkbox)
.checked
: (getPref("enablePopup") as boolean);
const hidden = !elemValue;
setDisabled("enable-popup", hidden);
if (!hidden) {
onPrefsEvents("setEnableAddToNote", fromElement);
}
}
break;
case "setEnableAddToNote":
{
const elemValue = fromElement
? (doc.querySelector(`#${makeId("enableAddToNote")}`) as XUL.Checkbox)
.checked
: (getPref("enableNote") as boolean);
const hidden = !elemValue;
setDisabled("enable-popup-addtonote", hidden);
}
break;
case "setShowPlayBtn":
{
const elemValue = fromElement
? (doc.querySelector(`#${makeId("showPlayBtn")}`) as XUL.Checkbox)
.checked
: (getPref("showPlayBtn") as boolean);
const hidden = !elemValue;
setDisabled("show-play-btn", hidden);
}
break;
case "setUseWordService":
{
const elemValue = fromElement
? (doc.querySelector(`#${makeId("useWordService")}`) as XUL.Checkbox)
.checked
: (getPref("enableDict") as boolean);
const hidden = !elemValue;
setDisabled("use-word-service", hidden);
if (!hidden) {
onPrefsEvents("setShowPlayBtn", fromElement);
}
}
break;
case "setEnableAutoTagAnnotation":
{
const elemValue = fromElement
? (
doc.querySelector(
`#${makeId("enableAutoTagAnnotation")}`,
) as XUL.Checkbox
).checked
: (getPref("enableAutoTagAnnotation") as boolean);
const hidden = !elemValue;
setDisabled("enable-auto-tag-annotation", hidden);
}
break;
case "setSentenceService":
{
setPref(
"translateSource",
(
doc.querySelector(`#${makeId("sentenceServices")}`) as XUL.MenuList
).getAttribute("value")!,
);
onPrefsEvents("setSentenceSecret", fromElement);
addon.hooks.onReaderTabPanelRefresh();
}
break;
case "updateSentenceSecret":
{
setServiceSecret(
getPref("translateSource") as string,
(
doc.querySelector(
`#${makeId("sentenceServicesSecret")}`,
) as HTMLInputElement
).value,
);
}
break;
case "setSentenceSecret":
{
const serviceId = getPref("translateSource") as string;
const secretCheckResult = validateServiceSecret(
serviceId,
(validateResult) => {
if (fromElement && !validateResult.status) {
addon.data.prefs.window?.alert(
`You see this because the translation service ${serviceId} requires SECRET, which is NOT correctly set.\n\nDetails:\n${validateResult.info}`,
);
}
},
);
(
doc.querySelector(
`#${makeId("sentenceServicesSecret")}`,
) as HTMLInputElement
).value = secretCheckResult.secret;
// Update secret status button
const statusButton = doc.querySelector(
`#${makeId("sentenceServicesStatus")}`,
) as XUL.Button;
const service =
addon.data.translate.services.getServiceById(serviceId)!;
if (service.config) {
statusButton.hidden = false;
statusButton.label = getString("service-dialog-config");
statusButton.onclick = (ev) => {
createServiceSettingsDialog(service);
};
} else {
statusButton.hidden = true;
}
}
break;
case "setWordService":
{
setPref(
"dictSource",
(
doc.querySelector(`#${makeId("wordServices")}`) as XUL.MenuList
).getAttribute("value")!,
);
onPrefsEvents("setWordSecret", fromElement);
}
break;
case "updateWordSecret":
{
setServiceSecret(
getPref("dictSource") as string,
(
doc.querySelector(
`#${makeId("wordServicesSecret")}`,
) as HTMLInputElement
).value,
);
}
break;
case "setWordSecret":
{
const serviceId = getPref("dictSource") as string;
const secretCheckResult = validateServiceSecret(
serviceId,
(validateResult) => {
if (fromElement && !validateResult.status) {
addon.data.prefs.window?.alert(
`You see this because the translation service ${serviceId} requires SECRET, which is NOT correctly set.\n\nDetails:\n${validateResult.info}`,
);
}
},
);
(
doc.querySelector(
`#${makeId("wordServicesSecret")}`,
) as HTMLInputElement
).value = secretCheckResult.secret;
}
break;
case "setSourceLanguage":
{
setPref(
"sourceLanguage",
(
doc.querySelector(`#${makeId("langfrom")}`) as XUL.MenuList
).getAttribute("value")!,
);
addon.hooks.onReaderTabPanelRefresh();
}
break;
case "setTargetLanguage":
{
setPref(
"targetLanguage",
(
doc.querySelector(`#${makeId("langto")}`) as XUL.MenuList
).getAttribute("value")!,
);
addon.hooks.onReaderTabPanelRefresh();
}
break;
case "updateFontSize":
addon.api.getTemporaryRefreshHandler()();
break;
case "updatelineHeight":
addon.api.getTemporaryRefreshHandler()();
break;
case "manageKeys":
{
import("../modules/settings/manageKeys").then(
({ manageKeysDialog }) => {
manageKeysDialog();
},
);
}
break;
case "renameServices":
{
import("../modules/settings/renameServices").then(
({ renameServicesDialog }) => {
renameServicesDialog();
},
);
}
break;
default:
return;
}
}
function makeId(type: string) {
return `${config.addonRef}-${type}`;
}
================================================
FILE: src/modules/prompt.ts
================================================
import { config } from "../../package.json";
export function registerPrompt() {
ztoolkit.Prompt.register([
{
name: "Translate Sentences",
label: config.addonInstance,
when: () => {
const selection = addon.data.translate.selectedText;
const sl = Zotero.Prefs.get(
"ZoteroPDFTranslate.sourceLanguage",
) as string;
const tl = Zotero.Prefs.get(
"ZoteroPDFTranslate.targetLanguage",
) as string;
return (
selection.length > 0 &&
Zotero?.PDFTranslate &&
sl.startsWith("en") &&
tl.startsWith("zh")
);
},
callback: async (prompt) => {
const selection = addon.data.translate.selectedText;
const queue = Zotero.PDFTranslate.data.translate.queue;
let task = queue.find(
(task: any) => task.raw == selection && task.result.length > 0,
);
task = undefined;
if (!task) {
prompt.showTip("Loading...");
task = await Zotero.PDFTranslate.api.translate(selection);
Zotero.PDFTranslate.data.translate.queue.push(task);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
prompt.exit();
}
prompt.inputNode.placeholder = task.service;
const rawText = task.raw,
resultText = task.result;
const addSentences = (
node: HTMLElement,
text: string,
dividers: string[],
) => {
let i = 0;
const sentences: string[] = [];
let sentence = "";
// https://www.npmjs.com/package/sentence-extractor?activeTab=explore
const abbrs = [
"a.m.",
"p.m.",
"vol.",
"inc.",
"jr.",
"dr.",
"tex.",
"co.",
"prof.",
"rev.",
"revd.",
"hon.",
"v.s.",
"i.e.",
"ie.",
"eg.",
"e.g.",
"al.",
"st.",
"ph.d.",
"capt.",
"mr.",
"mrs.",
"ms.",
"fig.",
];
const getWord = (i: number) => {
const before = text.slice(0, i).match(/[.a-zA-Z]+$/);
const after = text.slice(i + 1).match(/^[.a-zA-Z]+/);
const word = ([before, ["."], after].filter((i) => i) as string[][])
.map((i: string[]) => i[0])
.join("");
return word;
};
const isAbbr = (i: number) => {
const word = getWord(i).toLowerCase().replace(/\s+/g, " ");
return abbrs.find((abbr: string) => {
abbr = abbr.toLowerCase();
return word == abbr;
});
};
const isPotentialAbbr = (i: number) => {
const word = getWord(i);
const parts = word.split(".").filter((i) => i);
return parts.length > 2 && parts.every((part) => part.length <= 2);
};
while (i < text.length) {
const char = text[i];
sentence += char;
if (dividers.indexOf(char) != -1) {
if (char == ".") {
if (
(i + 1 < text.length && text[i + 1] != " ") ||
isAbbr(i) ||
isPotentialAbbr(i)
) {
i += 1;
continue;
}
}
const blank = " ";
i += 1;
while (text[i] == blank) {
sentence += blank;
i += 1;
}
sentences.push(sentence);
sentence = "";
continue;
}
i += 1;
}
for (let i = 0; i < sentences.length; i++) {
const span = ztoolkit.UI.appendElement(
{
tag: "span",
id: `sentence-${i}`,
properties: {
innerText: sentences[i],
},
styles: {
borderRadius: "3px",
},
listeners: [
{
type: "mousemove",
listener: () => {
const highlightColor = "var(--tag-yellow)";
const twinNode = [
...Array.from(
container.querySelectorAll(".text-container"),
),
].find((e) => e != node) as HTMLDivElement;
node
.querySelectorAll("span")
.forEach((e) => (e.style.backgroundColor = ""));
(span as HTMLSpanElement).style.backgroundColor =
highlightColor;
twinNode
?.querySelectorAll("span")
.forEach((e) => (e.style.backgroundColor = ""));
const twinSpan = twinNode.querySelector(
`span[id=sentence-${i}]`,
) as HTMLSpanElement;
twinSpan.style.backgroundColor = highlightColor;
const twinNodeContainer =
twinNode.parentNode as HTMLDivElement;
const nodeContainer = node.parentNode as HTMLDivElement;
if (
direction == "column" &&
twinNode.classList.contains("result")
) {
twinNodeContainer.scrollTo(
0,
twinSpan.offsetTop -
twinNodeContainer.offsetHeight * 0.5 -
nodeContainer.offsetHeight,
);
} else {
twinNodeContainer.scrollTo(
0,
twinSpan.offsetTop -
twinNodeContainer.offsetHeight * 0.5,
);
}
},
},
],
},
node,
);
}
};
const container = prompt.createCommandsContainer() as HTMLDivElement;
// TODO: prefs: direction
const directions = ["row", "column"];
const direction = directions[1];
container.setAttribute(
"style",
`
display: flex;
flex-direction: ${direction};
padding: .5em 1em;
margin-left: 0px;
width: 100%;
height: 25em;
`,
);
const subContainers: HTMLDivElement[] = [];
const doc = Zotero.getMainWindow().document;
[
["raw", rawText, [".", "?", "!"]],
["result", resultText, ["?", "!", "!", "。", "?"]],
].forEach((args: any[]) => {
const [className, text, dividers] = args;
const subContainer = ztoolkit.UI.createElement(doc, "div", {
styles: {
padding: ".5em",
border: "1px solid var(--color-border)",
overflowY: "auto",
minWidth: "10em",
minHeight: "5em",
height: "100%",
width: "100%",
textAlign: "justify",
},
children: [
{
tag: "div",
classList: [className, "text-container"],
styles: {
fontSize: "1em",
lineHeight: "1.5em",
marginBottom: ".5em",
},
},
],
});
addSentences(
subContainer.querySelector(".text-container")!,
text,
dividers,
);
subContainers.push(subContainer);
});
const size = 5;
const resizer = ztoolkit.UI.createElement(doc, "div", {
styles: {
height: direction == "row" ? "100%" : `${size}px`,
width: direction == "column" ? "100%" : `${size}px`,
backgroundColor: "var(--color-border)",
cursor: direction == "column" ? "ns-resize" : "ew-resize",
},
});
let y = 0,
x = 0;
let h = 0,
w = 0;
const rect = container.getBoundingClientRect();
const H = rect.height;
const W = rect.width;
const mouseDownHandler = function (e: MouseEvent) {
// hide
subContainers.forEach((div) => {
div
.querySelectorAll("span")
.forEach((e: HTMLSpanElement) => (e.style.display = "none"));
});
y = e.clientY;
x = e.clientX;
const rect = subContainers[1].getBoundingClientRect();
h = rect.height;
w = rect.width;
doc.addEventListener("mousemove", mouseMoveHandler);
doc.addEventListener("mouseup", mouseUpHandler);
};
const mouseMoveHandler = function (e: MouseEvent) {
const dy = e.clientY - y;
const dx = e.clientX - x;
if (direction == "column") {
subContainers[1].style.height = `${h - dy}px`;
subContainers[0].style.height = `${H - (h - dy) - size}px`;
}
if (direction == "row") {
subContainers[1].style.width = `${w - dx}px`;
subContainers[0].style.width = `${W - (w - dx) - size}px`;
}
};
const mouseUpHandler = function () {
// show
subContainers.forEach((div) => {
div
.querySelectorAll("span")
.forEach((e: HTMLSpanElement) => (e.style.display = ""));
});
doc.removeEventListener("mousemove", mouseMoveHandler);
doc.removeEventListener("mouseup", mouseUpHandler);
};
resizer.addEventListener("mousedown", mouseDownHandler);
container.append(subContainers[0], resizer, subContainers[1]);
},
},
]);
}
================================================
FILE: src/modules/reader.ts
================================================
import { config } from "../../package.json";
import { SVGIcon } from "../utils/config";
import { addTranslateAnnotationTask } from "../utils/task";
import { getString } from "../utils/locale";
export function registerReaderInitializer() {
Zotero.Reader.registerEventListener(
"renderTextSelectionPopup",
(event) => {
const { reader, doc, params, append } = event;
addon.data.translate.selectedText = params.annotation.text.trim();
addon.hooks.onReaderPopupShow(event);
},
config.addonID,
);
Zotero.Reader.registerEventListener(
"renderSidebarAnnotationHeader",
(event) => {
const { reader, doc, params, append } = event;
const annotationData = params.annotation;
// TEMP: If not many annotations, create the button immediately
if (reader._item.numAnnotations() < 1000) {
append(createTranslateAnnotationButton(doc, reader, annotationData));
return;
}
// TEMP: Use error event to delay the button creation to avoid blocking the main thread
const placeholder = doc.createElement("img");
placeholder.src = "chrome://zotero/error.png";
placeholder.dataset.annotationId = annotationData.id;
placeholder.dataset.libraryId = reader._item.libraryID.toString();
placeholder.addEventListener("error", (event) => {
const placeholder = event.currentTarget as HTMLElement;
placeholder.ownerGlobal?.requestIdleCallback(() => {
const annotationID = placeholder.dataset.annotationId;
const libraryID = parseInt(placeholder.dataset.libraryId || "");
const button = doc.createElement("div");
button.classList.add("icon");
button.innerHTML = SVGIcon;
button.title = getString("sideBarIcon-title");
button.addEventListener("click", (e) => {
const task = addTranslateAnnotationTask(libraryID, annotationID!);
addon.hooks.onTranslate(task, {
noCheckZoteroItemLanguage: true,
noDisplay: true,
});
e.preventDefault();
});
button.addEventListener("mouseover", (e) => {
(e.target as HTMLElement).style.backgroundColor =
"var(--color-sidepane)";
});
button.addEventListener("mouseout", (e) => {
(e.target as HTMLElement).style.removeProperty("background-color");
});
placeholder.replaceWith(button);
});
});
append(placeholder);
},
config.addonID,
);
}
function createTranslateAnnotationButton(
doc: Document,
reader: _ZoteroTypes.ReaderInstance,
annotationData: any,
): HTMLElement {
return ztoolkit.UI.createElement(doc, "div", {
classList: ["icon"],
properties: {
innerHTML: SVGIcon,
title: getString("sideBarIcon-title"),
},
listeners: [
{
type: "click",
listener: (e) => {
const task = addTranslateAnnotationTask(
reader._item.libraryID,
annotationData.id,
);
addon.hooks.onTranslate(task, {
noCheckZoteroItemLanguage: true,
noDisplay: true,
});
e.preventDefault();
},
},
{
type: "mouseover",
listener: (e) => {
(e.target as HTMLElement).style.backgroundColor =
"var(--color-sidepane)";
},
},
{
type: "mouseout",
listener: (e) => {
(e.target as HTMLElement).style.removeProperty("background-color");
},
},
],
enableElementRecord: false,
ignoreIfExists: true,
});
}
================================================
FILE: src/modules/services/_template.ts
================================================
/**
* Example Translation Service Template
*
* This file is a template for adding a new translation service.
* Follow the instructions below to create your own service.
*
* === How to use this template ===
*
* 1. **Copy this file** to `src/services/.ts`
* - The filename should match your `id` field (e.g. `google-translate.ts` for id `"google-translate"`).
*
* 2. **Fill in the required fields:**
* - `id` (string, required): A unique identifier for your service.
* Use lowercase letters and `-` only (e.g. `"google-translate"`).
* - `type` (required): `"word"` or `"sentence"`.
* Choose `"word"` for dictionary-like results, `"sentence"` for full-text translations.
* - `translate` (required): The function that sends the request to your translation API
* and writes the result into `data.result`.
*
* 3. **Optional fields:**
* - `name` (string): The display name of your service.
* Defaults to `getString("service-${id}")` if omitted.
* - `helpUrl` (string): A link to your service's documentation.
* If provided, a "Help" button will appear in the settings panel to open this URL.
* - `defaultSecret` (string): A placeholder API key or credentials format.
* Only set if your service requires authentication.
* - `secretValidator(secret)`: Function to validate the secret format and provide hints.
* - `config(settings)`: Function to add extra user-configurable settings (e.g. endpoint, model).
* Omit if no additional settings are required.
* - `requireExternalConfig`: Indicate whether the service requires external configuration (e.g. Pull Docker images or install softwares) and whether a 📍 label is added after the service name.
* Omit if no external configuration is required.
*
* 4. **If your service requires an API key (secret):**
* - Uncomment `defaultSecret` and `secretValidator` in the example below.
* - The `secretValidator` should return a `SecretValidateResult` object describing:
* - The parsed secret value
* - Whether it is valid
* - Any hints or errors for the user
*
* 5. **If your service has custom settings:**
* - Implement `config(settings)` using the methods from `AllowedSettingsMethods`.
* - These methods let you add input fields, checkboxes, selects, etc., in the settings dialog.
* - Example:
* ```ts
* config(settings) {
* settings
* .addTextSetting({ prefKey: "endpoint", nameKey: "service-myapi-endpoint" })
* .addSelectSetting({
* prefKey: "model",
* nameKey: "service-myapi-model",
* options: [
* { label: "Model A", value: "a" },
* { label: "Model B", value: "b" }
* ]
* });
* }
* ```
*
* 6. **If your service requires external configuration:**
* - Uncomment `requireExternalConfig` in the example below.
*
* 7. **Register your service:**
* - Open `services/index.ts` and add your new service object to the `register` array.
*
* 8. **Test your service** in the UI to ensure:
* - The settings panel works as expected
* - Secrets are validated correctly
* - Translation requests succeed and results are displayed
*/
import { getPref } from "../../utils";
import { TranslateService } from "./base";
export const ExampleTranslationService: TranslateService = {
id: "example",
type: "sentence",
helpUrl: "https://example.com/",
// === Optional: API key / secret support ===
// Uncomment if your service requires a secret
/*
defaultSecret: "accessKeyId#accessKeySecret",
secretValidator(secret) {
const parts = secret?.split("#");
const flag = parts.length === 2;
const partsInfo = `AccessKeyId: ${parts[0]}\nAccessKeySecret: ${parts[1]}`;
return {
secret,
status: flag && secret !== ExampleTranslationService.defaultSecret,
info:
secret === ExampleTranslationService.defaultSecret
? "The secret is not set."
: flag
? partsInfo
: `The secret must have 2 parts joined by '#', but got ${parts?.length}.\n${partsInfo}`,
};
},
*/
// === REQUIRED: translation function ===
async translate(data) {
// Get saved settings
const option1 = getPref("options1");
// Send request to translation API
const xhr = await Zotero.HTTP.request("POST", "https://example.com/api/", {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: "",
responseType: "json",
});
// Handle HTTP errors
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
// Handle API errors
if (xhr.response.Code !== "200") {
throw `Service error: ${xhr.response.Code}:${xhr.response.Message}`;
}
// Save the translation result
data.result = xhr.response;
},
// === Optional: custom settings in preferences ===
// Uncomment if your service requires extra settings
/*
config(settings) {
settings.addTextSetting({
prefKey: "example",
nameKey: "example",
});
},
*/
// === Optional: 📍 label in service name ===
// Uncomment if your service requires external configuration
/*
* requireExternalConfig: true;
*/
};
================================================
FILE: src/modules/services/aliyun.ts
================================================
import { TranslateService } from "./base";
import { getPref } from "../../utils/prefs";
import { base64, hmacSha1Digest, randomString } from "../../utils/crypto";
const translate: TranslateService["translate"] = async (data) => {
const params = data.secret.split("#");
const accessKeyId = params[0];
const accessKeySecret = params[1];
const endpoint = params[2] || "https://mt.aliyuncs.com/";
const action = (getPref("aliyun.action") as string) || "TranslateGeneral";
const scene = (getPref("aliyun.scene") as string) || "general";
const encodedBody = `AccessKeyId=${accessKeyId}&Action=${action}&Format=JSON&FormatType=text&Scene=${scene}&SignatureMethod=HMAC-SHA1&SignatureNonce=${encodeURIComponent(
randomString(12),
)}&SignatureVersion=1.0&SourceLanguage=auto&SourceText=${encodeRFC3986URIComponent(
data.raw,
)}&TargetLanguage=${languageCode(data.langto)}&Timestamp=${encodeURIComponent(
new Date().toISOString(),
)}&Version=2018-10-12`;
const stringToSign = `POST&%2F&${encodeURIComponent(encodedBody)}`;
const signature = base64(
await hmacSha1Digest(stringToSign, `${accessKeySecret}&`),
);
const xhr = await Zotero.HTTP.request("POST", endpoint, {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: `${encodedBody}&Signature=${encodeURIComponent(signature)}`,
responseType: "json",
});
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
if (xhr.response.Code !== "200") {
throw `Service error: ${xhr.response.Code}:${xhr.response.Message}`;
}
data.result = xhr.response.Data.Translated;
};
function languageCode(str: string) {
str = str.toLowerCase();
if (str === "zh-tw" || str === "zh-hk" || str === "zh-mo") {
return "zh-tw";
}
return str.split("-")[0];
}
function encodeRFC3986URIComponent(str: string) {
return encodeURIComponent(str).replace(
/[!'()*]/g,
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
);
}
export const Aliyun: TranslateService = {
id: "aliyun",
type: "sentence",
helpUrl:
"https://help.aliyun.com/zh/machine-translation/developer-reference/api-overview-1",
defaultSecret: "accessKeyId#accessKeySecret",
secretValidator(secret) {
const parts = secret?.split("#");
const flag = parts.length === 2;
const partsInfo = `AccessKeyId: ${parts[0]}\nAccessKeySecret: ${parts[1]}`;
return {
secret,
status: flag && secret !== Aliyun.defaultSecret,
info:
secret === Aliyun.defaultSecret
? "The secret is not set."
: flag
? partsInfo
: `The secret must have 2 parts joined by '#', but got ${parts?.length}.\n${partsInfo}`,
};
},
translate,
config(settings) {
settings
.addTextSetting({
prefKey: "aliyun.action",
nameKey: "service-aliyun-dialog-action",
})
.addTextSetting({
prefKey: "aliyun.scene",
nameKey: "service-aliyun-dialog-scene",
});
},
};
================================================
FILE: src/modules/services/baidu.ts
================================================
import { TranslateService } from "./base";
const translate: TranslateService["translate"] = async (data) => {
const params = data.secret.split("#");
const appid = params[0];
const key = params[1];
let action = "0";
if (params.length >= 3) {
action = params[2];
}
const salt = new Date().getTime();
const sign = Zotero.Utilities.Internal.md5(
appid + data.raw + salt + key,
false,
);
// Request
const xhr = await Zotero.HTTP.request(
"GET",
`http://api.fanyi.baidu.com/api/trans/vip/translate?q=${encodeURIComponent(
data.raw,
)}&appid=${appid}&from=${data.langfrom.split("-")[0]}&to=${
data.langto.split("-")[0]
}&salt=${salt}&sign=${sign}&action=${action}&needIntervene=1`,
{
responseType: "json",
},
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
// Parse
if (xhr.response.error_code) {
throw `Service error: ${xhr.response.error_code}:${xhr.response.error_msg}`;
}
let tgt = "";
for (let i = 0; i < xhr.response.trans_result.length; i++) {
tgt += xhr.response.trans_result[i].dst;
}
data.result = tgt;
};
export const Baidu: TranslateService = {
id: "baidu",
type: "sentence",
defaultSecret: "appid#key",
secretValidator(secret: string) {
const parts = secret?.split("#");
const flag = [2, 3].includes(parts.length);
const partsInfo = `AppID: ${parts[0]}\nKey: ${parts[1]}\nAction: ${
parts[2] ? parts[2] : "0"
}`;
return {
secret,
status: flag && secret !== Baidu.defaultSecret,
info:
secret === Baidu.defaultSecret
? "The secret is not set."
: flag
? partsInfo
: `The secret format of Baidu Text Translation is AppID#Key#Action(optional). The secret must have 2 or 3 parts joined by '#', but got ${parts?.length}.\n${partsInfo}`,
};
},
translate,
};
================================================
FILE: src/modules/services/baidufield.ts
================================================
import { TranslateService } from "./base";
const translate: TranslateService["translate"] = async (data) => {
const params = data.secret.split("#");
const appid = params[0];
const key = params[1];
const domain = params[2];
const salt = new Date().getTime();
const sign = Zotero.Utilities.Internal.md5(
appid + data.raw + salt + domain + key,
false,
);
const xhr = await Zotero.HTTP.request(
"GET",
`http://api.fanyi.baidu.com/api/trans/vip/fieldtranslate?q=${encodeURIComponent(
data.raw,
)}&appid=${appid}&from=${data.langfrom.split("-")[0]}&to=${
data.langto.split("-")[0]
}&domain=${domain}&salt=${salt}&sign=${sign}`,
{
responseType: "json",
},
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
// Parse
if (xhr.response.error_code) {
throw `Service error: ${xhr.response.error_code}:${xhr.response.error_msg}`;
}
let tgt = "";
for (let i = 0; i < xhr.response.trans_result.length; i++) {
tgt += xhr.response.trans_result[i].dst;
}
data.result = tgt;
};
export const BaiduField: TranslateService = {
id: "baidufield",
type: "sentence",
defaultSecret: "appid#key#field",
secretValidator(secret: string) {
const parts = secret?.split("#");
const flag = parts.length === 3;
const partsInfo = `AppID: ${parts[0]}\nKey: ${parts[1]}\nDomainCode: ${parts[2]}`;
return {
secret,
status: flag && secret !== BaiduField.defaultSecret,
info:
secret === BaiduField.defaultSecret
? "The secret is not set."
: flag
? partsInfo
: `The secret format of Baidu Domain Text Translation is AppID#Key#DomainCode. The secret must have 3 parts joined by '#', but got ${parts?.length}.\n${partsInfo}`,
};
},
translate,
};
================================================
FILE: src/modules/services/base.ts
================================================
import {
SecretValidateResult,
AllowedSettingsMethods,
TranslateTaskProcessor,
} from "../../utils";
export interface TranslateService {
/**
* The unique service ID.
*
* Use lowercase letters + hyphens only.
*/
id: string;
/**
* The display name of the service.
*
* @default getString(`service-${id}`)
*/
name?: string;
/**
* The type of translation service.
*
*/
type: "word" | "sentence";
/**
* Documentation or help page URL.
*
* If provided, a "Help" button will appear in the settings dialog.
*/
helpUrl?: string;
defaultSecret?: string;
secretValidator?: (secret: string) => SecretValidateResult;
/**
* Main translation function.
*
* - Must set `data.result` before returning.
* - Should throw an error if the request fails.
*/
translate: TranslateTaskProcessor;
/**
* Optional configuration UI builder.
*
* - Receives an {@link AllowedSettingsMethods}` instance with safe UI-building methods.
* - Use to add extra settings like endpoint, model selection, checkboxes, etc.
* - Omit if no extra configuration is needed.
*/
config?: (settings: AllowedSettingsMethods) => void;
/**
* Set this to true if the service requires external configuration (e.g. Pull Docker images or install softwares).
*
* - The services will be grouped as `Require Config`📍.
* - The label📍will be automatically added to the service name in `addon/locale/${lang}/addon.ftl`.
* - Omit if no external configuration is required.
*/
requireExternalConfig?: boolean;
}
================================================
FILE: src/modules/services/bing.ts
================================================
import { getPrefJSON, setPref } from "../../utils/prefs";
import { TranslateService } from "./base";
const translate: TranslateService["translate"] = async (data) => {
const xhr = await Zotero.HTTP.request(
"POST",
`https://api-edge.cognitive.microsofttranslator.com/translate?from=${data.langfrom}&to=${data.langto}&api-version=3.0&includeSentenceLength=true`,
{
headers: {
accept: "*/*",
"accept-language":
"zh-TW,zh;q=0.9,ja;q=0.8,zh-CN;q=0.7,en-US;q=0.6,en;q=0.5",
authorization: `Bearer ${await getToken()}`,
"cache-control": "no-cache",
"content-type": "application/json",
pragma: "no-cache",
"sec-ch-ua":
'"Microsoft Edge";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "cross-site",
Referer: "https://appsumo.com/",
"Referrer-Policy": "strict-origin-when-cross-origin",
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42",
},
body: JSON.stringify([{ text: data.raw }]),
responseType: "json",
},
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
try {
data.result = xhr.response[0].translations[0].text;
} catch {
throw `Service error: ${xhr.response}`;
}
};
const bingTokenKey = "bingToken";
const tokenExpTime = 5 * 60 * 1000; // 5 minutes refresh token
async function getToken(forceRefresh: boolean = false) {
let token = "";
// Just in case the update fails
let doRefresh = true;
try {
const tokenObj = getPrefJSON(bingTokenKey);
if (
!forceRefresh &&
tokenObj &&
tokenObj.token &&
new Date().getTime() < tokenObj.exp
) {
token = tokenObj.token;
doRefresh = false;
}
} catch (e) {
ztoolkit.log(e);
}
if (doRefresh) {
const xhr = await Zotero.HTTP.request(
"GET",
"https://edge.microsoft.com/translate/auth",
{
headers: {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42",
},
responseType: "text",
},
);
if (xhr && xhr.response) {
token = xhr.response;
setPref(
bingTokenKey,
JSON.stringify({
exp: new Date().getTime() + tokenExpTime,
token: token,
}),
);
}
}
return token;
}
export const Bing: TranslateService = {
id: "bing",
type: "sentence",
translate,
};
================================================
FILE: src/modules/services/bingdict.ts
================================================
import { TranslateService } from "./base";
const translate: TranslateService["translate"] = async function (data) {
const xhr = await Zotero.HTTP.request(
"GET",
`https://cn.bing.com/dict/search?q=${encodeURIComponent(data.raw)}/`,
{ responseType: "text" },
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
let res = xhr.response;
const doc = new DOMParser().parseFromString(res, "text/html");
const mp3s = Array.from(
doc.querySelectorAll(".hd_area .bigaud"),
) as Element[];
const phoneticText = doc.querySelectorAll(".hd_area .b_primtxt");
data.audio = mp3s.map((a: Element, i: number) => ({
text: phoneticText[i].innerHTML.replace(" ", " "),
url: "https://cn.bing.com" + (a.getAttribute("data-mp3link") ?? ""),
}));
try {
res = res.match(//gm)[0];
} catch (e) {
throw "Parse error";
}
let tgt = "";
for (const line of res.split(",").slice(3)) {
if (line.indexOf("网络释义") > -1) {
tgt += line.slice(0, line.lastIndexOf(";"));
} else {
tgt += line + "\n";
}
}
tgt = tgt.replace(/" \/>/g, "");
data.result = tgt;
};
export const BingDict: TranslateService = {
id: "bingdict",
type: "word",
translate,
};
================================================
FILE: src/modules/services/caiyun.ts
================================================
import { TranslateService } from "./base";
const translate: TranslateService["translate"] = async function (data) {
const param = `${transLang(data.langfrom)}2${transLang(data.langto)}`;
const xhr = await Zotero.HTTP.request(
"POST",
"http://api.interpreter.caiyunai.com/v1/translator",
{
headers: {
"content-type": "application/json",
"x-authorization": `token ${data.secret}`,
},
body: JSON.stringify({
source: [data.raw],
trans_type: param,
request_id: new Date().valueOf() / 10000,
detect: true,
}),
responseType: "json",
},
);
function transLang(inlang: string = "") {
const traditionalChinese = ["zh-HK", "zh-MO", "zh-TW"];
if (traditionalChinese.includes(inlang)) {
return "zh-Hant";
} else {
return inlang.split("-")[0];
}
}
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
data.result = xhr.response.target[0];
};
export const Caiyun: TranslateService = {
id: "caiyun",
type: "sentence",
defaultSecret: "3975l6lr5pcbvidl6jl2",
secretValidator(secret: string) {
const flag = secret.length > 0;
return {
secret,
status: flag && secret !== Caiyun.defaultSecret,
info:
secret === Caiyun.defaultSecret
? "The default secret is for testing only. You should set your own custom token for production."
: flag
? ""
: "The secret is not set.",
};
},
translate,
};
================================================
FILE: src/modules/services/cambridgedict.ts
================================================
import { TranslateService } from "./base";
const cambridgeLangCode = [
{ name: "arabic", code: "ar", parser: parser1 },
{ name: "bengali", code: "bn", parser: parser1 },
{ name: "catalan", code: "ca", parser: parser1 },
{ name: "chinese-simplified", code: "zh", parser: parser1 },
{ name: "chinese-traditional", code: "zht", parser: parser1 },
{ name: "english", code: "en", parser: parser1 },
{ name: "gujarati", code: "gu", parser: parser1 },
{ name: "hindi", code: "hi", parser: parser1 },
{ name: "italian", code: "it", parser: parser1 },
{ name: "japanese", code: "ja", parser: parser1 },
{ name: "korean", code: "ko", parser: parser1 },
{ name: "marathi", code: "mr", parser: parser1 },
{ name: "polish", code: "pl", parser: parser1 },
{ name: "portuguese", code: "pt", parser: parser1 },
{ name: "russian", code: "ru", parser: parser1 },
{ name: "spanish", code: "es", parser: parser1 },
{ name: "tamil", code: "ta", parser: parser1 },
{ name: "telugu", code: "te", parser: parser1 },
{ name: "turkish", code: "tr", parser: parser1 },
{ name: "urdu", code: "ur", parser: parser1 },
{ name: "french", code: "fr", parser: parser2 },
{ name: "german", code: "de", parser: parser2 },
{ name: "dutch", code: "nl", parser: parser2 },
{ name: "indonesian", code: "id", parser: parser2 },
{ name: "norwegian", code: "no", parser: parser2 },
{ name: "swedish", code: "sv", parser: parser2 },
{ name: "czech", code: "cs", parser: parser2 },
{ name: "danish", code: "da", parser: parser2 },
{ name: "malaysian", code: "ms", parser: parser2 },
{ name: "thai", code: "th", parser: parser2 },
{ name: "ukrainian", code: "uk", parser: parser2 },
{ name: "vietnamese", code: "vi", parser: parser2 },
];
const dictCode = cambridgeLangCode.reduce(
(acc, cur) => {
acc[`en-${cur.code}`] = `english-${cur.name}`;
return acc;
},
{} as Record,
);
const parsers = cambridgeLangCode.reduce(
(acc, cur) => {
acc[`en-${cur.code}`] = cur.parser;
return acc;
},
{} as Record,
);
const translate: TranslateService["translate"] = async function (data) {
const { dict, parser } = getDictionaryCode(data.langfrom, data.langto);
if (dict === "unsupported" || !parser)
throw `Language Error: unsupported dictionary ${dict}`;
const xhr = await Zotero.HTTP.request(
"GET",
`https://dictionary.cambridge.org/dictionary/${dict}/${encodeURIComponent(data.raw)}`,
{
responseType: "text",
},
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
const res = xhr.response;
const doc = new DOMParser().parseFromString(res, "text/html");
const { result, audioList } = parser(doc);
if (!result) {
throw "Parse Error";
}
data.result = result;
data.audio = audioList;
};
function getDictionaryCode(fromCode: string, toCode: string) {
fromCode = fromCode.split("-")[0].toLowerCase();
toCode = toCode.toLowerCase();
if (toCode.includes("zh")) {
toCode = ["zh", "zh-cn", "zh-sg"].includes(toCode) ? "zh" : "zht";
}
toCode = toCode.split("-")[0];
const code = `${fromCode}-${toCode}`;
let dict = "";
let parser = null;
if (fromCode === "en") {
dict = dictCode[code] ?? "unsupported";
parser = parsers[code] ?? null;
} else {
// TODO: should implement other languages
dict = "unsupported";
}
return { dict, parser };
}
function parser1(doc: Document) {
const audioList: Array<{ text: string; url: string }> = [];
const urls: Array = [];
const contents: Array = [];
doc.querySelectorAll(".entry-body__el").forEach((block: Element) => {
contents.push(block.querySelector(".posgram")?.textContent ?? "");
let prons: string = "";
block
.querySelectorAll('.pos-header span[class*="dpron-"]')
.forEach((value: Element) => {
const pron = value.querySelector(".dpron")?.textContent ?? "";
const pronText = `${value.querySelector(".region")?.textContent ?? ""} ${pron} `;
const url = value.querySelector("source")?.getAttribute("src");
if (pron) prons += pronText;
if (url && !urls.includes(url)) {
const audio = {
text: pronText,
url: "https://dictionary.cambridge.org" + url,
};
audioList.push(audio);
urls.push(url);
}
});
contents.push(prons);
contents.push(parseBody(block));
});
const result = contents.filter((content) => content !== "").join("\n");
return { result, audioList };
}
function parser2(doc: Document) {
const audioList: Array<{ text: string; url: string }> = [];
const contents: Array = [];
doc.querySelectorAll(".link").forEach((block: Element) => {
contents.push(block.querySelector(".dpos")?.textContent ?? "");
contents.push(block.querySelector(".dpos-h .pron")?.textContent ?? "");
contents.push(parseBody(block));
});
const result = contents.filter((content) => content !== "").join("\n");
return { result, audioList };
}
function parseBody(block: Element): string {
const body: Array = [];
block.querySelectorAll(".dsense").forEach((value: Element, i: number) => {
const guideword =
value.querySelector(".guideword")?.textContent?.replace(/\s+/g, " ") ??
"";
const defEn = value.querySelector(".def")?.textContent ?? "";
const def = value.querySelector(".trans[lang]")?.textContent?.trim() ?? "";
body.push(`\t${i + 1}.${guideword} ${defEn}\n\t\t${def}`);
});
return body.join("\n");
}
export const CambridgeDict: TranslateService = {
id: "cambridgedict",
type: "word",
translate,
};
================================================
FILE: src/modules/services/claude.ts
================================================
import { getPref, getString, transformPromptWithContext } from "../../utils";
import { TranslateService } from "./base";
import type { TranslateTask } from "../../utils/task";
function transformContent(
langFrom: string,
langTo: string,
sourceText: string,
data: Required,
) {
return transformPromptWithContext(
"claude.prompt",
langFrom,
langTo,
sourceText,
data,
);
}
// Removed duplicate implementation in favor of the main claude function
const translate = async function (data) {
const apiURL = getPref("claude.endPoint") as string;
const model = getPref("claude.model") as string;
const temperature = parseFloat(getPref("claude.temperature") as string);
const stream = getPref("claude.stream") as boolean;
const maxTokens = parseInt(getPref("claude.maxTokens") as string) || 4000;
const refreshHandler = addon.api.getTemporaryRefreshHandler({ task: data });
// Pass maxTokens to the request body
const requestBody = {
model: model,
messages: [
{
role: "user",
content: transformContent(data.langfrom, data.langto, data.raw, data),
},
],
temperature: temperature,
stream: stream,
max_tokens: maxTokens,
};
const headers = {
"Content-Type": "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": data.secret,
};
const xhr = await Zotero.HTTP.request("POST", apiURL, {
headers: headers,
body: JSON.stringify(requestBody),
responseType: "text",
requestObserver: (xmlhttp: XMLHttpRequest) => {
if (stream) {
let preLength = 0;
let result = "";
let buffer = ""; // Buffer to handle partial JSON chunks
xmlhttp.onprogress = (e: any) => {
try {
// Get only the new data since last progress event
const newResponse = e.target.response.slice(preLength);
preLength = e.target.response.length;
// Add to our working buffer
buffer += newResponse;
// Process complete data: chunks by splitting on newlines
const lines = buffer.split("\n");
// Keep the last line in the buffer as it might be incomplete
buffer = lines.pop() || "";
for (const line of lines) {
if (!line.trim()) continue; // Skip empty lines
// Remove the "data: " prefix if present
const dataLine = line.startsWith("data: ") ? line.slice(6) : line;
if (dataLine.trim() === "[DONE]") continue;
try {
const obj = JSON.parse(dataLine);
if (obj.type === "content_block_delta") {
result += obj.delta?.text || "";
} else if (
obj.type === "content_block_start" ||
obj.type === "content_block_stop"
) {
// Handle other event types if needed
continue;
}
} catch (parseError) {
// Skip invalid JSON - might be a partial chunk
continue;
}
}
// Clear timeouts caused by stream transfers
if (e.target.timeout) {
e.target.timeout = 0;
}
// Update the result
data.result = result.replace(/^\n\n/, "");
// Refresh UI to show progress
refreshHandler();
} catch (error) {
console.error("Error processing Claude stream:", error);
}
};
// Also handle the load event to ensure we get the complete text
xmlhttp.onload = () => {
data.status = "success";
// Refresh UI once more to ensure we display the final result
refreshHandler();
};
} else {
// Non-streaming logic
xmlhttp.onload = () => {
try {
const responseObj = JSON.parse(xmlhttp.responseText);
const resultContent = responseObj.content[0].text;
data.result = resultContent.replace(/^\n\n/, "");
} catch (error) {
data.result = getString("status-translating");
data.status = "fail";
throw `Failed to parse response: ${error}`;
}
// Trigger UI updates after receiving the full response
refreshHandler();
};
}
},
});
if (xhr?.status !== 200) {
data.result = `Request error: ${xhr?.status}`;
data.status = "fail";
throw `Request error: ${xhr?.status}`;
}
data.status = "success";
return;
};
export const Claude: TranslateService = {
id: "claude",
type: "sentence",
helpUrl:
"https://docs.anthropic.com/claude/docs/getting-started-with-the-claude-api",
defaultSecret: "",
secretValidator(secret: string) {
const status = /^sk-ant-[A-Za-z0-9]{24,}$/.test(secret);
const empty = secret.length === 0;
return {
secret,
status: status || Boolean(secret),
info: empty
? "The secret is not set."
: status
? "Click the button to check connectivity."
: "The Claude API key format might be invalid. Typically starts with 'sk-ant-'.",
};
},
translate,
config(settings) {
settings
.addTextSetting({
prefKey: "claude.endPoint",
nameKey: "service-claude-dialog-endPoint",
})
.addTextSetting({
prefKey: "claude.model",
nameKey: "service-claude-dialog-model",
})
.addNumberSetting({
prefKey: "claude.temperature",
nameKey: "service-claude-dialog-temperature",
min: 0,
max: 1,
step: 0.1,
})
.addNumberSetting({
prefKey: "claude.maxTokens",
nameKey: "service-claude-dialog-maxTokens",
inputType: "number",
min: 100,
max: 10000,
step: 100,
})
.addTextAreaSetting({
prefKey: "claude.prompt",
nameKey: "service-claude-dialog-prompt",
})
.addCheckboxSetting({
prefKey: "claude.stream",
nameKey: "service-claude-dialog-stream",
});
},
};
================================================
FILE: src/modules/services/cnki.ts
================================================
import { aesEcbEncrypt, base64 } from "../../utils/crypto";
import { getPref, getPrefJSON, setPref } from "../../utils/prefs";
import { TranslateService } from "./base";
const translate = async function (data) {
let progressWindow;
const useSplit = getPref("cnkiUseSplit") as boolean;
const splitSecond = getPref("cnkiSplitSecond") as number;
if (!data.silent) {
progressWindow = new ztoolkit.ProgressWindow("PDF Translate");
}
const processTranslation = async (text: string) => {
const xhr = await Zotero.HTTP.request(
"POST",
"https://dict.cnki.net/fyzs-front-api/translate/literaltranslation",
{
headers: {
"Content-Type": "application/json;charset=UTF-8",
Token: await getToken(),
},
body: JSON.stringify({
words: await getWord(text),
translateType: null,
}),
responseType: "json",
},
);
if (xhr.response.data?.isInputVerificationCode) {
throw "Your access is temporarily banned by the CNKI service. Please goto https://dict.cnki.net/, translate manually and pass human verification.";
}
let tgt = xhr.response.data?.mResult;
tgt = tgt.replace(new RegExp(getPref("cnkiRegex") as string, "g"), "");
return tgt;
};
if (useSplit) {
const sentences = data.raw
.split(/[.?!]/)
.map((s) => s.trim())
.filter((s) => s.length > 0);
const chunks = [];
let currentChunk = "";
sentences.forEach((sentence: string) => {
const sentenceWithPeriod = sentence + ". ";
if (currentChunk.length + sentenceWithPeriod.length > 800) {
chunks.push(currentChunk);
currentChunk = sentenceWithPeriod;
} else {
currentChunk += sentenceWithPeriod;
}
});
if (currentChunk) {
chunks.push(currentChunk);
}
let translatedText = "";
for (const chunk of chunks) {
translatedText += (await processTranslation(chunk)) + " ";
data.result = translatedText.trim();
addon.api.getTemporaryRefreshHandler({ task: data })();
await new Promise((resolve) => setTimeout(resolve, splitSecond * 1000));
}
// data.result = translatedText.trim();
} else {
if (data.raw.length > 800) {
progressWindow
?.createLine({
text: `Maximum text length is 800, ${data.raw.length} selected. Will only translate first 800 characters. If you want the plugin to automatically split the translation based on punctuation, you can enable the split switch in the preferences.`,
})
.show();
data.raw = data.raw.slice(0, 800);
}
data.result = await processTranslation(data.raw);
}
};
export async function getToken(forceRefresh: boolean = false) {
let token = "";
// Just in case the update fails
let doRefresh = true;
try {
const tokenObj = getPrefJSON("cnkiToken");
if (
!forceRefresh &&
tokenObj?.token &&
new Date().getTime() - tokenObj.t < 300 * 1000
) {
token = tokenObj.token;
doRefresh = false;
}
} catch (e) {
ztoolkit.log(e);
}
if (doRefresh) {
const xhr = await Zotero.HTTP.request(
"GET",
"https://dict.cnki.net/fyzs-front-api/getToken",
{
responseType: "json",
},
);
if (xhr && xhr.response && xhr.response.code === 200) {
token = xhr.response.token;
setPref(
"cnkiToken",
JSON.stringify({
t: new Date().getTime(),
token: xhr.response.data,
}),
);
}
}
return token;
}
export async function getWord(text: string) {
const encrypted = await aesEcbEncrypt(text, "4e87183cfd3a45fe");
const base64str = base64(encrypted.buffer);
return base64str.replace(/\//g, "_").replace(/\+/g, "-");
}
export const Cnki: TranslateService = {
id: "cnki",
type: "sentence",
translate,
config(settings) {
settings
.addTextSetting({
prefKey: "cnkiRegex",
nameKey: "service-cnki-dialog-regex",
})
.addCheckboxSetting({
prefKey: "cnkiUseSplit",
nameKey: "service-cnki-dialog-split",
});
},
};
================================================
FILE: src/modules/services/collinsdict.ts
================================================
import { TranslateService } from "./base";
const translate: TranslateService["translate"] = async function (data) {
const xhr = await Zotero.HTTP.request(
"GET",
"https://www.collinsdictionary.com/zh/dictionary/english-chinese/" +
encodeURIComponent(data.raw),
{ responseType: "text" },
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
if (xhr.responseURL.includes("?q=")) {
throw "No result found error";
}
const doc = new DOMParser().parseFromString(xhr.response, "text/html");
Array.prototype.forEach.call(doc.querySelectorAll("script"), (e) =>
e.remove(),
);
const phoneticElements = Array.from(
doc.querySelectorAll(".type-"),
) as HTMLElement[];
data.audio = phoneticElements.map((e) => ({
text: e.innerText.trim(),
url: e.querySelector("a")?.getAttribute("data-src-mp3") || "",
}));
// script in innerText
const explanationText: string = Array.prototype.map
.call(doc.querySelectorAll(".hom"), (e: HTMLSpanElement) =>
e.innerText.replace(/ /g, " ").replace(/[0-9]\./g, "\n$&"),
)
.join("");
data.result = explanationText;
};
export const CollinsDict: TranslateService = {
id: "collinsdict",
type: "word",
translate,
};
================================================
FILE: src/modules/services/deepl.ts
================================================
import { version } from "../../../package.json";
import { TranslateService } from "./base";
type ID = "deeplfree" | "deeplpro";
function createDeepl(id: ID): TranslateService {
return {
id,
type: "sentence",
defaultSecret: "",
secretValidator(secret: string) {
const flag = secret?.length >= 36;
return {
secret,
status: flag,
info: flag
? ""
: `The secret is your DeepL KEY. The secret length must >= 36, but got ${secret?.length}.`,
};
},
async translate(data) {
let url: string;
if (id === "deeplfree") {
url = "https://api-free.deepl.com/v2/translate";
} else {
// See https://github.com/windingwind/zotero-pdf-translate/issues/579
url = data.secret.endsWith("dp")
? "https://api.deepl-pro.com/v2/translate"
: "https://api.deepl.com/v2/translate";
}
const [key, glossary_id]: string[] = data.secret.split("#");
const xhr = await Zotero.HTTP.request("POST", url, {
headers: {
"Content-Type": "application/json",
Authorization: `DeepL-Auth-Key ${key}`,
"User-Agent": `Translate for Zotero/${Zotero.version}-${Zotero.platform}-${version}`,
},
responseType: "json",
body: JSON.stringify({
text: [data.raw],
source_lang: mapLang(data.langfrom),
target_lang: mapLang(data.langto),
glossary_id: glossary_id,
}),
});
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
data.result = xhr.response.translations[0].text;
},
};
}
function mapLang(lang: string) {
if (lang in LANG_MAP) {
return LANG_MAP[lang];
}
return lang.split("-")[0].toUpperCase();
}
const LANG_MAP = {
"pt-BR": "PT-BR",
"pt-PT": "PT-PT",
"zh-CN": "ZH-HANS",
"zh-HK": "ZH-HANT",
"zh-MO": "ZH-HANT",
"zh-SG": "ZH-HANS",
"zh-TW": "ZH-HANT",
} as Record;
export const DeeplFree = createDeepl("deeplfree");
export const DeeplPro = createDeepl("deeplpro");
================================================
FILE: src/modules/services/deeplcustom.ts
================================================
import { getPref } from "../../utils/prefs";
import { TranslateService } from "./base";
const translate = async function (data) {
const url = getPref("deeplcustom.endpoint") as string;
const reqBody = JSON.stringify({
text: data.raw,
source_lang: data.langfrom.split("-")[0].toUpperCase(),
target_lang: data.langto.split("-")[0].toUpperCase(),
});
const xhr = await Zotero.HTTP.request("POST", url, {
headers: {
"Content-Type": "application/json; charset=utf-8",
},
responseType: "json",
body: reqBody,
});
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
data.result = xhr.response.data;
};
export const DeepLCustom: TranslateService = {
id: "deeplcustom",
type: "sentence",
helpUrl:
"https://github.com/ramonmi/DeepLX-for-Zotero/blob/main/README_zh.md",
translate,
config(settings) {
settings.addTextSetting({
prefKey: "deeplcustom.endpoint",
nameKey: "service-deeplcustom-dialog-endPoint",
});
},
requireExternalConfig: true,
};
================================================
FILE: src/modules/services/deeplx.ts
================================================
import { getPref } from "../../utils/prefs";
import { TranslateService } from "./base";
const translate = async function (data) {
const id = 1000 * (Math.floor(Math.random() * 99999) + 8300000) + 1;
const url =
(getPref("deeplx.endpoint") as string) || "https://www2.deepl.com/jsonrpc";
const t = data.raw;
const ICounts = (t.match(/i/g) || []).length + 1;
const ts = Date.now();
let reqBody = JSON.stringify({
jsonrpc: "2.0",
method: "LMT_handle_texts",
id: id,
params: {
texts: [
{
text: t,
requestAlternatives: 3,
},
],
splitting: "newlines",
lang: {
source_lang_user_selected: mapLang(data.langfrom),
target_lang: mapLang(data.langto),
},
timestamp: ts - (ts % ICounts) + ICounts,
commonJobParams: {
wasSpoken: false,
transcribe_as: "",
},
},
});
if ((id + 5) % 29 == 0 || (id + 3) % 13 == 0) {
reqBody = reqBody.replace('"method":"', '"method" : "');
} else {
reqBody = reqBody.replace('"method":"', '"method": "');
}
const xhr = await Zotero.HTTP.request(
"POST",
`${url}?client=chrome-extension,1.28.0&method=LMT_handle_jobs`,
{
headers: {
Accept: "*/*",
Authorization: "None",
"Cache-Control": "no-cache",
"Accept-Language":
"en-US,en;q=0.9,zh-CN;q=0.8,zh-TW;q=0.7,zh-HK;q=0.6,zh;q=0.5",
"Content-Type": "application/json",
DNT: "1",
Origin: "chrome-extension://cofdbpoegempjloogbagkncekinflcnj",
Pragma: "no-cache",
Priority: "u=1, i",
Referer: "https://www.deepl.com/",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "none",
"Sec-GPC": "1",
"User-Agent":
"DeepLBrowserExtension/1.28.0 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
},
responseType: "json",
body: reqBody,
},
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
data.result = xhr.response.result.texts[0].text;
};
// Inherited from src/modules/services/deepl.ts
function mapLang(lang: string) {
if (lang in LANG_MAP) {
return LANG_MAP[lang];
}
return lang.split("-")[0].toUpperCase();
}
const LANG_MAP = {
"pt-BR": "PT-BR",
"pt-PT": "PT-PT",
"zh-CN": "ZH-HANS",
"zh-HK": "ZH-HANT",
"zh-MO": "ZH-HANT",
"zh-SG": "ZH-HANS",
"zh-TW": "ZH-HANT",
} as Record;
export const DeepLX: TranslateService = {
id: "deeplx",
type: "sentence",
translate,
config(setting) {
setting.addTextSetting({
prefKey: "deeplx.endpoint",
nameKey: "service-deeplx-dialog-endPoint",
});
},
};
================================================
FILE: src/modules/services/freedictionaryapi.ts
================================================
import { TranslateService } from "./base";
const translate = async function (data) {
const xhr = await Zotero.HTTP.request(
"GET",
`https://api.dictionaryapi.dev/api/v2/entries/en/${data.raw}`,
{
headers: {
Accept: "application/json",
},
responseType: "json",
},
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
const res = xhr.response[0];
let tgt = "";
if (res.phonetics) {
tgt += res.phonetics.map((p: any) => p.text).join(",");
tgt += "\n";
}
if (res.meanings) {
tgt += res.meanings
.map(
(m: any) =>
`[${m.partOfSpeech}] ${m.definitions
.map(
(d: any) =>
`${d.definition}\n${
d.example ? `\t[example] ${d.example}` : ""
}`,
)
.join("")}`,
)
.join("----\n");
}
data.result = tgt;
};
export const FreeDictionaryAPI: TranslateService = {
id: "freedictionaryapi",
type: "word",
translate,
};
================================================
FILE: src/modules/services/gemini.ts
================================================
import { getPref, transformPromptWithContext } from "../../utils";
import { TranslateService } from "./base";
import type { TranslateTask } from "../../utils/task";
const translate = async function (data) {
const apiURL = getPref("gemini.endPoint") as string;
function transformContent(
langFrom: string,
langTo: string,
sourceText: string,
) {
return transformPromptWithContext(
"gemini.prompt",
langFrom,
langTo,
sourceText,
data,
);
}
function getGenContentAPI(data: Required) {
const stream = getPref("gemini.stream") as boolean;
if (stream) {
return apiURL + `:streamGenerateContent?alt=sse&key=${data.secret}`;
} else {
return apiURL + `:generateContent?key=${data.secret}`;
}
}
const refreshHandler = addon.api.getTemporaryRefreshHandler({ task: data });
const xhr = await Zotero.HTTP.request("POST", getGenContentAPI(data), {
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
contents: [
{
parts: [
{
text: transformContent(data.langfrom, data.langto, data.raw),
},
],
},
],
}),
responseType: "text",
requestObserver: (xmlhttp: XMLHttpRequest) => {
let preLength = 0;
let result = "";
xmlhttp.onprogress = (e: any) => {
// Only concatenate the new strings
const newResponse = e.target.response.slice(preLength);
const dataArray = newResponse.split("data: ");
for (const data of dataArray) {
if (data) {
result +=
JSON.parse(data).candidates[0].content.parts[0].text || "";
}
}
// Clear timeouts caused by stream transfers
if (e.target.timeout) {
e.target.timeout = 0;
}
data.result = result;
preLength = e.target.response.length;
refreshHandler();
};
},
});
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
// data.result = xhr.response.choices[0].message.content.substr(2);
};
export const Gemini: TranslateService = {
id: "gemini",
type: "sentence",
helpUrl: "https://ai.google.dev/gemini-api/docs",
defaultSecret: "",
secretValidator(secret: string) {
const flag = Boolean(secret);
return {
secret,
status: flag,
info: flag ? "" : "The secret is not set.",
};
},
translate,
config(settings) {
settings
.addTextSetting({
prefKey: "gemini.endPoint",
nameKey: "service-gemini-dialog-endPoint",
})
.addTextAreaSetting({
prefKey: "gemini.prompt",
nameKey: "service-gemini-dialog-prompt",
})
.addCheckboxSetting({
prefKey: "gemini.stream",
nameKey: "service-gemini-dialog-stream",
});
},
};
================================================
FILE: src/modules/services/google.ts
================================================
import { TranslateTask } from "../../utils/task";
import { TranslateService } from "./base";
async function _google(url: string, data: Required) {
function TL(a: any) {
const k = "";
const b = 406644;
const b1 = 3293161072;
const jd = ".";
const $b = "+-a^+6";
const Zb = "+-3^+b+-f";
let e, f, g;
// disable the eslint, as the code is copied from google translate
/* eslint-disable */
for (e = [], f = 0, g = 0; g < a.length; g++) {
let m = a.charCodeAt(g);
128 > m
? (e[f++] = m)
: (2048 > m
? (e[f++] = (m >> 6) | 192)
: (55296 == (m & 64512) &&
g + 1 < a.length &&
56320 == (a.charCodeAt(g + 1) & 64512)
? ((m =
65536 + ((m & 1023) << 10) + (a.charCodeAt(++g) & 1023)),
(e[f++] = (m >> 18) | 240),
(e[f++] = ((m >> 12) & 63) | 128))
: (e[f++] = (m >> 12) | 224),
(e[f++] = ((m >> 6) & 63) | 128)),
(e[f++] = (m & 63) | 128));
}
a = b;
for (f = 0; f < e.length; f++) ((a += e[f]), (a = RL(a, $b)));
a = RL(a, Zb);
a ^= b1 || 0;
0 > a && (a = (a & 2147483647) + 2147483648);
a %= 1e6;
/* eslint-enable */
return a.toString() + jd + (a ^ b);
}
function RL(a: any, b: any) {
const t = "a";
const Yb = "+";
let d;
for (let c = 0; c < b.length - 2; c += 3) {
d = b.charAt(c + 2);
d = d >= t ? d.charCodeAt(0) - 87 : Number(d);
d = b.charAt(c + 1) == Yb ? a >>> d : a << d;
a = b.charAt(c) == Yb ? (a + d) & 4294967295 : a ^ d;
}
return a;
}
const langfrom = LANG_MAP[data.langfrom] || data.langfrom;
const langto = LANG_MAP[data.langto] || data.langto;
const param = `sl=${langfrom}&tl=${langto}`;
const xhr = await Zotero.HTTP.request(
"GET",
`${
data.secret ? data.secret : url
}/translate_a/single?client=gtx&${param}&hl=en&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&source=bh&ssel=0&tsel=0&kc=1&tk=${TL(
data.raw,
)}&q=${encodeURIComponent(data.raw)}`,
{ responseType: "json" },
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
let tgt = "";
for (let i = 0; i < xhr.response[0].length; i++) {
if (!xhr.response[0][i]) {
continue;
}
if (xhr.response[0][i] && xhr.response[0][i][0]) {
tgt += xhr.response[0][i][0];
}
}
data.result = tgt;
}
const LANG_MAP = {
// https://github.com/windingwind/zotero-pdf-translate/issues/997
"pt-BR": "pt",
} as Record;
type ID = "google" | "googleapi";
export function createGoogle(id: ID): TranslateService {
return {
id,
type: "sentence",
async translate(data) {
if (id === "google") {
return await _google("https://translate.google.com", data);
}
if (id === "googleapi") {
return await _google("https://translate.googleapis.com", data);
}
},
};
}
export const Google = createGoogle("google");
export const GoogleAPI = createGoogle("googleapi");
================================================
FILE: src/modules/services/gpt.ts
================================================
import { getPref, getString, transformPromptWithContext } from "../../utils";
import { TranslateService } from "./base";
type ID = "chatgpt" | "customgpt1" | "customgpt2" | "customgpt3" | "azuregpt";
function getCustomParams(prefix: string): Record {
const storedCustomParams =
(getPref(`${prefix}.customParams`) as string) || "{}";
try {
const customParams = JSON.parse(storedCustomParams);
// Filter out parameters that are already defined (for both Chat Completions and Responses API)
const standardParams = [
"model",
"messages",
"input",
"temperature",
"stream",
];
return Object.fromEntries(
Object.entries(customParams).filter(
([key]) => !standardParams.includes(key),
),
);
} catch (e) {
return {};
}
}
interface ParsedResponse {
content: string;
finished: boolean;
}
/**
* Detect if the endpoint URL is for OpenAI Responses API
*/
function isResponsesApiEndpoint(url: string): boolean {
return url.endsWith("/responses") || url.includes("/responses?");
}
/**
* Parse streaming response for OpenAI Responses API
* Event format: { "type": "response.output_text.delta", "delta": "text", ... }
*/
function parseResponsesApiStreamResponse(obj: any): ParsedResponse {
const eventType = obj.type || "";
// Text delta event - this is the main event for streaming text
// Format: { "type": "response.output_text.delta", "delta": "In", ... }
if (eventType === "response.output_text.delta") {
return {
content: obj.delta || "",
finished: false,
};
}
// Completion events
if (
eventType === "response.completed" ||
eventType === "response.done" ||
eventType === "response.failed" ||
eventType === "response.incomplete"
) {
return {
content: "",
finished: true,
};
}
// Other events we don't need to extract content from:
// response.created, response.in_progress, response.output_item.added,
// response.content_part.added, response.output_text.done, etc.
return { content: "", finished: false };
}
/**
* Parse non-streaming response for OpenAI Responses API
* Response format: { output: [{ type: "message", content: [{ type: "output_text", text: "..." }] }] }
*/
function parseResponsesApiNonStreamResponse(obj: any): string {
if (obj.output && Array.isArray(obj.output)) {
for (const item of obj.output) {
if (item.type === "message" && item.content) {
for (const content of item.content) {
if (content.type === "output_text") {
return content.text || "";
}
}
}
}
}
return "";
}
function parseStreamResponse(obj: any): ParsedResponse {
// Handle OpenAI format (choices array with delta)
if (obj.choices && obj.choices[0]) {
const choice = obj.choices[0];
return {
content: choice.delta?.content || "",
finished:
choice.finish_reason !== undefined && choice.finish_reason !== null,
};
}
// Handle Ollama native format (direct message)
else if (obj.message) {
return {
content: obj.message.content || "",
finished: obj.done === true,
};
}
return { content: "", finished: false };
}
function parseNonStreamResponse(obj: any): string {
// Handle OpenAI format (choices array)
if (obj.choices && obj.choices[0]) {
return obj.choices[0].message.content || "";
}
// Handle Ollama native format (direct message)
else if (obj.message && obj.message.content) {
return obj.message.content;
}
return "";
}
const gptTranslate = async function (
apiURL: string,
model: string,
temperature: number,
prefix: string,
data: Parameters[0],
stream?: boolean,
) {
function transformContent(
langFrom: string,
langTo: string,
sourceText: string,
) {
return transformPromptWithContext(
`${prefix}.prompt`,
langFrom,
langTo,
sourceText,
data,
);
}
const streamMode = stream ?? true;
const useResponsesApi = isResponsesApiEndpoint(apiURL);
const refreshHandler = addon.api.getTemporaryRefreshHandler({ task: data });
//It takes some time to translate, so set the text to "Translating" before the request
if (streamMode === false) {
data.result = getString("status-translating");
refreshHandler();
}
/**
* The requestObserver callback, under streaming mode
* @param xmlhttp
*/
const streamCallback = (xmlhttp: XMLHttpRequest) => {
let preLength = 0;
let result = "";
let buffer = ""; // Buffer to store incomplete JSON fragments
xmlhttp.onprogress = (e: any) => {
// Only concatenate the new strings
const newResponse = e.target.response.slice(preLength);
// Handle both OpenAI SSE format and Ollama native streaming
let dataArray;
const hasSseData = /(^|\n)data:/.test(newResponse);
if (hasSseData) {
// OpenAI SSE format
// Prepend buffer from previous incomplete chunk
const fullResponse = buffer + newResponse;
if (useResponsesApi) {
// Responses API has "event:" lines, need line-by-line parsing
dataArray = fullResponse
.split("\n")
.filter((line: string) => line.startsWith("data:"))
.map((line: string) => line.slice(5).trimStart());
} else {
// Chat Completions format: simple split works
dataArray = fullResponse.split("data:");
}
buffer = ""; // Reset buffer
} else {
// Ollama native format - each line is a JSON object
const fullResponse = buffer + newResponse;
dataArray = fullResponse
.split("\n")
.filter((line: string) => line.trim());
buffer = ""; // Reset buffer
}
for (let i = 0; i < dataArray.length; i++) {
const data = dataArray[i];
if (!data.trim()) continue;
try {
const obj = JSON.parse(data);
const { content, finished } = useResponsesApi
? parseResponsesApiStreamResponse(obj)
: parseStreamResponse(obj);
result += content;
if (finished) {
break;
}
} catch {
// If parsing fails and this is the last item, it might be incomplete
// Save it to buffer for next iteration
// https://github.com/windingwind/zotero-pdf-translate/issues/1304
if (i === dataArray.length - 1) {
buffer = hasSseData ? "data:" + data : data;
}
continue;
}
}
// Clear timeouts caused by stream transfers
if (e.target.timeout) {
e.target.timeout = 0;
}
// Remove \n\n from the beginning of the data
data.result = result.replace(/^\n\n/, "");
preLength = e.target.response.length;
refreshHandler();
};
};
/**
* The requestObserver callback, under non-streaming mode
* @param xmlhttp
*/
const nonStreamCallback = (xmlhttp: XMLHttpRequest) => {
// Non-streaming logic: Handle the complete response at once
xmlhttp.onload = () => {
// console.debug("GPT response received");
try {
const responseObj = JSON.parse(xmlhttp.responseText);
const resultContent = useResponsesApi
? parseResponsesApiNonStreamResponse(responseObj)
: parseNonStreamResponse(responseObj);
data.result = resultContent.replace(/^\n\n/, "");
} catch (error) {
// throw `Failed to parse response: ${error}`;
return;
}
// Trigger UI updates after receiving the full response
refreshHandler();
};
};
// Build request body based on API type
const requestBody = useResponsesApi
? {
model: model,
input: transformContent(data.langfrom, data.langto, data.raw),
temperature: temperature,
stream: streamMode,
...getCustomParams(prefix),
}
: {
model: model,
messages: [
{
role: "user",
content: transformContent(data.langfrom, data.langto, data.raw),
},
],
temperature: temperature,
stream: streamMode,
...getCustomParams(prefix),
};
const xhr = await Zotero.HTTP.request("POST", apiURL, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${data.secret}`,
"api-key": data.secret,
},
body: JSON.stringify(requestBody),
responseType: "text",
requestObserver: (xmlhttp: XMLHttpRequest) => {
if (streamMode) {
streamCallback(xmlhttp);
} else {
nonStreamCallback(xmlhttp);
}
},
});
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
// data.result = xhr.response.choices[0].message.content.substr(2);
};
function createGPTService(id: ID): TranslateService {
const checkSecret = id === "azuregpt" || id === "chatgpt";
// For compatibility reasons, in older versions, the preference key was `chatGPT`, rather than matching the ID.
// Additionally, customGPT was not initialized in prefs.js.
const prefPrefix = id.replace("gpt", "GPT") as
| "chatGPT"
// | "customGPT1"
// | "customGPT2"
// | "customGPT3"
| "azureGPT";
return {
id,
type: "sentence",
helpUrl:
id === "azuregpt"
? "https://learn.microsoft.com/en-us/azure/ai-foundry/openai/reference#chat-completions"
: "https://gist.github.com/GrayXu/f1b72353b4b0493d51d47f0f7498b67b",
...(checkSecret && {
defaultSecret: "",
secretValidator(secret: string) {
if (id === "chatgpt") {
const status = /^sk-[A-Za-z0-9_-]{32,}$/.test(secret);
const empty = secret.length === 0;
return {
secret,
status,
info: empty
? "The secret is not set."
: status
? "Click the button to check connectivity."
: "The secret key format is invalid.",
};
}
if (id === "azuregpt") {
const flag = Boolean(secret);
return {
secret,
status: flag,
info: flag ? "" : "The secret is not set.",
};
}
const status = secret.length > 0;
return {
secret,
status,
info: status
? "Click the button to check connectivity."
: "The secret key format is invalid.",
};
},
}),
async translate(data) {
switch (id) {
case "azuregpt": {
const endPoint = getPref("azureGPT.endPoint") as string;
const apiVersion = getPref("azureGPT.apiVersion");
const model = getPref("azureGPT.model") as string;
const temperature = parseFloat(
getPref("azureGPT.temperature") as string,
);
const stream = getPref("azureGPT.stream") as boolean;
const apiURL = new URL(endPoint);
apiURL.pathname = `/openai/deployments/${model}/chat/completions`;
apiURL.search = `api-version=${apiVersion}`;
return await gptTranslate(
apiURL.href,
model,
temperature,
"azureGPT",
data,
stream,
);
}
case "chatgpt":
case "customgpt1":
case "customgpt2":
case "customgpt3": {
const apiURL = getPref(`${prefPrefix}.endPoint`) as string;
const model = getPref(`${prefPrefix}.model`) as string;
const temperature = parseFloat(
getPref(`${prefPrefix}.temperature`) as string,
);
const stream = getPref(`${prefPrefix}.stream`) as boolean;
return await gptTranslate(
apiURL,
model,
temperature,
prefPrefix,
data,
stream,
);
}
default:
break;
}
},
config(settings) {
const servicePrefix = id === "azuregpt" ? "azuregpt" : "chatgpt";
settings
.addTextSetting({
prefKey: `${prefPrefix}.endPoint`,
nameKey: `service-${servicePrefix}-dialog-endPoint`,
})
.addTextSetting({
prefKey: `${prefPrefix}.model`,
nameKey: `service-${servicePrefix}-dialog-model`,
})
.addNumberSetting({
prefKey: `${prefPrefix}.temperature`,
nameKey: `service-${servicePrefix}-dialog-temperature`,
min: 0,
max: 2,
step: 0.1,
});
if (
id === "azuregpt" &&
prefPrefix === "azureGPT" &&
servicePrefix === "azuregpt"
) {
settings.addTextSetting({
prefKey: `${prefPrefix}.apiVersion`,
nameKey: `service-${servicePrefix}-dialog-apiVersion`,
hidden: id !== "azuregpt",
});
}
settings
.addTextAreaSetting({
prefKey: `${prefPrefix}.prompt`,
nameKey: `service-${servicePrefix}-dialog-prompt`,
placeholder: getString(`service-${servicePrefix}-dialog-prompt`),
})
.addCheckboxSetting({
prefKey: `${prefPrefix}.stream`,
nameKey: `service-${servicePrefix}-dialog-stream`,
})
.addCustomParamsSetting({
prefKey: `${prefPrefix}.customParams`,
nameKey: `service-${servicePrefix}-dialog-custom-request`,
desc: getString(
`service-${servicePrefix}-dialog-custom-request-description`,
),
});
},
};
}
export const ChatGPT = createGPTService("chatgpt");
export const customGPT1 = createGPTService("customgpt1");
export const customGPT2 = createGPTService("customgpt2");
export const customGPT3 = createGPTService("customgpt3");
export const azureGPT = createGPTService("azuregpt");
================================================
FILE: src/modules/services/haici.ts
================================================
import { getPrefJSON, setPref } from "../../utils/prefs";
import { TranslateService } from "./base";
const translate = async function (data) {
const xhr = await Zotero.HTTP.request(
"GET",
`http://api.microsofttranslator.com/V2/Ajax.svc/TranslateArray?appId=${await getAppId()}&from=${
data.langfrom
}&to=${data.langto}&texts=["${encodeURIComponent(
data.raw.replace(/"/g, '\\"'),
)}"]`,
{ responseType: "json" },
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
try {
let tgt = "";
xhr.response.forEach((line: { TranslatedText: string }) => {
tgt += line.TranslatedText;
});
data.result = tgt;
} catch {
throw `Service error: ${xhr.response}`;
}
};
async function getAppId(forceRefresh: boolean = false) {
let appId = "";
// Just in case the update fails
let doRefresh = true;
try {
const appIdObj = getPrefJSON("haiciAppId");
if (
!forceRefresh &&
appIdObj &&
appIdObj.appId &&
new Date().getTime() - appIdObj.t < 60 * 60 * 1000
) {
appId = appIdObj.appId;
doRefresh = false;
}
} catch (e) {
ztoolkit.log(e);
}
if (doRefresh) {
const xhr = await Zotero.HTTP.request(
"GET",
"http://capi.dict.cn/fanyi.php",
{
headers: {
Referer: "http://fanyi.dict.cn/",
},
responseType: "text",
},
);
if (xhr && xhr.response) {
appId = xhr.response.match(/"(.+)"/)[1];
setPref(
"haiciAppId",
JSON.stringify({
t: new Date().getTime(),
appId: appId,
}),
);
}
}
return appId;
}
export const Haici: TranslateService = {
id: "haici",
type: "sentence",
translate,
};
================================================
FILE: src/modules/services/haicidict.ts
================================================
import { TranslateService } from "./base";
const translate = async function (data) {
const xhr = await Zotero.HTTP.request("GET", `https://dict.cn/${data.raw}`, {
responseType: "text",
});
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
const res = xhr.response as string;
try {
const doc = new DOMParser().parseFromString(res, "text/html");
const audioList: Array<{ text: string; url: string }> = [];
for (const span of Array.from(
doc.querySelectorAll("div.phonetic > span"),
) as Array) {
const text = span.innerText.replace(/\s+/g, " ").trim();
for (const item of Array.from(
span.querySelectorAll("i"),
) as Array) {
audioList.push({
text: `${text} ${item.title}`,
url: `https://audio.dict.cn/${item.getAttribute("naudio")}`,
});
}
}
data.audio = audioList;
const items = (
Array.from(
doc.querySelectorAll("ul.dict-basic-ul > li"),
) as Array
)
.filter((item) => !item.querySelector("script"))
.map((item) => item.innerText.replace(/\s+/g, " ").trim())
.filter((item) => Boolean(item));
data.result = `${items.join("\n")}\n`;
} catch (e) {
throw "Parse error";
}
};
export const HaiciDict: TranslateService = {
id: "haicidict",
type: "word",
translate,
};
================================================
FILE: src/modules/services/huoshan.ts
================================================
import { hex, hmacSha256Digest, sha256Digest } from "../../utils/crypto";
import { TranslateService } from "./base";
const translate = async function (data) {
const params = data.secret.split("#");
const id: string = params[0];
const key: string = params[1];
function getDateTimeNow() {
const now = new Date();
return now.toISOString().replace(/[:-]|\.\d{3}/g, "");
}
async function getSigningKey(sk: any, metaData: any) {
const kDate = await hmacSha256Digest(metaData.date, sk);
const kRegion = await hmacSha256Digest(metaData.region, kDate);
const kService = await hmacSha256Digest(metaData.service, kRegion);
return await hmacSha256Digest("request", kService);
}
function getStringHeaders(header: any) {
let str = "";
const keys = Object.keys(header).sort();
keys.forEach((key) => {
str += `${key.toLocaleLowerCase()}:${header[key]}\n`;
});
return str;
}
function getSignedHeaders(header: any) {
const keys = Object.keys(header).sort();
const headerList = keys.map((v) => v.toLocaleLowerCase());
return headerList.join(";");
}
const ak = id;
const sk = key;
const currTime = getDateTimeNow();
const requestObj = {
method: "POST",
url: "/",
param: "Action=TranslateText&Version=2020-06-01",
service: "translate",
region: "cn-north-1",
version: "2020-06-01",
date: currTime,
algorithm: "HMAC-SHA256",
};
const requestBody = {
TargetLanguage: "zh",
TextList: [data.raw],
};
const XContentSha256 = hex(await sha256Digest(JSON.stringify(requestBody)));
const header: any = {
"Content-Type": "application/json",
"X-Date": currTime,
"X-Content-Sha256": XContentSha256,
};
const canonicalRequest = [
requestObj.method,
requestObj.url,
requestObj.param,
getStringHeaders(header),
getSignedHeaders(header),
header["X-Content-Sha256"],
].join("\n");
const hashCanonicalRequest = hex(await sha256Digest(canonicalRequest));
const signingStr = [
requestObj.algorithm,
currTime,
`${currTime}/${requestObj.region}/${requestObj.service}/request`,
hashCanonicalRequest,
].join("\n");
const signingKey = await getSigningKey(sk, requestObj);
const sign = hex(await hmacSha256Digest(signingStr, signingKey));
const authorization = [
`${requestObj.algorithm} Credential=${ak}/${currTime}/${requestObj.region}/${requestObj.service}/request`,
"SignedHeaders=" + getSignedHeaders(header),
`Signature=${sign}`,
].join(", ");
header["Authorization"] = authorization;
const xhr = await Zotero.HTTP.request(
"POST",
"http://translate.volcengineapi.com/?Action=TranslateText&Version=2020-06-01",
{
headers: header,
body: JSON.stringify(requestBody),
},
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
const { TranslationList } = JSON.parse(xhr.response);
data.result = TranslationList[0].Translation;
};
export const Huoshan: TranslateService = {
id: "huoshan",
type: "sentence",
defaultSecret: "accessKeyId#accessKeySecret",
secretValidator(secret: string) {
const parts = secret?.split("#");
const flag = parts.length === 2;
const partsInfo = `AccessKeyId: ${parts[0]}\nAccessKeySecret: ${parts[1]}`;
return {
secret,
status: flag && secret !== Huoshan.defaultSecret,
info:
secret === Huoshan.defaultSecret
? "The secret is not set."
: flag
? partsInfo
: `The secret format of Huoshan Text Translation is AccessKeyId#AccessKeySecret. The secret must have 2 parts joined by '#', but got ${parts?.length}.\n${partsInfo}`,
};
},
translate,
};
================================================
FILE: src/modules/services/huoshanweb.ts
================================================
import type { TranslateService } from "./base";
// https://github.com/TechDecryptor/pot-app-translate-plugin-volcengine
export const HuoshanWeb: TranslateService = {
id: "huoshanweb",
name: "Huoshan Web",
type: "sentence" as const,
translate: async function (data) {
const { raw: text } = data;
const from = (data.langfrom || "").split("-")[0];
const to = (data.langto || "").split("-")[0];
const URL = "https://translate.volcengine.com/crx/translate/v1";
const body = {
source_language: from,
target_language: to,
text,
};
const headers = {
"content-type": "application/json",
};
const xhr = await Zotero.HTTP.request("POST", URL, {
headers,
body: JSON.stringify(body),
responseType: "json",
});
if (xhr.status !== 200) {
throw `Request error: ${xhr.status}`;
}
const result = xhr.response;
const { translation } = result;
if (translation) {
data.result = translation;
} else {
throw JSON.stringify(result);
}
},
};
================================================
FILE: src/modules/services/index.ts
================================================
import { TranslateService } from "./base";
import {
getString,
getPref,
getLastTranslateTask,
TranslateTask,
TranslateTaskRunner,
stripEmptyLines,
} from "../../utils";
import { Aliyun } from "./aliyun";
import { Tencent } from "./tencent";
import { ChatGPT, customGPT1, customGPT2, customGPT3, azureGPT } from "./gpt";
import { Baidu } from "./baidu";
import { BaiduField } from "./baidufield";
import { Bing } from "./bing";
import { BingDict } from "./bingdict";
import { Caiyun } from "./caiyun";
import { CambridgeDict } from "./cambridgedict";
import { Claude } from "./claude";
import { Cnki } from "./cnki";
import { CollinsDict } from "./collinsdict";
import { DeeplFree, DeeplPro } from "./deepl";
import { FreeDictionaryAPI } from "./freedictionaryapi";
import { Gemini } from "./gemini";
import { Google, GoogleAPI } from "./google";
import { Haici } from "./haici";
import { HaiciDict } from "./haicidict";
import { Huoshan } from "./huoshan";
import { HuoshanWeb } from "./huoshanweb";
import { LibreTranslate } from "./libretranslate";
import { Microsoft } from "./microsoft";
import { Mtranserver } from "./mtranserver";
import { Niutrans } from "./niutrans";
import { Nllb } from "./nllb";
import { Openl } from "./openl";
import { Pot } from "./pot";
import { QwenMT } from "./qwenmt";
import { WeblioDict } from "./webliodict";
import { XFfrans } from "./xftrans";
import { TencentTransmart } from "./tencenttransmart";
import { Youdao } from "./youdao";
import { YoudaoDict } from "./youdaodict";
import { YoudaoZhiyun } from "./youdaozhiyun";
import { YoudaoZhiyunLLM } from "./youdaozhiyunllm";
import { DeepLCustom } from "./deeplcustom";
import { DeepLX } from "./deeplx";
const register: TranslateService[] = [
Aliyun,
Baidu,
BaiduField,
Bing,
BingDict,
Caiyun,
CambridgeDict,
Claude,
Cnki,
CollinsDict,
DeeplFree,
DeeplPro,
DeepLCustom,
DeepLX,
FreeDictionaryAPI,
Gemini,
Google,
GoogleAPI,
ChatGPT,
customGPT1,
customGPT2,
customGPT3,
azureGPT,
Haici,
HaiciDict,
Huoshan,
HuoshanWeb,
LibreTranslate,
Microsoft,
Mtranserver,
Niutrans,
Nllb,
Openl,
Pot,
QwenMT,
Tencent,
TencentTransmart,
WeblioDict,
XFfrans,
Youdao,
YoudaoDict,
YoudaoZhiyun,
YoudaoZhiyunLLM,
];
export class TranslationServices {
#services: readonly TranslateService[] = Object.freeze(
this.sortServices(register),
);
/**
* Sort the TranslateService list by the following rules:
* 1. Free and no-config services (no secret, no config) come first.
* 2. All other services are sorted by `id` in ascending order (case-insensitive).
* 3. Services whose `id` starts with "custom" are placed last
* (sorted by `id` in ascending order within this group).
*/
private sortServices(services: T[]) {
return services.sort((a, b) => {
const rank = (s: T) => {
const needsSecret = !!s.defaultSecret || !!s.secretValidator;
const hasConfig = !!s.config;
const needExternalConfig = s.requireExternalConfig;
// Rank for sentence services
if (s.type === "sentence") {
// Group 4: "custom" at the start → last
if (s.id.startsWith("custom")) return 3;
// Group 1: Free sentence services (no secret, no external config)
if (!needsSecret && !needExternalConfig) return 0;
// Group 2: No-secret but requires external config
if (!needsSecret && needExternalConfig) return 1;
// Group 3: Needs secret but no config
if (needsSecret && !hasConfig) return 2;
// Default (Sentence service needs secret and has config) — also rank 2
return 2;
}
// Rank for word services
else {
// Default //TODO Modify it if necessary in the future
return 0;
}
};
const ra = rank(a);
const rb = rank(b);
if (ra !== rb) return ra - rb;
return a.id.localeCompare(b.id);
});
}
public getServiceById(id: string): TranslateService | undefined {
return this.#services.find((service) => service.id === id);
}
public getAllServices(): TranslateService[] {
return [...this.#services];
}
public getAllServicesWithType(type: string): TranslateService[] {
return this.getAllServices().filter((service) => service.type === type);
}
public getServiceNameByID(id: string): string {
const baseName =
(getPref(`renameServices.${id}`) as string) || getString(`service-${id}`);
const service = this.getServiceById(id);
if (
!!service?.defaultSecret ||
!!service?.secretValidator ||
id.startsWith("custom")
) {
return baseName + "🗝️";
}
if (service?.requireExternalConfig) {
return baseName + "📍";
}
return baseName;
}
public getAllServiceNames(): string[] {
return this.getAllServices().map((service) =>
this.getServiceNameByID(service.id),
);
}
public getAllServiceNamesWithType(type: string): string[] {
return this.getAllServicesWithType(type).map((service) =>
this.getServiceNameByID(service.id),
);
}
/**
* Get the set of unconfigured service IDs.
* A service is unconfigured if it requires a secret but none is set or validation fails.
* @returns Set of service IDs that are not configured
*/
public getUnconfiguredServiceIds(): Set {
const unconfigured = new Set();
let secrets: Record = {};
try {
secrets = JSON.parse((getPref("secretObj") as string) || "{}");
} catch {
secrets = {};
}
for (const service of this.#services) {
const needsSecret =
!!service.defaultSecret ||
!!service.secretValidator ||
service.id.startsWith("custom");
if (!needsSecret) continue;
const secret = secrets[service.id] || "";
if (!secret) {
unconfigured.add(service.id);
continue;
}
if (service.secretValidator) {
try {
if (!service.secretValidator(secret).status) {
unconfigured.add(service.id);
}
} catch {
// Validation error - treat as configured
}
}
}
return unconfigured;
}
public async runTranslationTask(
task?: TranslateTask,
options: {
noCheckZoteroItemLanguage?: boolean;
noDisplay?: boolean;
noCache?: boolean;
} = {},
): Promise {
ztoolkit.log("runTranslationTask", options);
const { noCache, noCheckZoteroItemLanguage, noDisplay } = options;
task = task || getLastTranslateTask();
if (!task || !task.raw) {
ztoolkit.log("skipped empty");
return false;
}
task.status = "processing" as TranslateTask["status"];
// Check whether item language is in disabled languages list
let disabledByItemLanguage = false;
if (!noCheckZoteroItemLanguage && task.itemId) {
const item = Zotero.Items.getTopLevel([Zotero.Items.get(task.itemId)])[0];
if (item && task.type !== "custom") {
const itemLanguage = getPref("autoDetectLanguage")
? task.langfrom
: ((item.getField("language") as string) || "").split("-")[0];
const disabledLanguages = (
getPref("disabledLanguages") as string
).split(",");
disabledByItemLanguage =
disabledLanguages.length > 0 &&
!!itemLanguage &&
disabledLanguages.includes(itemLanguage);
}
}
if (disabledByItemLanguage) {
ztoolkit.log("disabledByItemLanguage");
return false;
}
// Remove possible translation results (for annotations).
const splitChar = (getPref("splitChar") as string).trim();
// /🔤[^🔤]*🔤/g
const regex =
splitChar === ""
? ""
: new RegExp(`${splitChar}[^${splitChar}]*${splitChar}`, "g");
task.raw = task.raw.replace(regex, "");
task.result = "";
// Display raw
if (!noDisplay) {
addon.api.getTemporaryRefreshHandler()();
}
let cacheHit = false;
if (!noCache) {
// Check cache
const cachedTask = addon.data.translate.queue.findLast((_t) => {
return (
_t.status === "success" &&
_t.raw === task!.raw &&
_t.service === task!.service &&
(!task.langfrom || _t.langfrom === task.langfrom) &&
(!task.langto || _t.langto === task.langto)
);
});
if (cachedTask) {
cacheHit = true;
ztoolkit.log("cache hit", cachedTask);
task.result = cachedTask.result;
task.status = "success";
if (!noDisplay) {
addon.api.getTemporaryRefreshHandler()();
}
}
}
if (!cacheHit) {
// Get task service
const service = this.getServiceById(task.service);
if (!service) {
task.result = `${task.service} is not implemented.`;
task.status = "fail";
return false;
}
// Run task
const runner = new TranslateTaskRunner(service.translate);
await runner.run(task);
// Apply strip empty lines if enabled
const stripEnabled = getPref("stripEmptyLines") as boolean;
if (stripEnabled && task.result) {
task.result = stripEmptyLines(task.result, true);
}
const resultRegex = getPref("resultRegex") as string;
if (resultRegex) {
try {
const regex = new RegExp(resultRegex, "g");
// Remove all matches
task.result = task.result.replace(regex, "");
} catch (e) {
ztoolkit.log("Invalid result regex", e);
task.result = `Invalid result regex: ${resultRegex}. Please check settings > Translate > Advanced > Result Regex.`;
}
}
// Run extra tasks. Do not wait.
if (task.extraTasks?.length) {
Promise.all(
task.extraTasks.map((extraTask) => {
return this.runTranslationTask(extraTask, {
noCheckZoteroItemLanguage,
noDisplay: true,
});
}),
).then(() => {
addon.hooks.onReaderTabPanelRefresh();
});
}
// Try candidate services if current run fails
if (task.status === "fail" && task.candidateServices.length > 0) {
task.service = task.candidateServices.shift()!;
task.status = "waiting";
return await this.runTranslationTask(task, options);
} else {
// Display result
if (!noDisplay) {
addon.api.getTemporaryRefreshHandler()();
}
}
}
const success = task.status === "success";
const item = Zotero.Items.get(task.itemId!);
// Data storage for corresponding types
if (success) {
switch (task.type) {
case "annotation":
{
if (item) {
const savePosition = getPref("annotationTranslationPosition") as
| "comment"
| "body";
const currentText = (
(savePosition === "comment"
? item.annotationComment
: item.annotationText) || ""
).replace(regex, "");
let text = `${
currentText[currentText.length - 1] === "\n" ? "" : "\n"
}${splitChar}${task.result}${splitChar}\n`;
text = splitChar === "" ? text : `${currentText}${text}`;
item[
savePosition === "comment"
? "annotationComment"
: "annotationText"
] = text;
// Auto tag
const enableAutoTag = getPref(
"enableAutoTagAnnotation",
) as boolean;
if (enableAutoTag) {
const tagContent = getPref("annotationTagContent") as string;
if (tagContent && tagContent.trim()) {
const tag = tagContent.trim();
// Check if the tag already exists
const existingTags = item.getTags();
const tagExists = existingTags.some(
(existingTag) => existingTag.tag === tag,
);
if (!tagExists) {
item.addTag(tag);
}
}
}
item.saveTx();
}
}
break;
case "title":
{
if (item) {
ztoolkit.ExtraField.setExtraField(
item,
"titleTranslation",
task.result,
);
item.saveTx();
}
}
break;
case "abstract":
{
if (item) {
ztoolkit.ExtraField.setExtraField(
item,
"abstractTranslation",
// A dirty workaround to make it collapsible on Zotero 6
task.result,
);
item.saveTx();
}
}
break;
default:
break;
}
}
return success;
}
}
export const services = new TranslationServices();
================================================
FILE: src/modules/services/libretranslate.ts
================================================
import { getPref } from "../../utils/prefs";
import { TranslateService } from "./base";
const translate = async function (data) {
const endpoint =
(getPref("libretranslate.endpoint") as string) || "http://localhost:5000";
const apiKey = data.secret; // Use the secret as the API key
// Prepare request body
const requestBody: any = {
q: data.raw,
source: data.langfrom.split("-")[0],
target: data.langto.split("-")[0],
format: "text",
};
// Only add API key if it exists
if (apiKey) {
requestBody.api_key = apiKey;
}
const xhr = await Zotero.HTTP.request("POST", `${endpoint}/translate`, {
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
responseType: "json",
});
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
if (xhr.response.error) {
throw `Service error: ${xhr.response.error}`;
}
data.result = xhr.response.translatedText;
};
export const LibreTranslate: TranslateService = {
id: "libretranslate",
type: "sentence",
helpUrl: "https://github.com/LibreTranslate/LibreTranslate",
translate,
config(settings) {
settings.addTextSetting({
prefKey: "libretranslate.endpoint",
nameKey: "service-libretranslate-dialog-endPoint",
placeholder: "http://localhost:5000",
});
},
requireExternalConfig: true,
};
================================================
FILE: src/modules/services/microsoft.ts
================================================
import { TranslateService } from "./base";
const translate = async function (data) {
const reqBody = JSON.stringify([{ Text: data.raw }]);
const params = data.secret.split("#");
const secretKey = params[0];
const headers: Record = {
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": secretKey,
};
// Sometimes the MicroSoft translator service need a region parameter.
// The region string is in lower case without space inside. East Asia -> eastasia
if (params[1]) {
const region = params[1].replace(" ", "").toLowerCase();
if (params[1] != "global") headers["Ocp-Apim-Subscription-Region"] = region;
}
const xhr = await Zotero.HTTP.request(
"POST",
`https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=${data.langto}`,
{
headers: headers,
responseType: "json",
body: reqBody,
},
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
const result = xhr.response[0].translations[0].text;
if (!result) {
throw `Parse error: ${JSON.stringify(xhr.response)}`;
}
data.result = result;
};
export const Microsoft: TranslateService = {
id: "microsoft",
type: "sentence",
defaultSecret: "",
secretValidator(secret: string) {
const params = secret.split("#");
const serviceKey = params[0];
const flag = serviceKey?.length === 32 || serviceKey?.length === 84;
return {
secret,
status: flag,
info: flag
? ""
: `The secret is your Azure translate serviceKEY#region(required if the region is not global). The serviceKEY length must be 32 or 84, but got ${serviceKey?.length}.`,
};
},
translate,
};
================================================
FILE: src/modules/services/mtranserver.ts
================================================
import { getPref } from "../../utils/prefs";
import { TranslateService } from "./base";
const translate = async function (data) {
const url =
(getPref("mtranserver.endpoint") as string) ||
"http://localhost:8989/translate";
const xhr = await Zotero.HTTP.request("POST", `${url}`, {
headers: {
authorization: `${data.secret}`,
"content-type": "application/json",
},
body: JSON.stringify({
text: data.raw,
from: mapLang(data.langfrom),
to: mapLang(data.langto),
}),
responseType: "json",
});
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
try {
data.result = xhr.response.result;
} catch {
throw `Service error: ${xhr.response}`;
}
};
function mapLang(lang: string) {
const versionlabel = getPref("mtranserver.versionlabel") as boolean;
if (versionlabel && lang in LANG_MAP) {
return LANG_MAP[lang];
}
return lang.split("-")[0];
}
const LANG_MAP = {
zh: "zh-Hans",
"zh-CN": "zh-Hans",
"zh-HK": "zh-Hant",
"zh-MO": "zh-Hant",
"zh-SG": "zh-Hans",
"zh-TW": "zh-Hant",
} as Record;
export const Mtranserver: TranslateService = {
id: "mtranserver",
type: "sentence",
helpUrl:
"https://github.com/xxnuo/MTranServer?tab=readme-ov-file#api-%E4%BD%BF%E7%94%A8",
translate,
config(settings) {
settings
.addTextSetting({
prefKey: "mtranserver.endpoint",
nameKey: "service-mtranserver-dialog-endPoint",
})
.addCheckboxSetting({
prefKey: "mtranserver.versionlabel",
nameKey: "service-mtranserver-dialog-versionlabel",
});
},
requireExternalConfig: true,
};
================================================
FILE: src/modules/services/niutrans.ts
================================================
import JSEncrypt from "jsencrypt";
import {
createServiceSettingsDialog,
getString,
ServiceSettingsDialog,
setServiceSecret,
} from "../../utils";
import { getPref, setPref } from "../../utils/prefs";
import { TranslateService } from "./base";
const translate = async function (data) {
const apikey = data.secret;
const dictNo = getPref("niutransDictNo");
const memoryNo = getPref("niutransMemoryNo");
const endpoint =
getPref("niutransEndpoint") || "https://niutrans.com/niuInterface";
let requestUrl: string;
let requestBody: any;
if (endpoint.includes("trans.neu.edu.cn")) {
//Neu Niutrans
requestUrl = `https://trans.neu.edu.cn/niutrans/textTranslation?apikey=${data.secret}`;
requestBody = {
from: data.langfrom.split("-")[0],
to: data.langto.split("-")[0],
src_text: data.raw,
};
} else {
//Normal Niutrans
requestUrl = `${endpoint}/textTranslation?pluginType=zotero&apikey=${apikey}`;
requestBody = {
from: data.langfrom.split("-")[0],
to: data.langto.split("-")[0],
termDictionaryLibraryId: dictNo,
translationMemoryLibraryId: memoryNo,
// TEMP: implement realmCode in settings
realmCode: 99,
source: "zotero",
src_text: data.raw,
caller_id: data.callerID,
};
}
const xhr = await Zotero.HTTP.request("POST", requestUrl, {
headers: {
"content-type": "application/json",
accept: "application/json, text/plain, */*",
},
body: JSON.stringify(requestBody),
responseType: "json",
});
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
if (xhr.response.code !== 200) {
throw `Service error: ${xhr.response.code}:${xhr.response.msg}`;
}
if (endpoint.includes("neu.edu.cn")) {
for (let i = 0; i < xhr.response.data[0].sentences.length; i++) {
data.result += xhr.response.data[0].sentences[i].data;
}
} else {
data.result = xhr.response.data.tgt_text;
}
};
export const Niutrans: TranslateService = {
id: "niutranspro",
type: "sentence",
helpUrl: "https://niutrans.com/cloud/resource/index",
defaultSecret: "",
secretValidator(secret: string) {
const flag = secret?.length === 32;
return {
secret,
status: flag,
info: flag
? ""
: `The secret is your NiuTrans API-KEY. The secret length must be 32, but got ${secret?.length}.`,
};
},
translate,
config(settings) {
async function niutransLogin(username: string, password: string) {
let loginFlag = false;
let loginErrorMessage = "Not login";
// Get the public key with a proper HTTPS request
const keyResponse = await getPublicKey();
// Verify the response was successful and has the expected flag
if (keyResponse?.status !== 200 || keyResponse.response.flag !== 1) {
return { loginFlag, loginErrorMessage };
}
// Get the JSESSIONID from the response headers
let jsessionid = "";
// Extract JSESSIONID from the response header
const setCookie = keyResponse.getResponseHeader?.("Set-Cookie") || "";
if (setCookie && setCookie.includes("JSESSIONID=")) {
const match = setCookie.match(/JSESSIONID=([^;]+)/);
if (match && match[1]) {
jsessionid = match[1];
}
}
// Encrypt the password using the public key
const encrypt = new JSEncrypt();
encrypt.setPublicKey(keyResponse.response.key);
let encryptionPassword = encrypt.encrypt(password);
encryptionPassword = encodeURIComponent(encryptionPassword);
// Login with the encrypted password and session ID
const userLoginResponse = await loginApi(
username,
encryptionPassword,
jsessionid,
);
if (userLoginResponse?.status === 200) {
if (userLoginResponse.response.flag === 1) {
const apikey = userLoginResponse.response.apikey;
setPref("niutransUsername", username);
setPref("niutransPassword", password);
setServiceSecret("niutranspro", apikey);
// Use the same JSESSIONID for subsequent requests
await setDictLibList(apikey, jsessionid);
await setMemoryLibList(apikey, jsessionid);
loginFlag = true;
} else {
loginFlag = false;
loginErrorMessage = userLoginResponse.response.msg;
}
}
return { loginFlag, loginErrorMessage };
}
async function loginApi(
username: string,
password: string,
jsessionid: string,
) {
return await Zotero.HTTP.request(
"POST",
"https://apis.niutrans.com/NiuTransAPIServer/checkInformation",
{
body: `account=${username}&encryptionPassword=${password}`,
responseType: "json",
headers: {
Cookie: `JSESSIONID=${jsessionid}`,
},
},
);
}
async function setDictLibList(apikey: string, jsessionid: string) {
const xhr = await Zotero.HTTP.request(
"POST",
"https://apis.niutrans.com/NiuTransAPIServer/getDictLibList",
{
body: `apikey=${apikey}`,
responseType: "json",
headers: {
Cookie: `JSESSIONID=${jsessionid}`,
},
},
);
if (xhr?.status === 200 && xhr.response.flag !== 0) {
const dictList = xhr.response.dlist as {
dictName: string;
dictNo: string;
isUse: number;
}[];
const dictNo = dictList.find((dict) => dict.isUse === 1)?.dictNo || "";
if (dictNo && !getPref("niutransDictNo")) {
setPref("niutransDictNo", dictNo);
}
setPref(
"niutransDictLibList",
JSON.stringify(
dictList.map((dict) => ({
dictName: dict.dictName,
dictNo: dict.dictNo,
})),
),
);
}
}
async function setMemoryLibList(apikey: string, jsessionid: string) {
const xhr = await Zotero.HTTP.request(
"POST",
"https://apis.niutrans.com/NiuTransAPIServer/getMemoryLibList",
{
body: `apikey=${apikey}`,
responseType: "json",
headers: {
Cookie: `JSESSIONID=${jsessionid}`,
},
},
);
if (xhr?.status === 200 && xhr.response.flag !== 0) {
const memoryList = xhr.response.mlist as {
memoryName: string;
memoryNo: string;
isUse: number;
}[];
const memoryNo =
memoryList.find((memory) => memory.isUse === 1)?.memoryNo || "";
if (memoryNo && !getPref("niutransMemoryNo")) {
setPref("niutransMemoryNo", memoryNo);
}
setPref(
"niutransMemoryLibList",
JSON.stringify(
memoryList.map((memory) => ({
memoryName: memory.memoryName,
memoryNo: memory.memoryNo,
})),
),
);
}
}
async function getPublicKey() {
return await Zotero.HTTP.request(
"GET",
"https://apis.niutrans.com/NiuTransAPIServer/getpublickey",
{
responseType: "json",
},
);
}
const dictLibList = getPref("niutransDictLibList") as string;
const memoryLibList = getPref("niutransMemoryLibList") as string;
const dictLibListObj = JSON.parse(dictLibList);
const memoryLibListObj = JSON.parse(memoryLibList);
(settings as ServiceSettingsDialog)
.addTextSetting({
prefKey: "niutransEndpoint",
nameKey: "service-niutranspro-dialog-endpoint",
})
// Add a space line
.addSetting("", "", { tag: "div" })
// For official niutrans service
.addTextSetting({
prefKey: "niutransUsername",
nameKey: "service-niutranspro-dialog-username",
})
.addPasswordSetting({
prefKey: "niutransPassword",
nameKey: "service-niutranspro-dialog-password",
inputType: "password",
})
.addStaticRow("", {
tag: "div",
namespace: "html",
styles: {
display: "flex",
justifyContent: "space-between",
},
children: [
// Register
{
tag: "button",
namespace: "html",
attributes: {
type: "button",
},
properties: {
innerHTML: getString("service-niutranspro-dialog-signup"),
},
listeners: [
{
type: "click",
listener: (e: Event) => {
Zotero.launchURL("https://niutrans.com/register");
},
},
],
},
// Forget password
{
tag: "button",
namespace: "html",
attributes: {
type: "button",
},
properties: {
innerHTML: getString("service-niutranspro-dialog-forget"),
},
listeners: [
{
type: "click",
listener: (e: Event) => {
Zotero.launchURL("https://niutrans.com/password_find");
},
},
],
},
// Sing out
{
tag: "button",
namespace: "html",
attributes: {
type: "button",
},
properties: {
innerHTML: getString("service-niutranspro-dialog-signout"),
},
listeners: [
{
type: "click",
listener: async (e: Event) => {
setPref("niutransUsername", "");
setPref("niutransPassword", "");
setPref("niutransDictLibList", "[]");
setPref("niutransMemoryLibList", "[]");
setPref("niutransDictNo", "");
setPref("niutransMemoryNo", "");
setServiceSecret("niutranspro", "");
const _dialog = settings as ServiceSettingsDialog;
_dialog.window.close();
await createServiceSettingsDialog(Niutrans);
},
},
],
},
// Sing in
{
tag: "button",
namespace: "html",
attributes: {
type: "button",
},
properties: {
innerHTML: getString("service-niutranspro-dialog-signin"),
},
listeners: [
{
type: "click",
listener: async (e: Event) => {
const _dialog = settings as ServiceSettingsDialog;
// login
const data = _dialog.getAllSettingsData();
const { loginFlag, loginErrorMessage } = await niutransLogin(
data["niutransUsername"],
data["niutransPassword"],
);
// If login failed, show error message
if (!loginFlag) {
Zotero.alert(_dialog.window, "Error", loginErrorMessage);
return loginErrorMessage;
}
// else save settings and reopen dialog
_dialog.saveAllSettings();
_dialog.window.close();
await createServiceSettingsDialog(Niutrans);
},
},
],
},
],
})
.addSelectSetting({
prefKey: "niutransMemoryNo",
nameKey: "service-niutranspro-dialog-memoryLib",
options: memoryLibListObj.map(
(memory: { memoryName: string; memoryNo: string }) => ({
value: memory.memoryNo,
label: memory.memoryName,
}),
),
})
.addSelectSetting({
prefKey: "niutransDictNo",
nameKey: "service-niutranspro-dialog-dictLib",
options: dictLibListObj.map(
(dict: { dictName: string; dictNo: string }) => ({
value: dict.dictNo,
label: dict.dictName,
}),
),
})
.addStaticRow("", {
tag: "label",
children: [
{
tag: "label",
properties: {
innerHTML: `${getString("service-niutranspro-dialog-tip0")} `,
},
},
{
tag: "a",
properties: {
href: "https://niutrans.com/cloud/resource/index",
target: "_blank",
innerHTML: getString("service-niutranspro-dialog-tip1"),
},
},
{
tag: "label",
properties: {
innerHTML: ` ${getString("service-niutranspro-dialog-tip2")}`,
},
},
],
});
},
};
================================================
FILE: src/modules/services/nllb.ts
================================================
import { getPref } from "../../utils/prefs";
import { getString } from "../../utils/locale";
import { TranslateService } from "./base";
const translate: TranslateService["translate"] = async (data) => {
const serveurl =
(getPref("nllb.serveendpoint") as string) || "http://localhost:6060";
const apiurl =
(getPref("nllb.apiendpoint") as string) || "http://localhost:7860";
const model = getPref("nllb.model") as string;
const refreshHandler = addon.api.getTemporaryRefreshHandler({ task: data });
if (model === "nllb-serve") {
data.result = getString("status-translating");
refreshHandler();
const nonStreamCallback = (xmlhttp: XMLHttpRequest) => {
xmlhttp.onload = () => {
try {
const responseObj = JSON.parse(xmlhttp.response);
data.result = responseObj.translation[0];
} catch (error) {
return;
}
refreshHandler();
};
};
const xhr = await Zotero.HTTP.request("POST", `${serveurl}/translate`, {
headers: {
"content-type": "application/json",
},
body: JSON.stringify({
source: data.raw,
src_lang: mapLang(data.langfrom),
tgt_lang: mapLang(data.langto),
}),
responseType: "text",
requestObserver: (xmlhttp: XMLHttpRequest) => {
nonStreamCallback(xmlhttp);
},
});
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
} else if (model === "nllb-api") {
const apistream = getPref("nllb.apistream") as boolean;
if (!apistream) {
data.result = getString("status-translating");
refreshHandler();
}
const streamCallback = (xmlhttp: XMLHttpRequest) => {
let preLength = 0;
let result = "";
xmlhttp.onprogress = (e: any) => {
// Only concatenate the new strings
const newResponse = e.target.response.slice(preLength);
const lines = newResponse.split("\n");
for (const line of lines) {
if (line) {
result += line.replace("data:", "").trim() || "";
}
}
if (e.target.timeout) {
e.target.timeout = 0;
}
data.result = result;
preLength = e.target.response.length;
refreshHandler();
};
};
const nonStreamCallback = (xmlhttp: XMLHttpRequest) => {
xmlhttp.onload = () => {
try {
data.result = xmlhttp.response.result;
} catch (error) {
return;
}
refreshHandler();
};
};
const stream = apistream ? "/stream" : "";
const responseType = apistream ? "text" : "json";
const xhr = await Zotero.HTTP.request(
"GET",
`${apiurl}/api/v4/translator${stream}?text=${data.raw}&source=${mapLang(data.langfrom)}&target=${mapLang(data.langto)}`,
{
headers: {
accept: "application/json",
},
responseType: `${responseType}`,
requestObserver: (xmlhttp: XMLHttpRequest) => {
if (apistream) {
streamCallback(xmlhttp);
} else {
nonStreamCallback(xmlhttp);
}
},
},
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
}
};
function mapLang(lang: string) {
const traditionalChinese = ["zh-HK", "zh-MO", "zh-TW"];
if (traditionalChinese.includes(lang)) {
return "zho_Hant";
} else if (lang.split("-")[0] in LANG_MAP) {
return LANG_MAP[lang.split("-")[0]];
}
return lang;
}
const LANG_MAP = {
en: "eng_Latn",
zh: "zho_Hans",
ja: "jpn_Jpan",
ko: "kor_Hang",
fr: "fra_Latn",
es: "spa_Latn",
de: "deu_Latn",
it: "ita_Latn",
nl: "nld_Latn",
pt: "por_Latn",
ru: "rus_Cyrl",
ar: "arb_Arab",
tr: "tur_Latn",
vi: "vie_Latn",
th: "tha_Thai",
id: "ind_Latn",
ms: "zsm_Latn",
hi: "hin_Deva",
bn: "ben_Beng",
ur: "urd_Arab",
he: "heb_Hebr",
pl: "pol_Latn",
ro: "ron_Latn",
cs: "ces_Latn",
hu: "hun_Latn",
sv: "swe_Latn",
da: "dan_Latn",
fi: "fin_Latn",
el: "ell_Grek",
uk: "ukr_Cyrl",
km: "khm_Khmr",
} as Record;
export const Nllb: TranslateService = {
id: "nllb",
type: "sentence",
translate,
config(settings) {
settings
.addSelectSetting({
prefKey: "nllb.model",
nameKey: "service-nllb-dialog-model",
options: [
{
value: "nllb-api",
label: "nllb-api API",
},
{
value: "nllb-serve",
label: "nllb-serve REST API",
},
],
})
// api
.addTextSetting({
nameKey: "service-nllb-dialog-apiendpoint",
prefKey: "nllb.apiendpoint",
})
.addCheckboxSetting({
nameKey: "service-nllb-dialog-apistream",
prefKey: "nllb.apistream",
})
// serve
.addTextSetting({
nameKey: "service-nllb-dialog-serveendpoint",
prefKey: "nllb.serveendpoint",
})
// documentation
.addButton(getString("service-nllb-dialog-apilabel"), "", {
noClose: true,
callback: () => {
Zotero.launchURL(
"https://github.com/winstxnhdw/nllb-api?tab=readme-ov-file#self-hosting",
);
},
})
.addButton(getString("service-nllb-dialog-servelabel"), "", {
noClose: true,
callback: () => {
Zotero.launchURL(
"https://github.com/thammegowda/nllb-serve?tab=readme-ov-file#nllb-serve",
);
},
});
},
requireExternalConfig: true,
};
================================================
FILE: src/modules/services/openl.ts
================================================
import { TranslateService } from "./base";
const translate: TranslateService["translate"] = async (data) => {
const [services, apikey] = data.secret.split("#");
const serviceList = services.split(",");
const xhr = await Zotero.HTTP.request(
"POST",
"https://api.openl.club/group/translate",
{
headers: {
"content-type": "application/json",
},
body: JSON.stringify({
apikey: apikey,
services: serviceList,
text: data.raw,
source_lang: data.langfrom.split("-")[0],
target_lang: data.langto.split("-")[0],
}),
responseType: "json",
},
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
const res = xhr.response as {
status: boolean | any;
[key: string]: any;
};
if (!res.status) {
throw `Service error: ${JSON.stringify(res)}`;
}
delete res.status;
let tgt = "";
const openLServices = Object.keys(res);
if (openLServices.length === 1) {
// Only one engine
const resObj = res[openLServices[0]];
if (resObj.status) {
tgt = resObj.result;
} else {
throw "Service error: all OpenL services failed.";
}
} else {
for (const openLService of openLServices) {
if (res[openLService].status) {
tgt += `[${openLService}] ${res[openLService].result}\n`;
}
}
}
data.result = tgt;
};
export const Openl: TranslateService = {
id: "openl",
type: "sentence",
defaultSecret: "service1,service2,...#apikey",
secretValidator(secret: string) {
const parts = secret?.split("#");
const flag = parts.length === 2;
const partsInfo = `Services: ${parts[0]}\nAPIKey: ${parts[1]}`;
return {
secret,
status: flag && secret !== Openl.defaultSecret,
info:
secret === Openl.defaultSecret
? "The secret is not set."
: flag
? partsInfo
: `The secret format of OpenL is service1,service2,...#APIKey. The secret must have 2 parts joined by '#', but got ${parts?.length}.\n${partsInfo}`,
};
},
translate,
};
================================================
FILE: src/modules/services/pot.ts
================================================
import { getPref } from "../../utils/prefs";
import { TranslateService } from "./base";
const translate: TranslateService["translate"] = async (data) => {
const port = getPref("pot.port");
const xhr = await Zotero.HTTP.request(
"POST",
`http://127.0.0.1:${port}/translate`,
{
headers: {
"content-type": "text/plain;charset=UTF-8",
},
body: data.raw,
responseType: "text",
},
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
// pot will show result in the popup, so we don't need to show it again
data.result = "";
};
export const Pot: TranslateService = {
id: "pot",
type: "sentence",
helpUrl: "https://github.com/pot-app/pot-desktop",
translate,
config(settings) {
settings.addNumberSetting({
prefKey: "pot.port",
nameKey: "service-pot-dialog-port",
min: 1,
max: 65535,
step: 1,
});
},
requireExternalConfig: true,
};
================================================
FILE: src/modules/services/qwenmt.ts
================================================
import { getPref } from "../../utils/prefs";
import { getString } from "../../utils/locale";
import { TranslateService } from "./base";
const translate: TranslateService["translate"] = async function (data) {
const apiURL =
(getPref("qwenmt.endPoint") as string) ||
"https://dashscope.aliyuncs.com/compatible-mode";
const model = (getPref("qwenmt.model") as string) || "qwen-mt-plus";
const domains_prompt = (getPref("qwenmt.domains") as string) || "";
const refreshHandler = addon.api.getTemporaryRefreshHandler({ task: data });
data.result = getString("status-translating");
refreshHandler();
const nonStreamCallback = (xmlhttp: XMLHttpRequest) => {
xmlhttp.onload = () => {
try {
const responseObj = xmlhttp.response;
const resultContent = responseObj.choices[0].message.content;
data.result = resultContent.replace(/^\n\n/, "");
} catch (error) {
return;
}
refreshHandler();
};
};
const xhr = await Zotero.HTTP.request(
"POST",
`${apiURL}/v1/chat/completions`,
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${data.secret}`,
},
body: JSON.stringify({
model: model,
messages: [
{
role: "user",
content: data.raw,
},
],
translation_options: {
source_lang: "auto",
target_lang: mapLang(data.langto),
domains: domains_prompt,
},
}),
responseType: "json",
requestObserver: (xmlhttp: XMLHttpRequest) => {
nonStreamCallback(xmlhttp);
},
},
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
};
function mapLang(lang: string) {
if (lang in LANG_MAP) {
return LANG_MAP[lang];
}
return lang.split("-")[0];
}
const LANG_MAP = {
en: "English",
zh: "Chinese",
"zh-CN": "Chinese",
"zh-HK": "Traditional Chinese",
"zh-MO": "Traditional Chinese",
"zh-SG": "Chinese",
"zh-TW": "Traditional Chinese",
ja: "Japanese",
ko: "Korean",
fr: "French",
es: "Spanish",
de: "German",
it: "Italian",
nl: "Dutch",
pt: "Portuguese",
ru: "Russian",
ar: "Arabic",
tr: "Turkish",
vi: "Vietnamese",
th: "Thai",
id: "Indonesian",
ms: "Malay",
hi: "Hindi",
bn: "Bengali",
ur: "Urdu",
fa: "Persian",
he: "Hebrew",
pl: "Polish",
ro: "Romanian",
cs: "Czech",
hu: "Hungarian",
sv: "Swedish",
da: "Danish",
fi: "Finnish",
el: "Greek",
no: "Norwegian",
uk: "Ukrainian",
km: "Khmer",
} as Record;
export const QwenMT: TranslateService = {
id: "qwenmt",
type: "sentence",
helpUrl:
"https://help.aliyun.com/zh/model-studio/user-guide/machine-translation/",
defaultSecret: "",
secretValidator(secret: string) {
const flag = Boolean(secret);
return {
secret,
status: flag,
info: flag ? "" : "The secret is not set.",
};
},
translate,
config(settings) {
settings
.addTextSetting({
prefKey: "qwenmt.endPoint",
nameKey: "service-qwenmt-dialog-endPoint",
})
.addTextSetting({
prefKey: "qwenmt.model",
nameKey: "service-qwenmt-dialog-model",
})
.addTextSetting({
prefKey: "qwenmt.domains",
nameKey: "service-qwenmt-dialog-domains",
});
},
};
================================================
FILE: src/modules/services/tencent.ts
================================================
import { base64, hmacSha1Digest } from "../../utils/crypto";
import { TranslateService } from "./base";
import { getPref, setPref } from "../../utils/prefs";
import { setServiceSecret } from "../../utils/secret";
const translate: TranslateService["translate"] = async (data) => {
let secretId = (getPref("tencent.secretId") as string) || "";
let secretKey = (getPref("tencent.secretKey") as string) || "";
let region = getPref("tencent.region") as string;
let projectId = getPref("tencent.projectId") as string;
const termRepoIDList = getPref("tencent.termRepoIDList") as string;
const sentRepoIDList = getPref("tencent.sentRepoIDList") as string;
// Migrate the modified secret to Prefs
if (data.secret !== Tencent.defaultSecret) {
const params = data.secret.split("#");
const parsedSecretId = params[0];
secretId = MigrateSecret(parsedSecretId, secretId, "secretId");
const parsedSecretKey = params[1];
secretKey = MigrateSecret(parsedSecretKey, secretKey, "secretKey");
if (params.length >= 3 && params[2]) {
const parsedRegion = params[2];
region = MigrateSecret(parsedRegion, region, "region");
}
if (params.length >= 4 && params[3]) {
const parsedProjectId = params[3];
projectId = MigrateSecret(parsedProjectId, projectId, "projectId");
}
}
function MigrateSecret(parsedStr: string, str: string, prefKey: string) {
if (parsedStr && parsedStr !== str) {
setPref(`tencent.${prefKey}`, parsedStr);
return parsedStr;
}
return str;
}
const parseCommaList = (input: string): string[] =>
input
.split(",")
.map((id) => id.trim())
.filter((id) => id.length > 0);
const termRepoList = parseCommaList(termRepoIDList);
const sentRepoList = parseCommaList(sentRepoIDList);
function encodeRFC5987ValueChars(str: string) {
return encodeURIComponent(str)
.replace(
/['()*]/g,
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
) // i.e., %27 %28 %29 %2A
.replace(/%20/g, "+");
}
// Build parameters object for proper sorting
const paramsObj: { [key: string]: string } = {
Action: "TextTranslate",
Language: "zh-CN",
Nonce: "9744",
ProjectId: projectId,
Region: region,
SecretId: secretId,
Source: data.langfrom.split("-")[0],
SourceText: "#$#",
Target: data.langto.split("-")[0],
Timestamp: new Date().getTime().toString().substring(0, 10),
Version: "2018-03-21",
};
// Add repository lists with compact syntax
termRepoList.forEach(
(repoId, index) => (paramsObj[`TermRepoIDList.${index}`] = repoId),
);
sentRepoList.forEach(
(repoId, index) => (paramsObj[`SentRepoIDList.${index}`] = repoId),
);
// Sort and build query string (required for Tencent Cloud signature)
const rawStr = Object.keys(paramsObj)
.sort()
.map((key) => `${key}=${paramsObj[key]}`)
.join("&");
const sha1Str = encodeRFC5987ValueChars(
base64(
await hmacSha1Digest(
`POSTtmt.tencentcloudapi.com/?${rawStr.replace("#$#", data.raw)}`,
secretKey,
),
),
);
const xhr = await Zotero.HTTP.request(
"POST",
"https://tmt.tencentcloudapi.com",
{
headers: {
"content-type": "application/json",
},
// Encode \s to +
body: `${rawStr.replace(
"#$#",
encodeRFC5987ValueChars(data.raw),
)}&Signature=${sha1Str}`,
responseType: "json",
},
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
if (xhr.response.Response.Error) {
throw `Service error: ${xhr.response.Response.Error.Code}:${xhr.response.Response.Error.Message}`;
}
data.result = xhr.response.Response.TargetText;
};
export const Tencent: TranslateService = {
id: "tencent",
type: "sentence",
helpUrl: "https://cloud.tencent.com/document/product/551/15619",
defaultSecret:
"secretId#SecretKey#Region(default ap-shanghai)#ProjectId(default 0)",
secretValidator(secret: string) {
const parts = secret?.split("#");
const flag = [2, 3, 4].includes(parts.length);
const partsInfo = `SecretId: ${parts[0]}\nSecretKey: ${
parts[1]
}\nRegion: ${parts[2] ? parts[2] : "ap-shanghai"}\nProjectId: ${
parts[3] ? parts[3] : "0"
}`;
return {
secret: secret as string,
status: flag && secret !== Tencent.defaultSecret,
info:
secret === Tencent.defaultSecret
? "The secret is not set. Click the button to configure."
: flag
? partsInfo
: `The secret must have 2, 3 or 4 parts joined by '#', but got ${parts?.length}.\n${partsInfo}\nUse format: SecretId#SecretKey#Region(optional)#ProjectId(optional) or click Config button for advanced configuration.`,
};
},
translate,
config(settings) {
settings
.addTextSetting({
// @ts-expect-error this pref is not inited in prefs.js
prefKey: "tencent.secretId",
nameKey: `service-tencent-dialog-secretid`,
})
.addPasswordSetting({
// @ts-expect-error this pref is not inited in prefs.js
prefKey: "tencent.secretKey",
nameKey: `service-tencent-dialog-secretkey`,
})
.addSelectSetting({
prefKey: "tencent.region",
nameKey: `service-tencent-dialog-region`,
options: [
{ value: "ap-bangkok", label: "ap-bangkok" },
{ value: "ap-beijing", label: "ap-beijing" },
{ value: "ap-chengdu", label: "ap-chengdu" },
{ value: "ap-chongqing", label: "ap-chongqing" },
{ value: "ap-guangzhou", label: "ap-guangzhou" },
{ value: "ap-hongkong", label: "ap-hongkong" },
{ value: "ap-seoul", label: "ap-seoul" },
{ value: "ap-shanghai", label: "ap-shanghai" },
{ value: "ap-shanghai-fsi", label: "ap-shanghai-fsi" },
{ value: "ap-shenzhen-fsi", label: "ap-shenzhen-fsi" },
{ value: "ap-singapore", label: "ap-singapore" },
{ value: "ap-tokyo", label: "ap-tokyo" },
{ value: "eu-frankfurt", label: "eu-frankfurt" },
{ value: "na-ashburn", label: "na-ashburn" },
{ value: "na-siliconvalley", label: "na-siliconvalley" },
],
})
.addTextSetting({
prefKey: "tencent.projectId",
placeholder: "0",
nameKey: `service-tencent-dialog-projectid`,
})
.addTextSetting({
// @ts-expect-error this pref is not inited in prefs.js
prefKey: "tencent.termRepoIDList",
placeholder: "144aed**fc7321d4, 256bef**ac8432e5",
nameKey: `service-tencent-dialog-termrepoid`,
})
.addTextSetting({
// @ts-expect-error this pref is not inited in prefs.js
prefKey: "tencent.sentRepoIDList",
placeholder: "345cde**bd9543f6, 456def**ce0654g7",
nameKey: `service-tencent-dialog-sentrepoid`,
})
.onSave((dialogData) => {
// Validate required fields
if (
// @ts-expect-error those pref key not inited in pref.js
!dialogData["tencent.secretId"] ||
// @ts-expect-error those pref key not inited in pref.js
!dialogData["tencent.secretKey"]
) {
return "Secret ID and Secret Key are required!";
}
// @ts-expect-error those pref key not inited in pref.js
const secretId = dialogData["tencent.secretId"];
// @ts-expect-error those pref key not inited in pref.js
const secretKey = dialogData["tencent.secretKey"];
const region = dialogData["tencent.region"];
const projectId = dialogData["tencent.projectId"];
// Update the tencent secret storage
const combinedSecret = (() => {
const parts = [];
const items = [secretId, secretKey, region, projectId];
for (const item of items) {
if (item == null || item === "") {
break;
}
parts.push(String(item));
}
return parts.join("#");
})();
setServiceSecret("tencent", combinedSecret);
return true;
});
},
};
const helpMessage = `Tencent Cloud Translation Configuration Help:
Required Fields:
• Secret ID: Your Tencent Cloud Access Key ID
• Secret Key: Your Tencent Cloud Secret Access Key
Optional Fields:
• Region: Tencent Cloud region (default: ap-shanghai)
• Project ID: Tencent Cloud project ID (default: 0)
Repository IDs (Optional):
• Term Repo IDs: Custom terminology databases
- Format: Comma-separated hex values (e.g., 144aed**fc7321d4, 256bef**ac8432e5)
- Used for domain-specific translations
• Sent Repo IDs: Sentence-level translation memories
- Format: Comma-separated hex values (e.g., 345cde**bd9543f6, 456def**ce0654g7)
- Used for consistent sentence translations
For more information, visit the documentation link.`;
================================================
FILE: src/modules/services/tencenttransmart.ts
================================================
import type { TranslateService } from "./base";
export const TencentTransmart: TranslateService = {
id: "tencenttransmart",
name: "Tencent Transmart",
type: "sentence" as const,
translate: async function (data) {
const { raw: text } = data;
// Tencent Transmart only accepts base language code (e.g., 'en', 'zh')
const from = (data.langfrom || "").split("-")[0];
const to = (data.langto || "").split("-")[0];
const URL = "https://transmart.qq.com/api/imt";
const body = {
header: {
fn: "auto_translation",
client_key:
"browser-chrome-110.0.0-Mac OS-df4bd4c5-a65d-44b2-a40f-42f34f3535f2-1677486696487",
},
type: "plain",
model_category: "normal",
source: {
lang: from,
text_list: [text],
},
target: {
lang: to,
},
};
const headers = {
"Content-Type": "application/json",
"user-agent":
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36",
referer: "https://transmart.qq.com/zh-CN/index",
};
const xhr = await Zotero.HTTP.request("POST", URL, {
headers,
body: JSON.stringify(body),
responseType: "json",
});
if (xhr.status !== 200) {
throw `Request error: ${xhr.status}`;
}
const result = xhr.response;
const { auto_translation } = result;
if (auto_translation) {
data.result = auto_translation.join("\n").trim();
} else {
throw JSON.stringify(result);
}
},
};
================================================
FILE: src/modules/services/webliodict.ts
================================================
import { TranslateService } from "./base";
const translate: TranslateService["translate"] = async function (data) {
const xhr = await Zotero.HTTP.request(
"GET",
`https://ejje.weblio.jp/content/${encodeURIComponent(data.raw)}/`,
{ responseType: "text" },
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
const res = xhr.response;
const doc: Document = new DOMParser().parseFromString(res, "text/html");
const translations: string[][] = [];
const process = (ele: Element | undefined) => {
if (!ele) {
return [];
}
return Array.from(ele.children).map((e) =>
(e as HTMLElement).innerText.trim(),
);
};
translations.push(process(doc.querySelector(".descriptionWrp")?.children[0]));
doc.querySelector(".descriptionWrp")?.remove();
Array.prototype.forEach.call(
doc.querySelector(".summaryM")?.children,
(e: Element) => translations.push(process(e)),
);
for (const e of doc.querySelectorAll(".intrst")) {
const tableRow = (e as HTMLElement)?.querySelector(
"tr",
);
if (tableRow) {
translations.push(process(tableRow));
}
}
data.result = translations
.filter((t) => t)
.map((t) => t.join(":"))
.join("\n");
};
export const WeblioDict: TranslateService = {
id: "webliodict",
type: "word",
translate,
};
================================================
FILE: src/modules/services/xftrans.ts
================================================
import { getString } from "../../utils";
import { base64, hmacSha256Digest, sha256Digest } from "../../utils/crypto";
import { getPref } from "../../utils/prefs";
import { TranslateService } from "./base";
const translate: TranslateService["translate"] = async function (data) {
const [appid, apiSecret, apiKey] = data.secret.split("#");
const useNiutrans = getPref("xftrans.engine") === "niutrans";
const config = useNiutrans
? {
appid,
apiSecret,
apiKey,
host: "ntrans.xfyun.cn",
hostUrl: "https://ntrans.xfyun.cn/v2/ots",
uri: "/v2/ots",
}
: {
appid,
apiSecret,
apiKey,
host: "itrans.xfyun.cn",
hostUrl: "https://itrans.xfyun.cn/v2/its",
uri: "/v2/its",
};
function transLang(inlang: string = "") {
if (useNiutrans) {
const simplifiedChinese = ["zh-CN", "zh-SG", "zh"];
const traditionalChinese = ["zh-HK", "zh-MO", "zh-TW"];
if (simplifiedChinese.includes(inlang)) {
return "cn";
}
if (traditionalChinese.includes(inlang)) {
return "cht";
} else {
return inlang.split("-")[0];
}
} else {
const langs = [{ regex: /zh(?:[-_]\w+)?/, lang: "cn" }];
// default
let outlang = inlang.split("-")[0];
langs.forEach((obj) => {
if (obj.regex.test(inlang)) {
outlang = obj.lang;
}
});
return outlang;
}
}
const transVar = {
text: data.raw,
from: transLang(data.langfrom),
to: transLang(data.langto),
};
const date = new Date().toUTCString();
const postBody = getPostBody(transVar.text, transVar.from, transVar.to);
const digest = await getDigest(postBody);
const options = {
url: config.hostUrl,
headers: {
"Content-Type": "application/json",
Accept: "application/json,version=1.0",
Host: config.host,
Date: date,
Digest: digest,
Authorization: await getAuthStr(date, digest),
},
json: true,
body: postBody,
};
function getPostBody(text: string, from: string, to: string) {
const digestObj = {
common: {
app_id: config.appid,
},
business: {
from: from,
to: to,
},
data: {
text: base64(new TextEncoder().encode(text).buffer as ArrayBuffer),
},
};
return digestObj;
}
async function getDigest(body: any) {
return `SHA-256=${base64(await sha256Digest(JSON.stringify(body)))}`;
}
async function getAuthStr(date: string, digest: string) {
const signatureOrigin = `host: ${config.host}\ndate: ${date}\nPOST ${config.uri} HTTP/1.1\ndigest: ${digest}`;
const signatureSha = await hmacSha256Digest(
signatureOrigin,
config.apiSecret,
);
const signature = base64(signatureSha);
const authorizationOrigin = `api_key="${config.apiKey}", algorithm="hmac-sha256", headers="host date request-line digest", signature="${signature}"`;
return authorizationOrigin;
}
const xhr = await Zotero.HTTP.request("POST", options.url, {
headers: options.headers,
responseType: "json",
body: JSON.stringify(options.body),
});
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
data.result = xhr.response.data.result.trans_result.dst;
};
export const XFfrans: TranslateService = {
id: "xftrans",
type: "sentence",
helpUrl: "https://console.xfyun.cn/services/its",
defaultSecret: "AppID#ApiSecret#ApiKey",
secretValidator(secret: string) {
const parts = secret?.split("#");
const flag = parts.length === 3;
const partsInfo = `AppID: ${parts[0]}\nApiSecret: ${parts[1]}\nApiKey: ${parts[2]}`;
return {
secret,
status: flag && secret !== XFfrans.defaultSecret,
info:
secret === XFfrans.defaultSecret
? "The secret is not set."
: flag
? partsInfo
: `The secret format of Xftrans Domain Text Translation is AppID#ApiSecret#ApiKey. The secret must have 3 parts joined by '#', but got ${parts?.length}.\n${partsInfo}`,
};
},
translate,
config(settings) {
settings.addSelectSetting({
prefKey: "xftrans.engine",
nameKey: "service-xftrans-dialog-engine",
options: [
{
value: "xftrans",
label: "xftrans",
},
{
value: "niutrans",
label: "niutrans",
},
],
});
},
};
================================================
FILE: src/modules/services/youdao.ts
================================================
import { TranslateService } from "./base";
const translate: TranslateService["translate"] = async function (data) {
const param = `${data.langfrom.toUpperCase().replace("-", "_")}2${data.langto
.toUpperCase()
.replace("-", "_")}`;
const xhr = await Zotero.HTTP.request(
"GET",
`http://fanyi.youdao.com/translate?&doctype=json&type=${param}&i=${encodeURIComponent(
data.raw,
)}`,
{ responseType: "json" },
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
const res = xhr.response.translateResult;
let tgt = "";
for (const i in res) {
for (const j in res[i]) {
tgt += res[i][j].tgt;
}
}
data.result = tgt;
};
export const Youdao: TranslateService = {
id: "youdao",
type: "sentence",
translate,
};
================================================
FILE: src/modules/services/youdaodict.ts
================================================
import { TranslateService } from "./base";
const translate: TranslateService["translate"] = async function (data) {
const xhr = await Zotero.HTTP.request(
"GET",
`https://www.youdao.com/w/${encodeURIComponent(data.raw)}/`,
{ responseType: "text" },
);
if (xhr?.status !== 200) {
throw `Request error: ${xhr?.status}`;
}
let res = xhr.response;
try {
res = res.replace(/(\r\n|\n|\r)/gm, "");
res = res.match(
/