├── .gitattributes ├── .prettierrc ├── addon ├── chrome │ └── content │ │ ├── zoteroPane.css │ │ ├── icons │ │ ├── favicon.png │ │ └── favicon@0.5x.png │ │ └── preferences.xhtml ├── prefs.js ├── locale │ ├── zh-CN │ │ ├── preferences.ftl │ │ └── addon.ftl │ └── en-US │ │ ├── preferences.ftl │ │ └── addon.ftl ├── manifest.json └── bootstrap.js ├── .vscode ├── extensions.json ├── setting.json ├── launch.json └── toolkit.code-snippets ├── .gitignore ├── src ├── utils │ ├── window.ts │ ├── prefs.ts │ ├── wait.ts │ └── locale.ts ├── modules │ ├── preferenceScript.ts │ ├── examples.ts │ └── rename.ts ├── index.ts ├── hooks.ts └── addon.ts ├── .release-it.json ├── tsconfig.json ├── update-template.json ├── scripts ├── stop.mjs ├── start.mjs ├── reload.mjs └── build.mjs ├── update.json ├── .github └── dependabot.yml ├── typing └── global.d.ts ├── .eslintrc.json ├── package.json ├── README.md └── LICENSE /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "tabWidth": 2 3 | } 4 | -------------------------------------------------------------------------------- /addon/chrome/content/zoteroPane.css: -------------------------------------------------------------------------------- 1 | .makeItRed { 2 | background-color: tomato; 3 | } 4 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": ["dbaeumer.vscode-eslint", "esbenp.prettier-vscode"] 3 | } 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **/builds 2 | node_modules 3 | package-lock.json 4 | zotero-cmd.json 5 | scripts/zotero-cmd-default.json -------------------------------------------------------------------------------- /addon/chrome/content/icons/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Theigrams/zotero-pdf-custom-rename/HEAD/addon/chrome/content/icons/favicon.png -------------------------------------------------------------------------------- /addon/chrome/content/icons/favicon@0.5x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Theigrams/zotero-pdf-custom-rename/HEAD/addon/chrome/content/icons/favicon@0.5x.png -------------------------------------------------------------------------------- /.vscode/setting.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnType": false, 3 | "editor.formatOnSave": true, 4 | "editor.codeActionsOnSave": { 5 | "source.fixAll.eslint": true 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /addon/prefs.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-undef */ 2 | pref("extensions.zotero.shortcut.enable", true); 3 | pref("extensions.zotero.shortcut.modifiers", "control"); 4 | pref("extensions.zotero.shortcut.key", "D"); 5 | -------------------------------------------------------------------------------- /addon/locale/zh-CN/preferences.ftl: -------------------------------------------------------------------------------- 1 | pref-title = PDF重命名设置 2 | pref-h1 = 快捷键设置 3 | pref-shortcut-enable = 4 | .label = 启用快捷键重命名PDF文件(默认:control+D) 5 | pref-modifiers = 快捷键: 6 | pref-key = + 7 | pref-help = { $name } Build { $version } { $time } -------------------------------------------------------------------------------- /src/utils/window.ts: -------------------------------------------------------------------------------- 1 | export { isWindowAlive }; 2 | 3 | /** 4 | * Check if the window is alive. 5 | * Useful to prevent opening duplicate windows. 6 | * @param win 7 | */ 8 | function isWindowAlive(win?: Window) { 9 | return win && !Components.utils.isDeadWrapper(win) && !win.closed; 10 | } 11 | -------------------------------------------------------------------------------- /addon/locale/en-US/preferences.ftl: -------------------------------------------------------------------------------- 1 | pref-title = PDF Rename Settings 2 | pref-h1 = Shortcut Settings 3 | pref-shortcut-enable = 4 | .label = Enable shortcut keys to rename PDF files (Default: control+D) 5 | pref-modifiers = Shortcut key: 6 | pref-key = + 7 | pref-help = { $name } Build { $version } { $time } -------------------------------------------------------------------------------- /.release-it.json: -------------------------------------------------------------------------------- 1 | { 2 | "npm": { 3 | "publish": false 4 | }, 5 | "github": { 6 | "release": true, 7 | "assets": ["builds/*.xpi"] 8 | }, 9 | "hooks": { 10 | "after:bump": "npm run build", 11 | "after:release": "echo Successfully released ${name} v${version} to ${repo.repository}." 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "experimentalDecorators": true, 4 | "module": "commonjs", 5 | "target": "ES2016", 6 | "resolveJsonModule": true, 7 | "skipLibCheck": true, 8 | "strict": true 9 | }, 10 | "include": ["src", "typing", "node_modules/zotero-types"], 11 | "exclude": ["builds", "addon"] 12 | } 13 | -------------------------------------------------------------------------------- /update-template.json: -------------------------------------------------------------------------------- 1 | { 2 | "addons": { 3 | "__addonID__": { 4 | "updates": [ 5 | { 6 | "version": "__buildVersion__", 7 | "update_link": "__releasepage__", 8 | "applications": { 9 | "zotero": { 10 | "strict_min_version": "6.999" 11 | } 12 | } 13 | } 14 | ] 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /addon/locale/zh-CN/addon.ftl: -------------------------------------------------------------------------------- 1 | startup-begin = 插件加载中 2 | startup-finish = 插件已就绪 3 | menuitem-renamePDF = 重命名PDF附件 4 | menuitem-label = 插件模板: 帮助工具样例 5 | menupopup-label = 插件模板: 弹出菜单 6 | menuitem-submenulabel = 插件模板:子菜单 7 | menuitem-filemenulabel = 插件模板: 文件菜单 8 | prefs-title = PDF重命名 9 | prefs-table-title = 标题 10 | prefs-table-detail = 详情 11 | tabpanel-lib-tab-label = 库标签 12 | tabpanel-reader-tab-label = 阅读器标签 -------------------------------------------------------------------------------- /scripts/stop.mjs: -------------------------------------------------------------------------------- 1 | import process from "process"; 2 | import { execSync } from "child_process"; 3 | import cmd from "./zotero-cmd.json" assert { type: "json" }; 4 | const { killZoteroWindows, killZoteroUnix } = cmd; 5 | 6 | try { 7 | if (process.platform === "win32") { 8 | execSync(killZoteroWindows); 9 | } else { 10 | execSync(killZoteroUnix); 11 | } 12 | } catch (e) { 13 | console.error(e); 14 | } 15 | -------------------------------------------------------------------------------- /update.json: -------------------------------------------------------------------------------- 1 | { 2 | "addons": { 3 | "pdfrename@theigrams.com": { 4 | "updates": [ 5 | { 6 | "version": "1.0.0", 7 | "update_link": "https://github.com/Theigrams/zotero-pdf-custom-rename/releases/latest/download/zotero-pdf-rename.xpi", 8 | "applications": { 9 | "zotero": { 10 | "strict_min_version": "6.999" 11 | } 12 | } 13 | } 14 | ] 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /addon/locale/en-US/addon.ftl: -------------------------------------------------------------------------------- 1 | startup-begin = Addon is loading 2 | startup-finish = Addon is ready 3 | menuitem-renamePDF = Rename PDF Attachments 4 | menuitem-label = Addon Template: Helper Examples 5 | menupopup-label = Addon Template: Menupopup 6 | menuitem-submenulabel = Addon Template 7 | menuitem-filemenulabel = Addon Template: File Menuitem 8 | prefs-title = PDF Rename 9 | prefs-table-title = Title 10 | prefs-table-detail = Detail 11 | tabpanel-lib-tab-label = Lib Tab 12 | tabpanel-reader-tab-label = Reader Tab -------------------------------------------------------------------------------- /addon/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 2, 3 | "name": "__addonName__", 4 | "version": "__buildVersion__", 5 | "description": "__description__", 6 | "author": "__author__", 7 | "icons": { 8 | "48": "chrome/content/icons/favicon@0.5x.png", 9 | "96": "chrome/content/icons/favicon.png" 10 | }, 11 | "applications": { 12 | "zotero": { 13 | "id": "__addonID__", 14 | "update_url": "__updaterdf__", 15 | "strict_min_version": "6.999", 16 | "strict_max_version": "7.0.*" 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "npm" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /typing/global.d.ts: -------------------------------------------------------------------------------- 1 | declare const _globalThis: { 2 | [key: string]: any; 3 | Zotero: _ZoteroTypes.Zotero; 4 | ZoteroPane: _ZoteroTypes.ZoteroPane; 5 | Zotero_Tabs: typeof Zotero_Tabs; 6 | window: Window; 7 | document: Document; 8 | ztoolkit: typeof ztoolkit; 9 | addon: typeof addon; 10 | }; 11 | 12 | // declare const ztoolkit: import("../src/addon").MyToolkit; 13 | declare const ztoolkit: import("zotero-plugin-toolkit").ZoteroToolkit; 14 | 15 | declare const rootURI: string; 16 | 17 | declare const addon: import("../src/addon").default; 18 | 19 | declare const __env__: "production" | "development"; 20 | 21 | declare class Localization {} 22 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // 使用 IntelliSense 了解相关属性。 3 | // 悬停以查看现有属性的描述。 4 | // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "node", 9 | "request": "launch", 10 | "name": "StartDev", 11 | "runtimeExecutable": "npm", 12 | "runtimeArgs": ["run", "start-watch"] 13 | }, 14 | { 15 | "type": "node", 16 | "request": "launch", 17 | "name": "Restart", 18 | "runtimeExecutable": "npm", 19 | "runtimeArgs": ["run", "restart"] 20 | }, 21 | { 22 | "type": "node", 23 | "request": "launch", 24 | "name": "Restart in Prod Mode", 25 | "runtimeExecutable": "npm", 26 | "runtimeArgs": ["run", "restart-prod"] 27 | } 28 | ] 29 | } 30 | -------------------------------------------------------------------------------- /src/utils/prefs.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../../package.json"; 2 | 3 | /** 4 | * Get preference value. 5 | * Wrapper of `Zotero.Prefs.get`. 6 | * @param key 7 | */ 8 | export function getPref(key: string) { 9 | return Zotero.Prefs.get(`${config.prefsPrefix}.${key}`, true); 10 | } 11 | 12 | /** 13 | * Set preference value. 14 | * Wrapper of `Zotero.Prefs.set`. 15 | * @param key 16 | * @param value 17 | */ 18 | export function setPref(key: string, value: string | number | boolean) { 19 | return Zotero.Prefs.set(`${config.prefsPrefix}.${key}`, value, true); 20 | } 21 | 22 | /** 23 | * Clear preference value. 24 | * Wrapper of `Zotero.Prefs.clear`. 25 | * @param key 26 | */ 27 | export function clearPref(key: string) { 28 | return Zotero.Prefs.clear(`${config.prefsPrefix}.${key}`, true); 29 | } 30 | -------------------------------------------------------------------------------- /scripts/start.mjs: -------------------------------------------------------------------------------- 1 | import process from "process"; 2 | import { execSync } from "child_process"; 3 | import { exit } from "process"; 4 | import minimist from "minimist"; 5 | import cmd from "./zotero-cmd.json" assert { type: "json" }; 6 | const { exec } = cmd; 7 | 8 | // Run node start.js -h for help 9 | const args = minimist(process.argv.slice(2)); 10 | 11 | if (args.help || args.h) { 12 | console.log("Start Zotero Args:"); 13 | console.log( 14 | "--zotero(-z): Zotero exec key in zotero-cmd.json. Default the first one." 15 | ); 16 | console.log("--profile(-p): Zotero profile name."); 17 | exit(0); 18 | } 19 | 20 | const zoteroPath = exec[args.zotero || args.z || Object.keys(exec)[0]]; 21 | const profile = args.profile || args.p; 22 | 23 | const startZotero = `${zoteroPath} --debugger --purgecaches ${ 24 | profile ? `-p ${profile}` : "" 25 | }`; 26 | 27 | execSync(startZotero); 28 | exit(0); 29 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true, 4 | "es2021": true 5 | }, 6 | "root": true, 7 | "extends": [ 8 | "eslint:recommended", 9 | "plugin:@typescript-eslint/recommended", 10 | "prettier" 11 | ], 12 | "overrides": [], 13 | "parser": "@typescript-eslint/parser", 14 | "parserOptions": { 15 | "ecmaVersion": "latest", 16 | "sourceType": "module" 17 | }, 18 | "plugins": ["@typescript-eslint"], 19 | "rules": { 20 | "@typescript-eslint/ban-ts-comment": ["warn", "allow-with-description"], 21 | "@typescript-eslint/no-unused-vars": "off", 22 | "@typescript-eslint/no-explicit-any": ["off", { "ignoreRestArgs": true }], 23 | "@typescript-eslint/no-non-null-assertion": "off" 24 | }, 25 | "ignorePatterns": [ 26 | "**/builds/**", 27 | "**/dist/**", 28 | "**/node_modules/**", 29 | "**/scripts/**", 30 | "**/*.js", 31 | "**/*.bak" 32 | ] 33 | } 34 | -------------------------------------------------------------------------------- /src/modules/preferenceScript.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../../package.json"; 2 | import { getString } from "../utils/locale"; 3 | import { KeyExampleFactory } from "./examples"; 4 | 5 | export async function registerPrefsScripts(_window: Window) { 6 | // This function is called when the prefs window is opened 7 | // See addon/chrome/content/preferences.xul onpaneload 8 | if (!addon.data.prefs) { 9 | addon.data.prefs = { 10 | window: _window, 11 | columns: [], 12 | rows: [], 13 | }; 14 | } else { 15 | addon.data.prefs.window = _window; 16 | } 17 | bindPrefEvents(); 18 | } 19 | 20 | function bindPrefEvents() { 21 | addon.data 22 | .prefs!.window.document.querySelector( 23 | `#zotero-prefpane-${config.addonRef}-shortcut-enable` 24 | ) 25 | ?.addEventListener("command", (e) => { 26 | KeyExampleFactory.registerRenameShortcuts(); 27 | }); 28 | 29 | addon.data 30 | .prefs!.window.document.querySelector( 31 | `#zotero-prefpane-${config.addonRef}-shortcut-confirm` 32 | ) 33 | ?.addEventListener("command", (e) => { 34 | KeyExampleFactory.registerRenameShortcuts(); 35 | }); 36 | } 37 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { BasicTool } from "zotero-plugin-toolkit/dist/basic"; 2 | import Addon from "./addon"; 3 | import { config } from "../package.json"; 4 | 5 | const basicTool = new BasicTool(); 6 | 7 | if (!basicTool.getGlobal("Zotero")[config.addonInstance]) { 8 | // Set global variables 9 | _globalThis.Zotero = basicTool.getGlobal("Zotero"); 10 | _globalThis.ZoteroPane = basicTool.getGlobal("ZoteroPane"); 11 | _globalThis.Zotero_Tabs = basicTool.getGlobal("Zotero_Tabs"); 12 | _globalThis.window = basicTool.getGlobal("window"); 13 | _globalThis.document = basicTool.getGlobal("document"); 14 | _globalThis.addon = new Addon(); 15 | _globalThis.ztoolkit = addon.data.ztoolkit; 16 | ztoolkit.basicOptions.log.prefix = `[${config.addonName}]`; 17 | ztoolkit.basicOptions.log.disableConsole = addon.data.env === "production"; 18 | ztoolkit.UI.basicOptions.ui.enableElementJSONLog = 19 | addon.data.env === "development"; 20 | ztoolkit.UI.basicOptions.ui.enableElementDOMLog = 21 | addon.data.env === "development"; 22 | ztoolkit.basicOptions.debug.disableDebugBridgePassword = 23 | addon.data.env === "development"; 24 | Zotero[config.addonInstance] = addon; 25 | // Trigger addon hook for initialization 26 | addon.hooks.onStartup(); 27 | } 28 | -------------------------------------------------------------------------------- /src/utils/wait.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Wait until the condition is `true` or timeout. 3 | * The callback is triggered if condition returns `true`. 4 | * @param condition 5 | * @param callback 6 | * @param interval 7 | * @param timeout 8 | */ 9 | export function waitUntil( 10 | condition: () => boolean, 11 | callback: () => void, 12 | interval = 100, 13 | timeout = 10000 14 | ) { 15 | const start = Date.now(); 16 | const intervalId = ztoolkit.getGlobal("setInterval")(() => { 17 | if (condition()) { 18 | ztoolkit.getGlobal("clearInterval")(intervalId); 19 | callback(); 20 | } else if (Date.now() - start > timeout) { 21 | ztoolkit.getGlobal("clearInterval")(intervalId); 22 | } 23 | }, interval); 24 | } 25 | 26 | /** 27 | * Wait async until the condition is `true` or timeout. 28 | * @param condition 29 | * @param interval 30 | * @param timeout 31 | */ 32 | export function waitUtilAsync( 33 | condition: () => boolean, 34 | interval = 100, 35 | timeout = 10000 36 | ) { 37 | return new Promise((resolve, reject) => { 38 | const start = Date.now(); 39 | const intervalId = ztoolkit.getGlobal("setInterval")(() => { 40 | if (condition()) { 41 | ztoolkit.getGlobal("clearInterval")(intervalId); 42 | resolve(); 43 | } else if (Date.now() - start > timeout) { 44 | ztoolkit.getGlobal("clearInterval")(intervalId); 45 | reject(); 46 | } 47 | }, interval); 48 | }); 49 | } 50 | -------------------------------------------------------------------------------- /.vscode/toolkit.code-snippets: -------------------------------------------------------------------------------- 1 | { 2 | "appendElement - full": { 3 | "scope": "javascript,typescript", 4 | "prefix": "appendElement", 5 | "body": [ 6 | "appendElement({", 7 | "\ttag: '${1:div}',", 8 | "\tid: '${2:id}',", 9 | "\tnamespace: '${3:html}',", 10 | "\tclassList: ['${4:class}'],", 11 | "\tstyles: {${5:style}: '$6'},", 12 | "\tproperties: {},", 13 | "\tattributes: {},", 14 | "\t[{ '${7:onload}', (e: Event) => $8, ${9:false} }],", 15 | "\tcheckExistanceParent: ${10:HTMLElement},", 16 | "\tignoreIfExists: ${11:true},", 17 | "\tskipIfExists: ${12:true},", 18 | "\tremoveIfExists: ${13:true},", 19 | "\tcustomCheck: (doc: Document, options: ElementOptions) => ${14:true},", 20 | "\tchildren: [$15]", 21 | "}, ${16:container});" 22 | ] 23 | }, 24 | "appendElement - minimum": { 25 | "scope": "javascript,typescript", 26 | "prefix": "appendElement", 27 | "body": "appendElement({ tag: '$1' }, $2);" 28 | }, 29 | "register Notifier": { 30 | "scope": "javascript,typescript", 31 | "prefix": "registerObserver", 32 | "body": [ 33 | "registerObserver({", 34 | "\t notify: (", 35 | "\t\tevent: _ZoteroTypes.Notifier.Event,", 36 | "\t\ttype: _ZoteroTypes.Notifier.Type,", 37 | "\t\tids: string[],", 38 | "\t\textraData: _ZoteroTypes.anyObj", 39 | "\t) => {", 40 | "\t\t$0", 41 | "\t}", 42 | "});" 43 | ] 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /scripts/reload.mjs: -------------------------------------------------------------------------------- 1 | import { exit, argv } from "process"; 2 | import minimist from "minimist"; 3 | import { execSync } from "child_process"; 4 | import details from "../package.json" assert { type: "json" }; 5 | const { addonID, addonName } = details.config; 6 | const version = details.version; 7 | import cmd from "./zotero-cmd.json" assert { type: "json" }; 8 | const { exec } = cmd; 9 | 10 | // Run node reload.js -h for help 11 | const args = minimist(argv.slice(2)); 12 | 13 | const zoteroPath = exec[args.zotero || args.z || Object.keys(exec)[0]]; 14 | const profile = args.profile || args.p; 15 | const startZotero = `${zoteroPath} --debugger --purgecaches ${ 16 | profile ? `-p ${profile}` : "" 17 | }`; 18 | 19 | const script = ` 20 | (async () => { 21 | Services.obs.notifyObservers(null, "startupcache-invalidate", null); 22 | const { AddonManager } = ChromeUtils.import("resource://gre/modules/AddonManager.jsm"); 23 | const addon = await AddonManager.getAddonByID("${addonID}"); 24 | await addon.reload(); 25 | const progressWindow = new Zotero.ProgressWindow({ closeOnClick: true }); 26 | progressWindow.changeHeadline("${addonName} Hot Reload"); 27 | progressWindow.progress = new progressWindow.ItemProgress( 28 | "chrome://zotero/skin/tick.png", 29 | "VERSION=${version}, BUILD=${new Date().toLocaleString()}. By zotero-plugin-toolkit" 30 | ); 31 | progressWindow.progress.setProgress(100); 32 | progressWindow.show(); 33 | progressWindow.startCloseTimer(5000); 34 | })()`; 35 | 36 | const url = `zotero://ztoolkit-debug/?run=${encodeURIComponent(script)}`; 37 | 38 | const command = `${startZotero} -url "${url}"`; 39 | 40 | execSync(command); 41 | exit(0); 42 | -------------------------------------------------------------------------------- /src/hooks.ts: -------------------------------------------------------------------------------- 1 | import { 2 | BasicExampleFactory, 3 | KeyExampleFactory, 4 | UIExampleFactory, 5 | } from "./modules/examples"; 6 | import { config } from "../package.json"; 7 | import { getString, initLocale } from "./utils/locale"; 8 | import { registerPrefsScripts } from "./modules/preferenceScript"; 9 | import { renameSelectedItems } from "./modules/rename"; 10 | 11 | async function onStartup() { 12 | await Promise.all([ 13 | Zotero.initializationPromise, 14 | Zotero.unlockPromise, 15 | Zotero.uiReadyPromise, 16 | ]); 17 | initLocale(); 18 | ztoolkit.ProgressWindow.setIconURI( 19 | "default", 20 | `chrome://${config.addonRef}/content/icons/favicon.png` 21 | ); 22 | 23 | BasicExampleFactory.registerPrefs(); 24 | KeyExampleFactory.registerRenameShortcuts(); 25 | UIExampleFactory.registerRightClickMenuItemRename(); 26 | } 27 | function onShutdown(): void { 28 | ztoolkit.unregisterAll(); 29 | addon.data.dialog?.window?.close(); 30 | // Remove addon object 31 | addon.data.alive = false; 32 | delete Zotero[config.addonInstance]; 33 | } 34 | 35 | /** 36 | * This function is just an example of dispatcher for Preference UI events. 37 | * Any operations should be placed in a function to keep this funcion clear. 38 | * @param type event type 39 | * @param data event data 40 | */ 41 | async function onPrefsEvent(type: string, data: { [key: string]: any }) { 42 | switch (type) { 43 | case "load": 44 | registerPrefsScripts(data.window); 45 | break; 46 | default: 47 | return; 48 | } 49 | } 50 | 51 | // Add your hooks here. For element click, etc. 52 | // Keep in mind hooks only do dispatch. Don't add code that does real jobs in hooks. 53 | // Otherwise the code would be hard to read and maintian. 54 | 55 | export default { 56 | onStartup, 57 | onShutdown, 58 | onPrefsEvent, 59 | renameSelectedItems, 60 | }; 61 | -------------------------------------------------------------------------------- /src/addon.ts: -------------------------------------------------------------------------------- 1 | import ZoteroToolkit from "zotero-plugin-toolkit/dist/index"; 2 | import { ColumnOptions } from "zotero-plugin-toolkit/dist/helpers/virtualizedTable"; 3 | import hooks from "./hooks"; 4 | 5 | class Addon { 6 | public data: { 7 | alive: boolean; 8 | // Env type, see build.js 9 | env: "development" | "production"; 10 | // ztoolkit: MyToolkit; 11 | ztoolkit: ZoteroToolkit; 12 | locale?: { 13 | current: any; 14 | }; 15 | prefs?: { 16 | window: Window; 17 | columns: Array; 18 | rows: Array<{ [dataKey: string]: string }>; 19 | }; 20 | dialog?: DialogHelper; 21 | }; 22 | // Lifecycle hooks 23 | public hooks: typeof hooks; 24 | // APIs 25 | public api: object; 26 | 27 | constructor() { 28 | this.data = { 29 | alive: true, 30 | env: __env__, 31 | // ztoolkit: new MyToolkit(), 32 | ztoolkit: new ZoteroToolkit(), 33 | }; 34 | this.hooks = hooks; 35 | this.api = {}; 36 | } 37 | } 38 | 39 | /** 40 | * Alternatively, import toolkit modules you use to minify the plugin size. 41 | * 42 | * Steps to replace the default `ztoolkit: ZoteroToolkit` with your `ztoolkit: MyToolkit`: 43 | * 44 | * 1. Uncomment this file's line 30: `ztoolkit: new MyToolkit(),` 45 | * and comment line 31: `ztoolkit: new ZoteroToolkit(),`. 46 | * 2. Uncomment this file's line 10: `ztoolkit: MyToolkit;` in this file 47 | * and comment line 11: `ztoolkit: ZoteroToolkit;`. 48 | * 3. Uncomment `./typing/global.d.ts` line 12: `declare const ztoolkit: import("../src/addon").MyToolkit;` 49 | * and comment line 13: `declare const ztoolkit: import("zotero-plugin-toolkit").ZoteroToolkit;`. 50 | * 51 | * You can now add the modules under the `MyToolkit` class. 52 | */ 53 | 54 | import { BasicTool, unregister } from "zotero-plugin-toolkit/dist/basic"; 55 | import { UITool } from "zotero-plugin-toolkit/dist/tools/ui"; 56 | import { PreferencePaneManager } from "zotero-plugin-toolkit/dist/managers/preferencePane"; 57 | import { DialogHelper } from "zotero-plugin-toolkit/dist/helpers/dialog"; 58 | 59 | export class MyToolkit extends BasicTool { 60 | UI: UITool; 61 | PreferencePane: PreferencePaneManager; 62 | 63 | constructor() { 64 | super(); 65 | this.UI = new UITool(this); 66 | this.PreferencePane = new PreferencePaneManager(this); 67 | } 68 | 69 | unregisterAll() { 70 | unregister(this); 71 | } 72 | } 73 | 74 | export default Addon; 75 | -------------------------------------------------------------------------------- /src/utils/locale.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../../package.json"; 2 | 3 | export { initLocale, getString }; 4 | 5 | /** 6 | * Initialize locale data 7 | */ 8 | function initLocale() { 9 | const l10n = new ( 10 | typeof Localization === "undefined" 11 | ? ztoolkit.getGlobal("Localization") 12 | : Localization 13 | )([`${config.addonRef}-addon.ftl`], true); 14 | addon.data.locale = { 15 | current: l10n, 16 | }; 17 | } 18 | 19 | /** 20 | * Get locale string, see https://firefox-source-docs.mozilla.org/l10n/fluent/tutorial.html#fluent-translation-list-ftl 21 | * @param localString ftl key 22 | * @param options.branch branch name 23 | * @param options.args args 24 | * @example 25 | * ```ftl 26 | * # addon.ftl 27 | * addon-static-example = This is default branch! 28 | * .branch-example = This is a branch under addon-static-example! 29 | * addon-dynamic-example = 30 | { $count -> 31 | [one] I have { $count } apple 32 | *[other] I have { $count } apples 33 | } 34 | * ``` 35 | * ```js 36 | * getString("addon-static-example"); // This is default branch! 37 | * getString("addon-static-example", { branch: "branch-example" }); // This is a branch under addon-static-example! 38 | * getString("addon-dynamic-example", { args: { count: 1 } }); // I have 1 apple 39 | * getString("addon-dynamic-example", { args: { count: 2 } }); // I have 2 apples 40 | * ``` 41 | */ 42 | function getString(localString: string): string; 43 | function getString(localString: string, branch: string): string; 44 | function getString( 45 | localString: string, 46 | options: { branch?: string | undefined; args?: Record } 47 | ): string; 48 | function getString(...inputs: any[]) { 49 | if (inputs.length === 1) { 50 | return _getString(inputs[0]); 51 | } else if (inputs.length === 2) { 52 | if (typeof inputs[1] === "string") { 53 | return _getString(inputs[0], { branch: inputs[1] }); 54 | } else { 55 | return _getString(inputs[0], inputs[1]); 56 | } 57 | } else { 58 | throw new Error("Invalid arguments"); 59 | } 60 | } 61 | 62 | function _getString( 63 | localString: string, 64 | options: { branch?: string | undefined; args?: Record } = {} 65 | ): string { 66 | const { branch, args } = options; 67 | const pattern = addon.data.locale?.current.formatMessagesSync([ 68 | { id: localString, args }, 69 | ])[0]; 70 | if (!pattern) { 71 | return localString; 72 | } 73 | if (branch && pattern.attributes) { 74 | return pattern.attributes[branch] || localString; 75 | } else { 76 | return pattern.value || localString; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "zotero-pdf-rename", 3 | "version": "1.0.0", 4 | "description": "Custom rename pdf", 5 | "config": { 6 | "addonName": "Zotero PDF Rename", 7 | "addonID": "pdfrename@theigrams.com", 8 | "addonRef": "pdfrename", 9 | "addonInstance": "AddonPDFRename", 10 | "prefsPrefix": "extensions.zotero.addonpdfrename", 11 | "releasepage": "https://github.com/Theigrams/zotero-pdf-custom-rename/releases/latest/download/zotero-pdf-rename.xpi", 12 | "updaterdf": "https://raw.githubusercontent.com/Theigrams/zotero-pdf-custom-rename/main/update.json" 13 | }, 14 | "main": "src/index.ts", 15 | "scripts": { 16 | "build-dev": "cross-env NODE_ENV=development node scripts/build.mjs", 17 | "build-prod": "cross-env NODE_ENV=production node scripts/build.mjs", 18 | "build": "concurrently -c auto npm:build-prod npm:tsc", 19 | "tsc": "tsc --noEmit", 20 | "start": "node scripts/start.mjs", 21 | "start-watch": "npm run build-dev && concurrently -c auto npm:start npm:watch", 22 | "stop": "node scripts/stop.mjs", 23 | "restart-dev": "npm run build-dev && npm run stop && npm run start", 24 | "restart-prod": "npm run build-prod && npm run stop && npm run start", 25 | "restart": "npm run restart-dev", 26 | "reload": "npm run build-dev && node scripts/reload.mjs", 27 | "watch": "chokidar \"src/**\" \"addon/**\" -c \"npm run reload\"", 28 | "release": "release-it", 29 | "lint": "prettier --write . && eslint . --ext .ts --fix", 30 | "test": "echo \"Error: no test specified\" && exit 1", 31 | "update-deps": "npm update --save" 32 | }, 33 | "repository": { 34 | "type": "git", 35 | "url": "git+https://github.com/Theigrams/zotero-pdf-custom-rename.git" 36 | }, 37 | "author": "JinZhang", 38 | "license": "AGPL-3.0-or-later", 39 | "bugs": { 40 | "url": "https://github.com/Theigrams/zotero-pdf-custom-rename/issues" 41 | }, 42 | "homepage": "https://github.com/Theigrams/zotero-pdf-custom-rename#readme", 43 | "dependencies": { 44 | "zotero-plugin-toolkit": "^2.1.3" 45 | }, 46 | "devDependencies": { 47 | "@types/node": "^20.1.1", 48 | "@typescript-eslint/eslint-plugin": "^5.59.2", 49 | "@typescript-eslint/parser": "^5.59.2", 50 | "chokidar-cli": "^3.0.0", 51 | "compressing": "^1.9.0", 52 | "concurrently": "^8.0.1", 53 | "cross-env": "^7.0.3", 54 | "esbuild": "^0.18.1", 55 | "eslint": "^8.40.0", 56 | "eslint-config-prettier": "^8.8.0", 57 | "minimist": "^1.2.8", 58 | "prettier": "2.8.8", 59 | "release-it": "^15.10.3", 60 | "replace-in-file": "^6.3.5", 61 | "typescript": "^5.0.4", 62 | "zotero-types": "^1.0.14" 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/modules/examples.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../../package.json"; 2 | import { getString } from "../utils/locale"; 3 | import { renameSelectedItems } from "./rename"; 4 | import { messageWindow } from "./rename"; 5 | 6 | function example( 7 | target: any, 8 | propertyKey: string | symbol, 9 | descriptor: PropertyDescriptor 10 | ) { 11 | const original = descriptor.value; 12 | descriptor.value = function (...args: any) { 13 | try { 14 | ztoolkit.log(`Calling example ${target.name}.${String(propertyKey)}`); 15 | return original.apply(this, args); 16 | } catch (e) { 17 | ztoolkit.log(`Error in example ${target.name}.${String(propertyKey)}`, e); 18 | throw e; 19 | } 20 | }; 21 | return descriptor; 22 | } 23 | 24 | export class BasicExampleFactory { 25 | @example 26 | static registerPrefs() { 27 | const prefOptions = { 28 | pluginID: config.addonID, 29 | src: rootURI + "chrome/content/preferences.xhtml", 30 | label: getString("prefs-title"), 31 | image: `chrome://${config.addonRef}/content/icons/favicon.png`, 32 | defaultXUL: true, 33 | }; 34 | ztoolkit.PreferencePane.register(prefOptions); 35 | } 36 | } 37 | 38 | export class KeyExampleFactory { 39 | @example 40 | static registerRenameShortcuts() { 41 | if (!Zotero.Prefs.get("pdfrename.shortcut.enable")) { 42 | messageWindow(`Shortcut off`, "default"); 43 | ztoolkit.Shortcut.unregisterAll(); 44 | return; 45 | } 46 | ztoolkit.Shortcut.unregisterAll(); 47 | const modSet = Zotero.Prefs.get("pdfrename.shortcut.modifiers")?.toString(); 48 | const keySet = Zotero.Prefs.get("pdfrename.shortcut.key")?.toString(); 49 | messageWindow(`Shortcut on: ${modSet}+${keySet}`, "success"); 50 | ztoolkit.Shortcut.register("event", { 51 | id: `${config.addonRef}-key-rename`, 52 | key: keySet || "D", 53 | modifiers: modSet, 54 | callback: (keyOptions) => { 55 | addon.hooks.renameSelectedItems(); 56 | }, 57 | }); 58 | } 59 | 60 | @example 61 | static exampleShortcutConflictingCallback() { 62 | const conflictingGroups = ztoolkit.Shortcut.checkAllKeyConflicting(); 63 | new ztoolkit.ProgressWindow("Check Key Conflicting") 64 | .createLine({ 65 | text: `${conflictingGroups.length} groups of conflicting keys found. Details are in the debug output/console.`, 66 | }) 67 | .show(-1); 68 | ztoolkit.log( 69 | "Conflicting:", 70 | conflictingGroups, 71 | "All keys:", 72 | ztoolkit.Shortcut.getAll() 73 | ); 74 | } 75 | } 76 | 77 | export class UIExampleFactory { 78 | @example 79 | static registerRightClickMenuItemRename() { 80 | const menuIcon = `chrome://${config.addonRef}/content/icons/favicon@0.5x.png`; 81 | // item menuitem with icon 82 | ztoolkit.Menu.register("item", { 83 | tag: "menuitem", 84 | id: "zotero-itemmenu-renamePDF", 85 | label: getString("menuitem-renamePDF"), 86 | commandListener: (ev) => addon.hooks.renameSelectedItems(), 87 | icon: menuIcon, 88 | }); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /addon/chrome/content/preferences.xhtml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 21 | 22 | 23 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 44 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 68 | 74 | 80 | 81 | 82 | 83 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Zotero PDF Rename 2 | 3 | [![zotero target version](https://img.shields.io/badge/Zotero-7.0.*-green&logo=zotero&logoColor=CC2936)](https://www.zotero.org/support/beta_builds) 4 | [![Latest release](https://img.shields.io/github/v/release/Theigrams/zotero-pdf-custom-rename)](https://github.com/Theigrams/zotero-pdf-custom-rename/releases) 5 | [![code size](https://img.shields.io/github/languages/code-size/Theigrams/zotero-pdf-custom-rename)](#zotero-pdf-custom-rename) 6 | ![Downloads latest release](https://img.shields.io/github/downloads/Theigrams/zotero-pdf-custom-rename/latest/total?color=yellow) 7 | [![License](https://img.shields.io/github/license/Theigrams/zotero-pdf-custom-rename)](https://github.com/Theigrams/zotero-pdf-custom-rename/blob/main/LICENSE) 8 | [![Using Zotero Plugin Template](https://img.shields.io/badge/Using-Zotero%20Plugin%20Template-blue?style=flat-round&logo=github)](https://github.com/windingwind/zotero-plugin-template) 9 | 10 | This is a Zotero plugin that allows you to rename PDF files in your Zotero library using custom rules. 11 | 12 | **Note**: *This plugin only works on **Zotero 7.0** and above*. 13 | 14 | ## Usage 15 | 16 | Select one or more items in your Zotero library and right click to open the context menu. Select `Rename PDF attachments` from the menu. 17 | 18 | image 19 | 20 | Then the PDF files will be renamed according to the custom rules you set in the plugin preferences(not implemented yet). 21 | 22 | ### Default rules 23 | 24 | This plugin will read the journal name and year from the metadata of the item and rename the PDF file as follows: 25 | 26 | ``` 27 | {short journal name}_{year}_{short title}.pdf 28 | ``` 29 | 30 | For example, the PDF file of the item below will be renamed as `TPAMI_2016_Go-ICP.pdf`. 31 | 32 | The `short title` is read from the `Short Title` field of the item. If the `Short Title` field is empty, the plugin will use the `Title` field instead. 33 | 34 | ### Journal tags 35 | 36 | The `short journal name` is generated by selecting the first capital letter of each word in the journal name. For example, `IEEE Transactions on Pattern Analysis and Machine Intelligence` will be converted to `TPAMI`, while `IEEE` will be ignored. 37 | 38 | However, `ACM Transactions on Graphics` will be converted to `TG` rather than `TOG` in current version. This is because the word `on` is ignored in the conversion. 39 | A better method is manually adding the short name of the journal in the `Tags` of the item. 40 | 41 | For example, you can add `Jab/#TOG` to the `Tags` of the item, and the plugin will use `TOG` as the short name of the journal. 42 | 43 | **Note**: the plugin will first read the `Jab/#` tag in the `Tags` as the short name. If there is no `Jab/#` tag, the plugin will automatically extract the short name from the full name of the journal. 44 | 45 | PS: It is recommended to install the plugin [MuiseDestiny/zotero-style](https://github.com/MuiseDestiny/zotero-style) for a better experience. 46 | 47 | Xnip2023-06-22_21-14-44 48 | 49 | ### Short Cut 50 | 51 | Now, we can use `control+D` to rename the PDF files. Moreover, we can customize the short cut in the `Preferences` of Zotero. 52 | 53 | The custom short cut can be a combination of the modifier keys and another key. The modifier keys can be `alt`, `control`, `meta` and `accel`, while another key can be any key on the keyboard. 54 | 55 | The following table shows the corresponding modifier keys on Windows and Mac. 56 | 57 | | modifier | Windows | Mac | 58 | | --------- | ------------------ | --------- | 59 | | `alt` | Alt | ⌥ Option | 60 | | `control` | Ctrl | ⌃ Control | 61 | | `meta` | ❌ *Not supported* | ⌘ Command | 62 | | `accel` | Ctrl | ⌘ Command | 63 | 64 | 65 | ## Future work 66 | 67 | - [x] Add a short cut for the renaming function 68 | - [ ] Preferences panel to allow users to customize the rules. 69 | - [ ] Better way to extract the short name of the journal. 70 | -------------------------------------------------------------------------------- /addon/bootstrap.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Most of this code is from Zotero team's official Make It Red example[1] 3 | * or the Zotero 7 documentation[2]. 4 | * [1] https://github.com/zotero/make-it-red 5 | * [2] https://www.zotero.org/support/dev/zotero_7_for_developers 6 | */ 7 | 8 | if (typeof Zotero == "undefined") { 9 | var Zotero; 10 | } 11 | 12 | var chromeHandle; 13 | 14 | // In Zotero 6, bootstrap methods are called before Zotero is initialized, and using include.js 15 | // to get the Zotero XPCOM service would risk breaking Zotero startup. Instead, wait for the main 16 | // Zotero window to open and get the Zotero object from there. 17 | // 18 | // In Zotero 7, bootstrap methods are not called until Zotero is initialized, and the 'Zotero' is 19 | // automatically made available. 20 | async function waitForZotero() { 21 | if (typeof Zotero != "undefined") { 22 | await Zotero.initializationPromise; 23 | } 24 | 25 | var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); 26 | var windows = Services.wm.getEnumerator("navigator:browser"); 27 | var found = false; 28 | while (windows.hasMoreElements()) { 29 | let win = windows.getNext(); 30 | if (win.Zotero) { 31 | Zotero = win.Zotero; 32 | found = true; 33 | break; 34 | } 35 | } 36 | if (!found) { 37 | await new Promise((resolve) => { 38 | var listener = { 39 | onOpenWindow: function (aWindow) { 40 | // Wait for the window to finish loading 41 | let domWindow = aWindow 42 | .QueryInterface(Ci.nsIInterfaceRequestor) 43 | .getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow); 44 | domWindow.addEventListener( 45 | "load", 46 | function () { 47 | domWindow.removeEventListener("load", arguments.callee, false); 48 | if (domWindow.Zotero) { 49 | Services.wm.removeListener(listener); 50 | Zotero = domWindow.Zotero; 51 | resolve(); 52 | } 53 | }, 54 | false 55 | ); 56 | }, 57 | }; 58 | Services.wm.addListener(listener); 59 | }); 60 | } 61 | await Zotero.initializationPromise; 62 | } 63 | 64 | function install(data, reason) {} 65 | 66 | async function startup({ id, version, resourceURI, rootURI }, reason) { 67 | await waitForZotero(); 68 | 69 | // String 'rootURI' introduced in Zotero 7 70 | if (!rootURI) { 71 | rootURI = resourceURI.spec; 72 | } 73 | 74 | if (Zotero.platformMajorVersion >= 102) { 75 | var aomStartup = Components.classes[ 76 | "@mozilla.org/addons/addon-manager-startup;1" 77 | ].getService(Components.interfaces.amIAddonManagerStartup); 78 | var manifestURI = Services.io.newURI(rootURI + "manifest.json"); 79 | chromeHandle = aomStartup.registerChrome(manifestURI, [ 80 | ["content", "__addonRef__", rootURI + "chrome/content/"], 81 | ]); 82 | } else { 83 | setDefaultPrefs(rootURI); 84 | } 85 | 86 | /** 87 | * Global variables for plugin code. 88 | * The `_globalThis` is the global root variable of the plugin sandbox environment 89 | * and all child variables assigned to it is globally accessible. 90 | * See `src/index.ts` for details. 91 | */ 92 | const ctx = { 93 | rootURI, 94 | }; 95 | ctx._globalThis = ctx; 96 | 97 | Services.scriptloader.loadSubScript( 98 | `${rootURI}/chrome/content/scripts/index.js`, 99 | ctx 100 | ); 101 | } 102 | 103 | function shutdown({ id, version, resourceURI, rootURI }, reason) { 104 | if (reason === APP_SHUTDOWN) { 105 | return; 106 | } 107 | if (typeof Zotero === "undefined") { 108 | Zotero = Components.classes["@zotero.org/Zotero;1"].getService( 109 | Components.interfaces.nsISupports 110 | ).wrappedJSObject; 111 | } 112 | Zotero.__addonInstance__.hooks.onShutdown(); 113 | 114 | Cc["@mozilla.org/intl/stringbundle;1"] 115 | .getService(Components.interfaces.nsIStringBundleService) 116 | .flushBundles(); 117 | 118 | Cu.unload(`${rootURI}/chrome/content/scripts/index.js`); 119 | 120 | if (chromeHandle) { 121 | chromeHandle.destruct(); 122 | chromeHandle = null; 123 | } 124 | } 125 | 126 | function uninstall(data, reason) {} 127 | 128 | // Loads default preferences from defaults/preferences/prefs.js in Zotero 6 129 | function setDefaultPrefs(rootURI) { 130 | var branch = Services.prefs.getDefaultBranch(""); 131 | var obj = { 132 | pref(pref, value) { 133 | switch (typeof value) { 134 | case "boolean": 135 | branch.setBoolPref(pref, value); 136 | break; 137 | case "string": 138 | branch.setStringPref(pref, value); 139 | break; 140 | case "number": 141 | branch.setIntPref(pref, value); 142 | break; 143 | default: 144 | Zotero.logError(`Invalid type '${typeof value}' for pref '${pref}'`); 145 | } 146 | }, 147 | }; 148 | Zotero.getMainWindow().console.log(rootURI + "prefs.js"); 149 | Services.scriptloader.loadSubScript(rootURI + "prefs.js", obj); 150 | } 151 | -------------------------------------------------------------------------------- /scripts/build.mjs: -------------------------------------------------------------------------------- 1 | import { build } from "esbuild"; 2 | import { zip } from "compressing"; 3 | import { join, basename } from "path"; 4 | import { 5 | existsSync, 6 | lstatSync, 7 | writeFileSync, 8 | readFileSync, 9 | mkdirSync, 10 | readdirSync, 11 | rmSync, 12 | renameSync, 13 | } from "fs"; 14 | import { env, exit } from "process"; 15 | import replaceInFile from "replace-in-file"; 16 | const { sync } = replaceInFile; 17 | import details from "../package.json" with { type: "json" }; 18 | const { name, author, description, homepage, version, config } = details; 19 | 20 | function copyFileSync(source, target) { 21 | var targetFile = target; 22 | 23 | // If target is a directory, a new file with the same name will be created 24 | if (existsSync(target)) { 25 | if (lstatSync(target).isDirectory()) { 26 | targetFile = join(target, basename(source)); 27 | } 28 | } 29 | 30 | writeFileSync(targetFile, readFileSync(source)); 31 | } 32 | 33 | function copyFolderRecursiveSync(source, target) { 34 | var files = []; 35 | 36 | // Check if folder needs to be created or integrated 37 | var targetFolder = join(target, basename(source)); 38 | if (!existsSync(targetFolder)) { 39 | mkdirSync(targetFolder); 40 | } 41 | 42 | // Copy 43 | if (lstatSync(source).isDirectory()) { 44 | files = readdirSync(source); 45 | files.forEach(function (file) { 46 | var curSource = join(source, file); 47 | if (lstatSync(curSource).isDirectory()) { 48 | copyFolderRecursiveSync(curSource, targetFolder); 49 | } else { 50 | copyFileSync(curSource, targetFolder); 51 | } 52 | }); 53 | } 54 | } 55 | 56 | function clearFolder(target) { 57 | if (existsSync(target)) { 58 | rmSync(target, { recursive: true, force: true }); 59 | } 60 | 61 | mkdirSync(target, { recursive: true }); 62 | } 63 | 64 | function dateFormat(fmt, date) { 65 | let ret; 66 | const opt = { 67 | "Y+": date.getFullYear().toString(), 68 | "m+": (date.getMonth() + 1).toString(), 69 | "d+": date.getDate().toString(), 70 | "H+": date.getHours().toString(), 71 | "M+": date.getMinutes().toString(), 72 | "S+": date.getSeconds().toString(), 73 | }; 74 | for (let k in opt) { 75 | ret = new RegExp("(" + k + ")").exec(fmt); 76 | if (ret) { 77 | fmt = fmt.replace( 78 | ret[1], 79 | ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0") 80 | ); 81 | } 82 | } 83 | return fmt; 84 | } 85 | 86 | async function main() { 87 | const t = new Date(); 88 | const buildTime = dateFormat("YYYY-mm-dd HH:MM:SS", t); 89 | const buildDir = "builds"; 90 | 91 | console.log( 92 | `[Build] BUILD_DIR=${buildDir}, VERSION=${version}, BUILD_TIME=${buildTime}, ENV=${[ 93 | env.NODE_ENV, 94 | ]}` 95 | ); 96 | 97 | clearFolder(buildDir); 98 | 99 | copyFolderRecursiveSync("addon", buildDir); 100 | 101 | copyFileSync("update-template.json", "update.json"); 102 | 103 | await build({ 104 | entryPoints: ["src/index.ts"], 105 | define: { 106 | __env__: `"${env.NODE_ENV}"`, 107 | }, 108 | bundle: true, 109 | outfile: join(buildDir, "addon/chrome/content/scripts/index.js"), 110 | // Don't turn minify on 111 | // minify: true, 112 | }).catch(() => exit(1)); 113 | 114 | console.log("[Build] Run esbuild OK"); 115 | 116 | const replaceFrom = [ 117 | /__author__/g, 118 | /__description__/g, 119 | /__homepage__/g, 120 | /__buildVersion__/g, 121 | /__buildTime__/g, 122 | ]; 123 | 124 | const replaceTo = [author, description, homepage, version, buildTime]; 125 | 126 | replaceFrom.push( 127 | ...Object.keys(config).map((k) => new RegExp(`__${k}__`, "g")) 128 | ); 129 | replaceTo.push(...Object.values(config)); 130 | 131 | const optionsAddon = { 132 | files: [ 133 | join(buildDir, "**/*.rdf"), 134 | join(buildDir, "**/*.dtd"), 135 | join(buildDir, "**/*.xul"), 136 | join(buildDir, "**/*.xhtml"), 137 | join(buildDir, "**/*.json"), 138 | join(buildDir, "addon/prefs.js"), 139 | join(buildDir, "addon/chrome.manifest"), 140 | join(buildDir, "addon/manifest.json"), 141 | join(buildDir, "addon/bootstrap.js"), 142 | "update.json", 143 | ], 144 | from: replaceFrom, 145 | to: replaceTo, 146 | countMatches: true, 147 | }; 148 | 149 | const replaceResult = sync(optionsAddon); 150 | console.log( 151 | "[Build] Run replace in ", 152 | replaceResult 153 | .filter((f) => f.hasChanged) 154 | .map((f) => `${f.file} : ${f.numReplacements} / ${f.numMatches}`) 155 | ); 156 | 157 | console.log("[Build] Replace OK"); 158 | 159 | // Walk the builds/addon/locale folder's sub folders and rename *.ftl to addonRef-*.ftl 160 | const localeDir = join(buildDir, "addon/locale"); 161 | const localeFolders = readdirSync(localeDir, { withFileTypes: true }) 162 | .filter((dirent) => dirent.isDirectory()) 163 | .map((dirent) => dirent.name); 164 | 165 | for (const localeSubFolder of localeFolders) { 166 | const localeSubDir = join(localeDir, localeSubFolder); 167 | const localeSubFiles = readdirSync(localeSubDir, { 168 | withFileTypes: true, 169 | }) 170 | .filter((dirent) => dirent.isFile()) 171 | .map((dirent) => dirent.name); 172 | 173 | for (const localeSubFile of localeSubFiles) { 174 | if (localeSubFile.endsWith(".ftl")) { 175 | renameSync( 176 | join(localeSubDir, localeSubFile), 177 | join(localeSubDir, `${config.addonRef}-${localeSubFile}`) 178 | ); 179 | } 180 | } 181 | } 182 | 183 | console.log("[Build] Addon prepare OK"); 184 | 185 | await zip.compressDir( 186 | join(buildDir, "addon"), 187 | join(buildDir, `${name}.xpi`), 188 | { 189 | ignoreBase: true, 190 | } 191 | ); 192 | 193 | console.log("[Build] Addon pack OK"); 194 | console.log( 195 | `[Build] Finished in ${(new Date().getTime() - t.getTime()) / 1000} s.` 196 | ); 197 | } 198 | 199 | main().catch((err) => { 200 | console.log(err); 201 | exit(1); 202 | }); 203 | -------------------------------------------------------------------------------- /src/modules/rename.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../../package.json"; 2 | export { renameSelectedItems, messageWindow }; 3 | 4 | function messageWindow(info: string, status: string) { 5 | new ztoolkit.ProgressWindow(config.addonName, { 6 | closeOnClick: true, 7 | }) 8 | .createLine({ 9 | text: info, 10 | type: status, 11 | icon: `chrome://${config.addonRef}/content/icons/favicon.png`, 12 | }) 13 | .show(); 14 | } 15 | 16 | async function renameSelectedItems() { 17 | const items = getSelectedItems(); 18 | if (items.length === 0) { 19 | messageWindow("No items selected", "fail"); 20 | return; 21 | } else if (items.length > 1) { 22 | messageWindow(" " + items.length + " items selected", "default"); 23 | } 24 | 25 | for (const item of items) { 26 | const att = getAttachmentFromItem(item); 27 | if (att === -1) { 28 | continue; 29 | } 30 | const newAttName = getAttachmentName(item); 31 | const status = await att.renameAttachmentFile(newAttName); 32 | if (status === true) { 33 | messageWindow(newAttName, "success"); 34 | if (newAttName !== att.getField("title")) { 35 | att.setField("title", newAttName); 36 | att.saveTx(); 37 | } 38 | } else if (status === -1) { 39 | messageWindow("Destination file exists; use force to overwrite.", "fail"); 40 | } else { 41 | messageWindow("Attachment file not found.", "fail"); 42 | } 43 | } 44 | } 45 | 46 | function getSelectedItems() { 47 | let items = Zotero.getActiveZoteroPane().getSelectedItems(); 48 | // get regular items 49 | let itemIds = items 50 | .filter((item) => item.isRegularItem()) 51 | .map((item) => item.id as number); 52 | // get items from attachment 53 | const itemIdsFromAttachment = items 54 | .filter((item) => item.isAttachment()) 55 | .map((item) => item.parentItemID as number); 56 | // remove duplicate items 57 | itemIds = itemIds.concat(itemIdsFromAttachment); 58 | itemIds = Zotero.Utilities.arrayUnique(itemIds); 59 | items = itemIds.map((id) => Zotero.Items.get(id)); 60 | return items; 61 | } 62 | 63 | function getAttachmentFromItem(item: Zotero.Item) { 64 | const oldTitle = item.getField("title").toString().slice(0, 10); 65 | const attachmentIDs = item.getAttachments(); 66 | const attachments = attachmentIDs.map((id) => Zotero.Items.get(id)); 67 | 68 | // attachments = attachments.filter(att => att.attachmentLinkMode === Zotero.Attachments.LINK_MODE_LINKED_FILE); 69 | const pdfAttachments = attachments.filter((att) => { 70 | return ( 71 | att.attachmentContentType === "application/pdf" || 72 | (att.attachmentFilename && 73 | att.attachmentFilename.toLowerCase().endsWith(".pdf")) 74 | ); 75 | }); 76 | if (pdfAttachments.length === 0) { 77 | messageWindow("No attachments found for " + oldTitle, "fail"); 78 | return -1; 79 | } else if (pdfAttachments.length > 1) { 80 | messageWindow( 81 | " " + pdfAttachments.length + " attachments found for " + oldTitle, 82 | "default" 83 | ); 84 | } 85 | return pdfAttachments[0]; 86 | } 87 | 88 | function getAttachmentName(item: Zotero.Item) { 89 | const jst = getJournalShortTitle(item); 90 | let shortTitle = item.getField("shortTitle"); 91 | if (!shortTitle) { 92 | shortTitle = item.getField("title"); 93 | } 94 | const year = item.getField("year"); 95 | let newFileName = `${jst}_${year}_${shortTitle}.pdf`; 96 | newFileName = Zotero.Utilities.cleanTags(newFileName); 97 | Zotero.debug("[renamePDF] New file name: " + newFileName); 98 | return newFileName; 99 | } 100 | 101 | function getJournalShortTitle(item: Zotero.Item) { 102 | const tags = item.getTags(); 103 | // Find the tag that contains the journal short title 104 | // For example, the tag might be "Object { tag: "Jab/#IJCV" }" 105 | const journalTag = tags.find((tag) => tag.tag.startsWith("Jab/#")); 106 | let title = ""; 107 | if (journalTag) { 108 | title = journalTag.tag.split("/#")[1]; 109 | Zotero.debug("[renamePDF] Found journal short title from tag: " + title); 110 | } else { 111 | title = generateJournalShortTitle(item); 112 | Zotero.debug("[renamePDF] Generated journal short title: " + title); 113 | if (title !== "") { 114 | item.addTag("Jab/#" + title); 115 | item.saveTx(); 116 | } 117 | } 118 | return title; 119 | } 120 | 121 | function generateJournalShortTitle(item: Zotero.Item) { 122 | let jst = "Pre"; 123 | if (item.itemType === "journalArticle") { 124 | const journalName = item.getField("publicationTitle").toString(); 125 | if (journalName.includes("arXiv")) { 126 | return jst; 127 | } 128 | jst = firstLetterOfEachWord(journalName); 129 | } else if (item.itemType === "conferencePaper") { 130 | const conferenceName = item.getField("conferenceName").toString(); 131 | // use abbreviations in parentheses 132 | const patt = /.*\((.+)\)/; 133 | jst = conferenceName?.match(patt)?.[1] ?? ""; 134 | if (jst === "") { 135 | // use first letter of each word 136 | jst = firstLetterOfEachWord(conferenceName); 137 | } 138 | } else if (item.itemType === "bookSection") { 139 | const bookTitle = item.getField("bookTitle").toString(); 140 | // if bookTitle contains "ECCV" or "ACCV", use it as the journal short title 141 | if (bookTitle.includes("ECCV")) { 142 | jst = "ECCV"; 143 | } else if (bookTitle.includes("ACCV")) { 144 | jst = "ACCV"; 145 | } else { 146 | jst = "Book"; 147 | } 148 | } 149 | return jst; 150 | } 151 | 152 | function firstLetterOfEachWord(str: string) { 153 | if (str === "") { 154 | return "Pre"; 155 | } 156 | // Use each capitalized initial letter of the journal title as an abbreviation 157 | const words = str.split(" "); 158 | // remove lowercase words and "IEEE", "ACM", "The", numbers, etc. 159 | const capitalizedWords = words.filter( 160 | (word) => 161 | word[0] === word[0].toUpperCase() && 162 | word !== "IEEE" && 163 | word !== "ACM" && 164 | word !== "The" && 165 | !word.match(/\d+/) 166 | ); 167 | // use first letter of each word as abbreviation 168 | const jab = capitalizedWords.map((word) => word[0]).join(""); 169 | return jab; 170 | } 171 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------