├── .gitattributes ├── src ├── l10n │ ├── locales │ │ ├── de.ts │ │ ├── test.ts │ │ └── en.ts │ └── locale.ts ├── templating │ ├── PredefinedTemplate.ts │ ├── predefinedTemplates.json │ ├── PredefinedTemplatesSelector.ts │ ├── templateProcessing.ts │ └── TemplateEditor.ts ├── sources │ ├── CalibreSource.ts │ ├── CalibreSourceTypes.ts │ ├── CalibreContentServerTypes.ts │ └── CalibreContentServer.ts ├── settings │ ├── SettingData.ts │ └── SettingTab.ts ├── functions.ts ├── FolderSuggestor.ts ├── modals │ ├── BaseModal.ts │ ├── TextInputPrompt.ts │ ├── BookSuggestModal.ts │ └── BookInfoModal.ts ├── views │ └── BookView.ts ├── styles.scss ├── main.ts └── suggest.ts ├── versions.json ├── .editorconfig ├── .stylelintrc.json ├── .gitignore ├── lefthook.yml ├── manifest.json ├── jest.config.js ├── test ├── locale..ts └── CalibreContentServer.ts ├── .eslintrc.js ├── tsconfig.json ├── .github └── workflows │ ├── ci.yml │ ├── stale.yml │ └── release.yml ├── version-bump.mjs ├── __mocks__ ├── highlights.json ├── obsidian.ts └── books.json ├── package.json ├── esbuild.config.mjs ├── README.md └── LICENCE /.gitattributes: -------------------------------------------------------------------------------- 1 | main.js binary 2 | styles.css binary -------------------------------------------------------------------------------- /src/l10n/locales/de.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | save: "speichern" 3 | } 4 | -------------------------------------------------------------------------------- /versions.json: -------------------------------------------------------------------------------- 1 | { 2 | "0.0.1": "0.12.19", 3 | "0.1.0": "0.13.14" 4 | } -------------------------------------------------------------------------------- /src/l10n/locales/test.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | "testingValue": "Hello World", 3 | testingInserts: "Hello %1 %2", 4 | } 5 | -------------------------------------------------------------------------------- /src/templating/PredefinedTemplate.ts: -------------------------------------------------------------------------------- 1 | 2 | 3 | export interface PredefinedTemplate { 4 | name: string; 5 | content: string; 6 | creator?: string; 7 | } 8 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # top-most EditorConfig file 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | insert_final_newline = true 7 | indent_style = tab 8 | indent_size = 4 9 | tab_width = 4 -------------------------------------------------------------------------------- /.stylelintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["stylelint-config-recommended", "stylelint-config-standard-scss"], 3 | "rules": { 4 | "font-family-no-missing-generic-family-keyword": null, 5 | "no-descending-specificity": null, 6 | "indentation": "tab" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Intellij 2 | *.iml 3 | .idea 4 | 5 | # npm 6 | node_modules 7 | package-lock.json 8 | 9 | # build 10 | # main.js 11 | *.js.map 12 | 13 | # Exclude sourcemaps 14 | *.map 15 | 16 | # obsidian 17 | .nyc_output 18 | coverage 19 | build 20 | -------------------------------------------------------------------------------- /lefthook.yml: -------------------------------------------------------------------------------- 1 | pre-commit: 2 | parallel: true 3 | commands: 4 | lint: 5 | tags: frontend 6 | run: yarn lint 7 | lint-css: 8 | tags: ui 9 | run: yarn lint-css 10 | test: 11 | tags: testing 12 | run: yarn test 13 | -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "calibre-import", 3 | "name": "Calibre Importer", 4 | "version": "0.1.0", 5 | "minAppVersion": "0.13.14", 6 | "description": "Import book metadata from Calibre and read your books in obsidian", 7 | "author": "Johannes Theiner", 8 | "authorUrl": "https://github.com/joethei/", 9 | "isDesktopOnly": false 10 | } 11 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: "ts-jest", 3 | transform: {"\\.ts$": ['ts-jest']}, 4 | collectCoverage: true, 5 | testEnvironment: "jsdom", 6 | moduleDirectories: ["node_modules", "src", "test"], 7 | coverageReporters: ["lcov", "text", "teamcity"], 8 | testResultsProcessor: "jest-teamcity-reporter", 9 | testMatch: ["**/test/**/*.ts"] 10 | }; 11 | -------------------------------------------------------------------------------- /test/locale..ts: -------------------------------------------------------------------------------- 1 | import t from "../src/l10n/locale"; 2 | 3 | describe('translation', function () { 4 | test('returns correct value', function () { 5 | expect(t("testingValue")).toEqual("Hello World"); 6 | }); 7 | test('fallback to default if no value in selected language', function () { 8 | expect(t("save")).toEqual("Save"); 9 | }); 10 | test('inserts', function () { 11 | expect(t('testingInserts', "World", "!")).toEqual("Hello World !"); 12 | }); 13 | }); 14 | -------------------------------------------------------------------------------- /src/sources/CalibreSource.ts: -------------------------------------------------------------------------------- 1 | import {Book, BookManifest} from "./CalibreSourceTypes"; 2 | 3 | export default interface CalibreSource { 4 | 5 | allBooks(): Promise; 6 | 7 | book(id: number): Promise; 8 | 9 | libraryInfo(): Promise; 10 | 11 | manifest(book: Book) : Promise; 12 | 13 | search(query: string): Promise; 14 | 15 | setHostname(hostname: string) : void; 16 | 17 | setLibrary(library: string) : void; 18 | 19 | } 20 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | parser: "@typescript-eslint/parser", 4 | plugins: ["@typescript-eslint"], 5 | extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended"], 6 | rules: { 7 | "@typescript-eslint/no-unused-vars": [ 8 | 2, 9 | { args: "all", argsIgnorePattern: "^_" }, 10 | ], 11 | "no-useless-escape": "off", 12 | "@typescript-eslint/no-explicit-any": "off", 13 | "@typescript-eslint/ban-ts-comment": "off", 14 | "@typescript-eslint/no-var-requires": "off" 15 | }, 16 | }; 17 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "inlineSourceMap": true, 5 | "inlineSources": true, 6 | "module": "ESNext", 7 | "target": "ES2021", 8 | "allowJs": true, 9 | "noImplicitAny": false, 10 | "moduleResolution": "node", 11 | "importHelpers": true, 12 | "lib": [ 13 | "es2021", 14 | "dom" 15 | ], 16 | "allowSyntheticDefaultImports": true 17 | }, 18 | "include": ["src/**/*", "src/*", "**/*.ts"], 19 | "exclude": ["node_modules/*"] 20 | } 21 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | branches: [master] 8 | 9 | jobs: 10 | lint-and-test: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v2 14 | - name: Install modules 15 | run: yarn 16 | - name: Lint 17 | run: yarn run lint 18 | - name: Lint CSS 19 | run: yarn run lint-css 20 | - name: Test 21 | run: yarn run test 22 | -------------------------------------------------------------------------------- /version-bump.mjs: -------------------------------------------------------------------------------- 1 | import { readFileSync, writeFileSync } from "fs"; 2 | 3 | const targetVersion = process.env.npm_package_version; 4 | 5 | // read minAppVersion from manifest.json and bump version to target version 6 | let manifest = JSON.parse(readFileSync("manifest.json", "utf8")); 7 | const { minAppVersion } = manifest; 8 | manifest.version = targetVersion; 9 | writeFileSync("manifest.json", JSON.stringify(manifest, null, "\t")); 10 | 11 | // update versions.json with target version and minAppVersion from manifest.json 12 | let versions = JSON.parse(readFileSync("versions.json", "utf8")); 13 | versions[targetVersion] = minAppVersion; 14 | writeFileSync("versions.json", JSON.stringify(versions, null, "\t")); 15 | -------------------------------------------------------------------------------- /__mocks__/highlights.json: -------------------------------------------------------------------------------- 1 | { 2 | "449:epub": { 3 | "last_read_positions": [], 4 | "annotations_map": { 5 | "highlight": [ 6 | { 7 | "end_cfi": "/2/4/104", 8 | "highlighted_text": "Wissenschaft ist die Suche nach Wahrheit.", 9 | "spine_index": 11, 10 | "spine_name": "OPS/xhtml/08_Chapter02.xhtml", 11 | "start_cfi": "/2/4/102/1:137", 12 | "style": { 13 | "kind": "color", 14 | "type": "builtin", 15 | "which": "yellow" 16 | }, 17 | "timestamp": "2021-12-26T07:10:04.407Z", 18 | "toc_family_titles": [ 19 | "2", 20 | "2.2" 21 | ], 22 | "type": "highlight", 23 | "uuid": "QXcKdXMQERODiavpq9BrDA" 24 | } 25 | ] 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/l10n/locale.ts: -------------------------------------------------------------------------------- 1 | //taken from https://github.com/valentine195/obsidian-leaflet-plugin/blob/master/src/l10n/locale.ts 2 | import en from "./locales/en"; 3 | import de from "./locales/de"; 4 | import test from "./locales/test"; 5 | 6 | /* istanbul ignore next */ 7 | const locale = (window.moment) ? window.moment.locale() : "test"; 8 | 9 | const localeMap: { [k: string]: Partial } = { 10 | en, 11 | de, 12 | test, 13 | }; 14 | 15 | const userLocale = localeMap[locale]; 16 | 17 | export default function t(str: keyof typeof en, ...inserts: string[]): string { 18 | let localeStr = (userLocale && userLocale[str]) ?? en[str]; 19 | 20 | for (let i = 0; i < inserts.length; i++) { 21 | localeStr = localeStr.replace(`%${i + 1}`, inserts[i]); 22 | } 23 | 24 | return localeStr; 25 | } 26 | -------------------------------------------------------------------------------- /src/settings/SettingData.ts: -------------------------------------------------------------------------------- 1 | export interface CalibreSettings{ 2 | server: string, 3 | library: string, 4 | template: string, 5 | saveLocation: string, 6 | saveLocationFolder: string, 7 | askForFilename: boolean, 8 | } 9 | 10 | export const DEFAULT_SETTINGS: CalibreSettings = { 11 | server: "http://localhost:8080", 12 | library: "", 13 | template: "---\n" + 14 | "authors: {% for author in authors %}\n" + 15 | "- {{author}}{% endfor %}\n" + 16 | "---\n" + 17 | "\n" + 18 | "![cover|250]({{cover}})\n" + 19 | "\n" + 20 | "# {{title}}\n" + 21 | "\n" + 22 | "---\n" + 23 | "{{description}}\n" + 24 | "\n" + 25 | "\n" + 26 | "## Highlights\n" + 27 | "{% for highlight in highlights %} -{{highlight.highlighted_text}}{% endfor %}", 28 | saveLocation: "default", 29 | saveLocationFolder: "", 30 | askForFilename: true, 31 | }; 32 | -------------------------------------------------------------------------------- /src/functions.ts: -------------------------------------------------------------------------------- 1 | //original taken from: https://davidwalsh.name/javascript-polling 2 | /** 3 | * 4 | * @param fn 5 | * @param timeout 6 | * @param interval 7 | */ 8 | export function poll(fn: () => any, timeout = 2000, interval = 100) : Promise { 9 | const endTime = Number(new Date()) + timeout; 10 | 11 | const checkCondition = function (resolve: (arg0: any) => void, reject: (arg0: Error) => void, ...args) { 12 | // If the condition is met, we're done! 13 | const result = fn(); 14 | if (result) { 15 | resolve(result); 16 | } 17 | // If the condition isn't met but the timeout hasn't elapsed, go again 18 | else if (Number(new Date()) < endTime) { 19 | setTimeout(checkCondition, interval, resolve, reject); 20 | } 21 | // Didn't match and too much time, reject! 22 | else { 23 | reject(new Error('timed out for ' + fn + ': ' + args)); 24 | } 25 | }; 26 | 27 | return new Promise(checkCondition); 28 | } 29 | -------------------------------------------------------------------------------- /src/FolderSuggestor.ts: -------------------------------------------------------------------------------- 1 | // Credits go to Liam's Periodic Notes Plugin: https://github.com/liamcain/obsidian-periodic-notes 2 | 3 | import { TAbstractFile, TFolder } from "obsidian"; 4 | import { TextInputSuggest } from "./suggest"; 5 | 6 | export class FolderSuggest extends TextInputSuggest { 7 | getSuggestions(inputStr: string): TFolder[] { 8 | const abstractFiles = this.app.vault.getAllLoadedFiles(); 9 | const folders: TFolder[] = []; 10 | const lowerCaseInputStr = inputStr.toLowerCase(); 11 | 12 | abstractFiles.forEach((folder: TAbstractFile) => { 13 | if (folder instanceof TFolder && folder.path.toLowerCase().contains(lowerCaseInputStr)) { 14 | folders.push(folder); 15 | } 16 | }); 17 | 18 | return folders; 19 | } 20 | 21 | renderSuggestion(file: TFolder, el: HTMLElement): void { 22 | el.setText(file.path); 23 | } 24 | 25 | selectSuggestion(file: TFolder): void { 26 | this.inputEl.value = file.path; 27 | this.inputEl.trigger("input"); 28 | this.close(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/sources/CalibreSourceTypes.ts: -------------------------------------------------------------------------------- 1 | export interface Book { 2 | id: number; 3 | title: string; 4 | authors: string[]; 5 | tags: string[]; 6 | cover: string; 7 | description?: string; 8 | publisher: string; 9 | series?: string; 10 | published: Date; 11 | last_modified: Date; 12 | languages: string[]; 13 | rating: number; 14 | formats: Format; 15 | main_format: string; 16 | highlights: Highlight[]; 17 | identifiers: Identifiers; 18 | custom: CustomMetadata[]; 19 | } 20 | 21 | export interface Format { 22 | [key: string]: string; 23 | } 24 | 25 | export interface CustomMetadata { 26 | name: string; 27 | label: string; 28 | datatype: string; 29 | description: string; 30 | value: string; 31 | } 32 | 33 | export interface BookManifest { 34 | chapter: Chapter; 35 | } 36 | 37 | export interface Identifiers { 38 | [key: string]: string; 39 | } 40 | 41 | 42 | export interface Highlight { 43 | text: string; 44 | timestamp: Date; 45 | type: string; 46 | which: string; 47 | location: string[]; 48 | notes?: string; 49 | 50 | } 51 | 52 | export interface Chapter { 53 | id: number; 54 | title: string; 55 | children: Chapter[]; 56 | level: number; 57 | } 58 | -------------------------------------------------------------------------------- /src/l10n/locales/en.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | //these values are only used in testing, don't overwrite them 3 | testingValue: "", 4 | testingInserts: "", 5 | 6 | 7 | save: "Save", 8 | cancel: "Cancel", 9 | 10 | specify_name: "Please specify a name", 11 | cannot_contain: "cannot contain", 12 | invalid_filename: "The filename you specified is invalid", 13 | note_exists: "A note with that name already exists", 14 | 15 | //settings 16 | file_location: "Default location for new notes", 17 | file_location_help: "Where newly created notes are placed", 18 | file_location_default: "In the default folder", 19 | file_location_custom: "In the folder specified below", 20 | file_location_folder: "Folder to create new notes in", 21 | file_location_folder_help: "newly created booknotes will appear in this folder", 22 | 23 | written_by: "written by: ", 24 | tags: "Tags: ", 25 | rating: "Rating: ", 26 | publisher: "Publisher: ", 27 | publish_date: "Published on: ", 28 | last_modified: "Last modified: ", 29 | series: "Series: ", 30 | languages: "Languages: ", 31 | 32 | create_note: "Create note", 33 | paste_note: "Paste to current note", 34 | 35 | server_offline: "Cannot reach Calibre Content server" 36 | 37 | } 38 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | # This workflow warns and then closes issues and PRs that have had no activity for a specified amount of time. 2 | # 3 | # You can adjust the behavior by modifying this file. 4 | # For more information, see: 5 | # https://github.com/actions/stale 6 | name: Mark stale issues and pull requests 7 | 8 | on: 9 | schedule: 10 | - cron: '32 6 * * *' 11 | 12 | jobs: 13 | stale: 14 | 15 | runs-on: ubuntu-latest 16 | permissions: 17 | issues: write 18 | pull-requests: write 19 | 20 | steps: 21 | - uses: actions/stale@v3 22 | with: 23 | repo-token: ${{ secrets.GITHUB_TOKEN }} 24 | days-before-issue-stale: 30 25 | days-before-issue-close: 14 26 | stale-issue-label: "stale" 27 | stale-issue-message: "This issue is stale because it has been open for 30 days with no activity." 28 | close-issue-message: "This issue was closed because it has been inactive for 14 days since being marked as stale." 29 | any-of-issue-labels: "question" 30 | days-before-pr-stale: -1 31 | days-before-pr-close: -1 32 | -------------------------------------------------------------------------------- /src/templating/predefinedTemplates.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "Simple", 4 | "content": "---\n{%-if rating %}rating: {{rating}}{% endif%}\nauthors: {% for author in authors%}\n- {{author}}\n{%- endfor%}\n---\n\n![cover|250]({{cover}})\n\n# {{title}}\nby {{authors | list }}\n\n---\n{{description}}\n\n{% if highlights.length > 0 %}\n## Highlights\n{% for highlight in highlights %} -{{highlight.highlighted_text}}{% endfor %}\n{% endif %}" 5 | }, 6 | { 7 | "name": "Full Metadata", 8 | "content": "---\ncover: {{cover}}\ncalibreId: {{id}}\n{%if rating %}rating: {{rating}}{% endif%}\nauthors: {% for author in authors%}\n- {{author}}\n{%- endfor%}\n{% if tags.length > 0 -%}\ntags: {% for tag in tags %}\n- {{tag | strip}}\n{%- endfor%}\n{%endif-%}\n{%if published != \"None\" %}published: {{published}} {%endif -%}\n{%if languages.length > 0%}\nlanguages: {%for language in languages %}\n- {{language}}\n{%-endfor%}\n{%-endif-%}\n{% if formats.length > 0 -%}\nformats:\n{%for format in formats-%}\n- {{format}}\n{%- endfor -%}\n{%-endif -%}\n{%- if series -%}series: {{series}}{%- endif%}\n{%- for metadata in custom -%}\n{%if metadata.value !== null %}\n{{metadata.label}}: {{metadata.value}}\n{%- endif%}\n{%- endfor%}\n---\n\n![cover|250]({{cover}})\n\n# {{title}}\n\n---\n{{description}}\n\n{% if highlights.length > 0 %}\n## Highlights\n{% for highlight in highlights %} -{{highlight.text}}\n{% endfor %}\n{% endif %}" 9 | } 10 | ] 11 | -------------------------------------------------------------------------------- /src/modals/BaseModal.ts: -------------------------------------------------------------------------------- 1 | import {AbstractTextComponent, Modal} from "obsidian"; 2 | 3 | export class BaseModal extends Modal { 4 | 5 | //taken from github.com/valentine195/obsidian-admonition 6 | setValidationError(input: AbstractTextComponent, message?: string) : void { 7 | input.inputEl.addClass("is-invalid"); 8 | if (message) { 9 | input.inputEl.parentElement.addClasses([ 10 | "has-invalid-message", 11 | "unset-align-items" 12 | ]); 13 | input.inputEl.parentElement.parentElement.addClass( 14 | ".unset-align-items" 15 | ); 16 | let mDiv = input.inputEl.parentElement.querySelector( 17 | ".invalid-feedback" 18 | ) as HTMLDivElement; 19 | 20 | if (!mDiv) { 21 | mDiv = createDiv({ cls: "invalid-feedback" }); 22 | } 23 | mDiv.innerText = message; 24 | mDiv.insertAfter(input.inputEl); 25 | } 26 | } 27 | 28 | removeValidationError(input: AbstractTextComponent) : void { 29 | input.inputEl.removeClass("is-invalid"); 30 | input.inputEl.parentElement.removeClasses([ 31 | "has-invalid-message", 32 | "unset-align-items" 33 | ]); 34 | input.inputEl.parentElement.parentElement.removeClass( 35 | ".unset-align-items" 36 | ); 37 | 38 | if ( 39 | input.inputEl.parentElement.querySelector(".invalid-feedback") 40 | ) { 41 | input.inputEl.parentElement.removeChild( 42 | input.inputEl.parentElement.querySelector( 43 | ".invalid-feedback" 44 | ) 45 | ); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/views/BookView.ts: -------------------------------------------------------------------------------- 1 | import {ItemView, Platform, WorkspaceLeaf} from "obsidian"; 2 | import {Book} from "../sources/CalibreSourceTypes"; 3 | import CalibrePlugin, {VIEW_ID} from "../main"; 4 | 5 | export class BookView extends ItemView { 6 | 7 | private book: Book; 8 | private plugin: CalibrePlugin; 9 | private format: string; 10 | 11 | constructor(leaf: WorkspaceLeaf, plugin: CalibrePlugin) { 12 | super(leaf); 13 | this.plugin = plugin; 14 | } 15 | 16 | setEphemeralState(state: { book: Book, format: string }) { 17 | this.book = state.book; 18 | this.format = state.format; 19 | 20 | this.contentEl.empty(); 21 | 22 | if(Platform.isDesktop) { 23 | const webview = document.createElement("webview"); 24 | webview.setAttribute("class", "calibre-frame"); 25 | webview.setAttribute('allowpopups', ''); 26 | webview.setAttribute("src", this.book.formats[this.format]); 27 | 28 | this.contentEl.appendChild(webview); 29 | 30 | return; 31 | } 32 | 33 | this.contentEl.createEl("iframe", { 34 | cls: "calibre-frame", attr: { 35 | src: this.book.formats[this.format], 36 | sandbox: "allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts allow-top-navigation-by-user-activation", 37 | allow: "encrypted-media; fullscreen; oversized-images; picture-in-picture; sync-xhr; geolocation;" 38 | } 39 | }); 40 | } 41 | 42 | 43 | getIcon(): string { 44 | return "library"; 45 | } 46 | 47 | getDisplayText(): string { 48 | return "Calibre Book"; 49 | } 50 | 51 | getViewType(): string { 52 | return VIEW_ID; 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "obsidian-calibre", 3 | "version": "0.1.0", 4 | "description": "Import book information from calibre into obsidian", 5 | "main": "main.js", 6 | "scripts": { 7 | "dev": "node esbuild.config.mjs", 8 | "build": "node esbuild.config.mjs production", 9 | "version": "node version-bump.mjs && git add manifest.json versions.json", 10 | "test": "jest", 11 | "lint": "eslint . --ext .ts", 12 | "lint-css": "stylelint src/styles.scss" 13 | }, 14 | "keywords": [], 15 | "author": "Johannes Theiner", 16 | "license": "GPL-3.0", 17 | "devDependencies": { 18 | "@types/node": "16.11.19", 19 | "esbuild": "0.13.15", 20 | "stylelint": "14.5.3", 21 | "eslint": "8.11.0", 22 | "stylelint-config-standard": "25.0.0", 23 | "stylelint-config-standard-scss": "3.0.0", 24 | "@typescript-eslint/eslint-plugin": "5.15.0", 25 | "@typescript-eslint/parser": "5.15.0", 26 | "ts-node": "10.4.0", 27 | "source-map-support": "0.5.21", 28 | "jsdom": "19.0.0", 29 | "@types/jsdom": "16.2.14", 30 | "jsdom-global": "3.0.2", 31 | "sass": "1.49.9", 32 | "css-minify": "2.0.0", 33 | "jest": "27.5.1", 34 | "@types/jest": "27.4.1", 35 | "ts-jest": "27.1.4", 36 | "jest-teamcity-reporter": "0.9.0", 37 | "postcss": "8.4.12", 38 | "autoprefixer": "10.4.4", 39 | "cssnano": "5.1.7", 40 | "cssnano-preset-default": "5.2.7", 41 | "builtin-modules": "3.2.0", 42 | "@arkweid/lefthook": "0.7.7" 43 | }, 44 | "dependencies": { 45 | "obsidian": "0.13.30", 46 | "tslib": "2.3.1", 47 | "typescript": "4.4.4", 48 | "nunjucks": "3.2.3", 49 | "@types/nunjucks": "3.2.1", 50 | "@popperjs/core": "2.11.4" 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/modals/TextInputPrompt.ts: -------------------------------------------------------------------------------- 1 | import {App, Setting, TextComponent} from "obsidian"; 2 | import {BaseModal} from "./BaseModal"; 3 | import t from "../l10n/locale"; 4 | 5 | //slightly modified version from https://github.com/zsviczian/obsidian-excalidraw-plugin 6 | export class TextInputPrompt extends BaseModal { 7 | private resolve: (value: TextComponent) => void; 8 | private textComponent: TextComponent; 9 | private buttonText: string; 10 | 11 | constructor(app: App, private promptText: string, private hint: string, private defaultValue: string, private placeholder: string, buttonText: string = t("save")) { 12 | super(app); 13 | this.buttonText = buttonText; 14 | } 15 | 16 | onOpen(): void { 17 | this.titleEl.setText(this.promptText); 18 | this.createForm(); 19 | } 20 | 21 | onClose(): void { 22 | this.contentEl.empty(); 23 | } 24 | 25 | createForm(): void { 26 | const div = this.contentEl.createDiv(); 27 | 28 | const text = new Setting(div).setName(this.promptText).setDesc(this.hint).addText((textComponent) => { 29 | textComponent 30 | .setValue(this.defaultValue) 31 | .setPlaceholder(this.placeholder) 32 | .onChange(() => { 33 | this.removeValidationError(textComponent); 34 | }) 35 | .inputEl.setAttribute("size", "50"); 36 | this.textComponent = textComponent; 37 | }); 38 | text.controlEl.addClass("calibre-setting-input"); 39 | 40 | new Setting(div).addButton((b) => { 41 | b 42 | .setButtonText(this.buttonText) 43 | .onClick(async () => { 44 | this.resolve(this.textComponent); 45 | }); 46 | return b; 47 | }); 48 | } 49 | 50 | async openAndGetValue(resolve: (value: TextComponent) => void): Promise { 51 | this.resolve = resolve; 52 | await this.open(); 53 | } 54 | } 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /src/styles.scss: -------------------------------------------------------------------------------- 1 | img.calibre-suggest-cover { 2 | height: 10em; 3 | } 4 | 5 | .calibre-suggest-wrapper { 6 | height: 250px; 7 | max-height: 250px; 8 | overflow: hidden; 9 | } 10 | 11 | .calibre-suggest-title { 12 | display: block; 13 | color: var(--interactive-success); 14 | } 15 | 16 | .calibre-suggest-authors { 17 | color: var(--interactive-accent); 18 | } 19 | 20 | .calibre-suggest-cover { 21 | float: right; 22 | } 23 | 24 | .calibre-suggest-text { 25 | float: left; 26 | max-width: 70%; 27 | } 28 | 29 | .calibre-suggest-comments { 30 | overflow: hidden; 31 | text-overflow: ellipsis; 32 | } 33 | 34 | .calibre-modal .data-wrapper .cover { 35 | float: left; 36 | max-width: 30%; 37 | width: 30%; 38 | height: 100%; 39 | } 40 | 41 | .calibre-modal .data-wrapper .metadata { 42 | float: right; 43 | width: 70%; 44 | height: 100%; 45 | 46 | @for $i from 0 through 10 { 47 | .chapters .level-#{$i} { 48 | text-indent: #{$i}em; 49 | padding: 0; 50 | margin: 0; 51 | } 52 | } 53 | } 54 | 55 | .calibre-template-editor .editor-section { 56 | display: flex; 57 | } 58 | 59 | .calibre-template-selector { 60 | display: flex; 61 | flex-wrap: wrap; 62 | justify-content: center; 63 | } 64 | 65 | .calibre-predefined-template { 66 | border: var(--border-size) solid transparent; 67 | background: var(--background-secondary-alt); 68 | padding: 10px; 69 | margin: 5px; 70 | display: flex; 71 | flex-direction: column; 72 | position: relative; 73 | } 74 | 75 | .calibre-predefined-template .is-selected { 76 | background-color: var(--interactive-accent); 77 | } 78 | 79 | .calibre-template-editor .editor-section .template-preview { 80 | display: unset; 81 | } 82 | 83 | .calibre-frame { 84 | position: fixed; 85 | top: 0; 86 | left: 0; 87 | bottom: 0; 88 | right: 0; 89 | width: 100%; 90 | height: 100%; 91 | border: none; 92 | margin: 0; 93 | padding: 0; 94 | overflow: hidden; 95 | z-index: 999999; 96 | } 97 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import {Plugin, WorkspaceLeaf} from "obsidian"; 2 | import {SettingTab} from "./settings/SettingTab"; 3 | import {BookSuggestModal} from "./modals/BookSuggestModal"; 4 | import {CalibreSettings, DEFAULT_SETTINGS} from "./settings/SettingData"; 5 | import CalibreContentServer from "./sources/CalibreContentServer"; 6 | import CalibreSource from "./sources/CalibreSource"; 7 | import {BookView} from "./views/BookView"; 8 | 9 | export const VIEW_ID = "calibre-importer"; 10 | 11 | export default class CalibrePlugin extends Plugin { 12 | settings: CalibreSettings; 13 | 14 | private source: CalibreSource; 15 | getSource() : CalibreSource { 16 | if(!this.source) { 17 | this.source = new CalibreContentServer(this.settings.server, this.settings.library); 18 | } 19 | return this.source; 20 | } 21 | 22 | async onload() { 23 | await this.loadSettings(); 24 | this.addSettingTab(new SettingTab(this.app, this)); 25 | 26 | this.addCommand({ 27 | id: "show-info", 28 | name: "Show book info", 29 | callback: async () => { 30 | new BookSuggestModal(this).open(); 31 | } 32 | }); 33 | 34 | this.registerView(VIEW_ID, (leaf: WorkspaceLeaf) => new BookView(leaf, this)); 35 | } 36 | 37 | onunload() { 38 | console.log("unloading Calibre importer plugin"); 39 | this.app.workspace.detachLeavesOfType(VIEW_ID); 40 | } 41 | 42 | async loadSettings() { 43 | this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); 44 | } 45 | 46 | async saveSettings() { 47 | await this.saveData(this.settings); 48 | this.source.setHostname(this.settings.server); 49 | this.source.setLibrary(this.settings.library); 50 | } 51 | 52 | 53 | async initLeaf(): Promise { 54 | if (this.app.workspace.getLeavesOfType(VIEW_ID).length > 0) { 55 | return; 56 | } 57 | const leaf = this.app.workspace.getRightLeaf(false) 58 | await leaf.setViewState({ 59 | type: VIEW_ID 60 | }); 61 | this.app.workspace.revealLeaf(leaf); 62 | 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /__mocks__/obsidian.ts: -------------------------------------------------------------------------------- 1 | 2 | export interface RequestParam { 3 | url: string; 4 | method?: string; 5 | contentType?: string; 6 | body?: string; 7 | headers?: Record; 8 | } 9 | 10 | export interface RequestUrlResponse { 11 | status: number; 12 | headers: Record; 13 | arrayBuffer: ArrayBuffer; 14 | json: any; 15 | text: string; 16 | } 17 | 18 | export function htmlToMarkdown(html: string): string { 19 | return html; 20 | } 21 | 22 | 23 | export async function requestUrl(request: RequestParam): Promise { 24 | const books = require("./books.json"); 25 | if (request.url === "http://localhost:8080/ajax/library-info") { 26 | return { 27 | arrayBuffer: undefined, 28 | headers: undefined, 29 | json: {"library_map": {"eBooks": "eBooks"}, "default_library": "eBooks"}, 30 | status: 200, 31 | text: "" 32 | } 33 | } 34 | 35 | if(request.url === "http://localhost:8080/ajax/books") { 36 | return { 37 | arrayBuffer: undefined, 38 | headers: undefined, 39 | json: books, 40 | status: 200, 41 | text: "" 42 | } 43 | } 44 | 45 | if(request.url === "http://localhost:8080/ajax/book/449") { 46 | return { 47 | arrayBuffer: undefined, 48 | headers: undefined, 49 | json: books["449"], 50 | status: 200, 51 | text: "" 52 | } 53 | } 54 | 55 | if(request.url === "http://localhost:8080/ajax/book/2") { 56 | return { 57 | arrayBuffer: undefined, 58 | headers: undefined, 59 | json: books["2"], 60 | status: 200, 61 | text: "" 62 | } 63 | } 64 | 65 | if(request.url === "http://localhost:8080/book-get-annotations/eBooks/449-epub") { 66 | const highlights = require("./highlights.json"); 67 | return { 68 | arrayBuffer: undefined, 69 | headers: undefined, 70 | json: highlights, 71 | status: 200, 72 | text: "" 73 | } 74 | } 75 | 76 | return { 77 | status: 404, 78 | json: "not found", 79 | text: "not found", 80 | arrayBuffer: undefined, 81 | headers: undefined 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/templating/PredefinedTemplatesSelector.ts: -------------------------------------------------------------------------------- 1 | import {BaseModal} from "../modals/BaseModal"; 2 | import CalibrePlugin from "../main"; 3 | import {ButtonComponent, MarkdownPreviewView} from "obsidian"; 4 | import {Book} from "../sources/CalibreSourceTypes"; 5 | import {PredefinedTemplate} from "./PredefinedTemplate"; 6 | import {applyTemplate} from "./templateProcessing"; 7 | 8 | export class PredefinedTemplatesSelector extends BaseModal { 9 | 10 | private readonly plugin: CalibrePlugin; 11 | private book: Book; 12 | 13 | template: string; 14 | saved: boolean; 15 | 16 | private resolve: (template: PredefinedTemplate) => void; 17 | 18 | 19 | constructor(plugin: CalibrePlugin, book: Book) { 20 | super(plugin.app); 21 | this.book = book; 22 | this.plugin = plugin; 23 | this.template = plugin.settings.template; 24 | } 25 | 26 | async display(): Promise { 27 | this.modalEl.addClass("calibre-template-selector"); 28 | const {contentEl} = this; 29 | contentEl.empty(); 30 | 31 | const predefinedTemplates: PredefinedTemplate[] = require('./predefinedTemplates.json'); 32 | for (const predefinedTemplate of predefinedTemplates) { 33 | const wrapper = contentEl.createDiv({cls: "calibre-predefined-template-wrapper"}); 34 | wrapper.createEl("h3", {text: predefinedTemplate.name}); 35 | if(predefinedTemplate.creator) { 36 | wrapper.createEl("p", {text: "by " + predefinedTemplate.creator}); 37 | } 38 | const div = wrapper.createDiv({cls: "calibre-predefined-template"}); 39 | 40 | const appliedTemplate = await applyTemplate(this.plugin, this.book, predefinedTemplate.content); 41 | await MarkdownPreviewView.renderMarkdown(appliedTemplate, div, "", this.plugin); 42 | 43 | new ButtonComponent(div) 44 | .setCta() 45 | .setButtonText("Choose") 46 | .onClick(async () => { 47 | this.resolve(predefinedTemplate); 48 | this.close(); 49 | }) 50 | } 51 | 52 | 53 | } 54 | 55 | async onClose(): Promise { 56 | const {contentEl} = this; 57 | contentEl.empty(); 58 | } 59 | 60 | async onOpen(): Promise { 61 | await this.display(); 62 | } 63 | 64 | async openAndGetValue(resolve: (template: PredefinedTemplate) => void): Promise { 65 | this.resolve = resolve; 66 | await this.open(); 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/sources/CalibreContentServerTypes.ts: -------------------------------------------------------------------------------- 1 | export interface CcsBooks { 2 | [key: number]: CcsBook, 3 | } 4 | 5 | export interface CcsBook { 6 | application_id: number; 7 | title: string; 8 | authors: string[]; 9 | tags: string[]; 10 | cover: string; 11 | cover_raw: string; 12 | comments?: string; 13 | thumbnail: string; 14 | publisher: string; 15 | series: string; 16 | pubdate: Date; 17 | last_modified: Date; 18 | languages: string[]; 19 | rating: number, 20 | formats: string[]; 21 | other_formats: CcsFormat; 22 | main_format: CcsFormat; 23 | user_metadata: CcsUserMetadataWrapper; 24 | identifiers: CcsBookIdentifiers; 25 | highlights: CcsHighlight[]; 26 | [key: string]: any; 27 | } 28 | 29 | export interface CcsFormat { 30 | [key: string]: string; 31 | } 32 | 33 | export interface CcsBookIdentifiers { 34 | [key: string]: string; 35 | } 36 | 37 | export interface CcsBookManifest extends CcsAnnotation{ 38 | version: number; 39 | toc: CcsChapter; 40 | metadata: CcsBook; 41 | } 42 | 43 | export interface CcsAnnotations { 44 | [key: string]: CcsAnnotation; 45 | } 46 | 47 | export interface CcsAnnotation { 48 | annotations_map: CcsAnnotationMap; 49 | } 50 | 51 | export interface CcsAnnotationMap { 52 | highlight: CcsHighlight[]; 53 | } 54 | 55 | export interface CcsHighlight { 56 | highlighted_text: string; 57 | type: string; 58 | notes?: string; 59 | timestamp: Date; 60 | spine_index: number; 61 | spine_name: string; 62 | start_cfi: string; 63 | end_cfi: string; 64 | toc_family_titles: string[]; 65 | style: CcsHighlightStyle; 66 | } 67 | 68 | export interface CcsHighlightStyle { 69 | kind: string; 70 | type: string; 71 | which: string; 72 | } 73 | 74 | 75 | export interface CcsChapter { 76 | title: string; 77 | dest: string; 78 | frag: string; 79 | children: CcsChapter[]; 80 | id: number; 81 | } 82 | 83 | export interface CcsUserMetadataWrapper { 84 | [key: string]: CcsUserMetadata; 85 | } 86 | 87 | export interface CcsUserMetadata { 88 | name: string; 89 | label: string; 90 | datatype: string; 91 | display: CcsUserMetadataDisplay; 92 | [key: string]: any; 93 | } 94 | 95 | export interface CcsUserMetadataDisplay { 96 | description: string; 97 | } 98 | 99 | export interface CcsBookSearchResults { 100 | total_num: number; 101 | book_ids: number[]; 102 | } 103 | 104 | export interface CcsLibraryInfo { 105 | library_map: CcsLibrary; 106 | default_library: string; 107 | } 108 | 109 | export interface CcsLibrary { 110 | [key: string]: string; 111 | } 112 | 113 | export const FILE_NAME_REGEX = /["\/<>:|?]/gm; 114 | -------------------------------------------------------------------------------- /esbuild.config.mjs: -------------------------------------------------------------------------------- 1 | import esbuild from "esbuild"; 2 | import fs from 'fs'; 3 | import process from "process"; 4 | import builtins from 'builtin-modules'; 5 | import sass from "sass"; 6 | import autoprefixer from "autoprefixer"; 7 | import postcss from "postcss"; 8 | import cssnano from "cssnano"; 9 | import defaultPreset from "cssnano-preset-default"; 10 | 11 | 12 | const banner = 13 | `/* 14 | THIS IS A GENERATED/BUNDLED FILE BY ESBUILD 15 | if you want to view the source, please visit the github repository of this plugin 16 | https://github.com/joethei/obsidian-calibre 17 | */ 18 | `; 19 | 20 | const prod = (process.argv[2] === 'production'); 21 | 22 | 23 | const copyMinifiedCSS = { 24 | name: 'minify-css', 25 | setup: (build) => { 26 | build.onEnd(async () => { 27 | const {css} = sass.compile('src/styles.scss'); 28 | let result; 29 | if (prod) { 30 | const content = `${banner}\n${css}`; 31 | const preset = defaultPreset({discardComments: false}); 32 | result = await postcss([cssnano({ 33 | preset: preset, 34 | plugins: [ 35 | autoprefixer, 36 | ] 37 | })]).process(content); 38 | } else { 39 | const content = `${banner}\n${css}`; 40 | result = await postcss([autoprefixer]).process(content); 41 | } 42 | 43 | fs.writeFileSync('build/styles.css', result.css, {encoding: 'utf-8'}); 44 | }) 45 | } 46 | } 47 | 48 | const copyManifest = { 49 | name: 'copy-manifest', 50 | setup: (build) => { 51 | build.onEnd(() => { 52 | fs.copyFileSync('manifest.json', 'build/manifest.json'); 53 | }); 54 | }, 55 | }; 56 | 57 | esbuild.build({ 58 | banner: { 59 | js: banner, 60 | }, 61 | entryPoints: ['src/main.ts'], 62 | bundle: true, 63 | external: [ 64 | 'obsidian', 65 | 'electron', 66 | '@codemirror/autocomplete', 67 | '@codemirror/closebrackets', 68 | '@codemirror/collab', 69 | '@codemirror/commands', 70 | '@codemirror/comment', 71 | '@codemirror/fold', 72 | '@codemirror/gutter', 73 | '@codemirror/highlight', 74 | '@codemirror/history', 75 | '@codemirror/language', 76 | '@codemirror/lint', 77 | '@codemirror/matchbrackets', 78 | '@codemirror/panel', 79 | '@codemirror/rangeset', 80 | '@codemirror/rectangular-selection', 81 | '@codemirror/search', 82 | '@codemirror/state', 83 | '@codemirror/stream-parser', 84 | '@codemirror/text', 85 | '@codemirror/tooltip', 86 | '@codemirror/view', 87 | ...builtins], 88 | format: 'cjs', 89 | watch: !prod, 90 | target: 'es2016', 91 | logLevel: "info", 92 | sourcemap: prod ? false : 'inline', 93 | treeShaking: true, 94 | outfile: 'build/main.js', 95 | plugins: [copyManifest, copyMinifiedCSS] 96 | }).catch(() => process.exit(1)); 97 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Calibre Importer 2 | Plugin for [Obsidian](https://obsidian.md) 3 | 4 | ![GitHub package.json version](https://shields.joethei.xyz/github/package-json/v/joethei/obsidian-calibre) 5 | ![Maintenance](https://shields.joethei.xyz:/maintenance/yes/2022) 6 | ![min app version](https://shields.joethei.xyz/github/manifest-json/minAppVersion/joethei/obsidian-calibre?label=lowest%20supported%20app%20version) 7 | [![libera manifesto](https://shields.joethei.xyz/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com) 8 | --- 9 | 10 | > ⚠️ This plugin is stil in early development, no guarantees on anything. 11 | 12 | > This plugin is not related to the other [Calibre plugin](https://github.com/caronchen/obsidian-calibre-plugin) 13 | 14 | Extract data from your [Calibre](https://calibre-ebook.com/) library, 15 | Read only. 16 | 17 | Read books from your Calibre library directly in Obsidian. 18 | 19 | This plugin requires the use of the [Calibre content server](https://manual.calibre-ebook.com/server.html?highlight=apache) 20 | 21 | Using _calibre-web_ is not supported. 22 | 23 | ![Demo](https://i.joethei.space/Obsidian_aj6b0EURTP.mp4) 24 | 25 | ## Search 26 | 27 | You can make full use of the Search syntax Calibre offers, see the 28 | [Documentation](https://manual.calibre-ebook.com/gui.html#the-search-interface) for more information. 29 | 30 | # Templates 31 | 32 | You have full access to 33 | [Nunjucks](https://mozilla.github.io/nunjucks/templating.html) 34 | 35 | You can find the possible variables [here](https://github.com/joethei/obsidian-calibre/blob/master/src/sources/CalibreSourceTypes.ts)(better documentation will follow). 36 | 37 | There are also some custom filters added: 38 | - `strip`: removes any spaces 39 | 40 | The plugin already provides a few of predefined sample templates 41 | for you to customize. 42 | 43 | ## Annotations 44 | 45 | Calibre does not expose annotation data by default. 46 | You need to enable this in the calibre settings. 47 | 48 | Open a random book with the calibre viewer, then follow these screenshots: 49 | 50 | ![](https://i.joethei.space/calibre_BvvEHQ9coF.png) 51 | ![](https://i.joethei.space/calibre-parallel_Yh9VxFRBCR.png) 52 | ![](https://i.joethei.space/calibre-parallel_65rfGmCxJr.png) 53 | ![](https://i.joethei.space/calibre-parallel_GSdVyCDkqD.png) 54 | 55 | Enable the Keep a copy of annotations/bookmarks in the e-book file option. 56 | If you don't have user accounts configured in calibre put a `*` in the following field. 57 | Put in the username otherwise. 58 | 59 | 60 | # Contributing 61 | ![GitHub Workflow Status](https://shields.joethei.xyz:/github/workflow/status/joethei/obsidian-calibre/CI) 62 | ![GitHub](https://shields.joethei.xyz/github/license/joethei/obsidian-calibre) 63 | ![TeamCity Coverage](https://shields.joethei.xyz:/teamcity/coverage/Obsidian_Plugins_Calibre?server=https%3A%2F%2Fteamcity.joethei.xyz) 64 | 65 | --- 66 | 67 | If you want to contribute your own template you can do so by creating a Pull Request on `src/templating/predefinedTemplates.json` 68 | -------------------------------------------------------------------------------- /__mocks__/books.json: -------------------------------------------------------------------------------- 1 | { 2 | "449": { 3 | "identifiers": { 4 | "isbn": "9783548234106", 5 | "ddc": "820|B" 6 | }, 7 | "user_categories": {}, 8 | "title": "1984 : Roman", 9 | "cover": "/get/cover/449/eBooks", 10 | "user_metadata": { 11 | "#read": { 12 | "name": "Gelesen", 13 | "datatype": "enumeration", 14 | "label": "read", 15 | "display": { 16 | "description": "" 17 | } 18 | }, 19 | "#type": { 20 | "name": "Type", 21 | "label": "type", 22 | "datatype": "enumeration", 23 | "display": { 24 | "enum_values": [ 25 | "eBook", 26 | "PaperBook", 27 | "Magazine" 28 | ], 29 | "enum_colors": [], 30 | "use_decorations": 0, 31 | "description": "Type" 32 | }, 33 | "#value#": "PaperBook" 34 | } 35 | }, 36 | "rating": 4, 37 | "comments": "Der Zukunftsroman 1984 beschreibt einen totalitären Staat", 38 | "timestamp": "2021-12-28T18:47:33+00:00", 39 | "last_modified": "2022-02-14T16:33:51+00:00", 40 | "tags": [ 41 | "Zukunft", 42 | "paper", 43 | "Polizeistaat" 44 | ], 45 | "series": "Orwell", 46 | "uuid": "84cba8a8-ce3a-432d-8a07-2b207e628642", 47 | "publisher": "Ullstein", 48 | "languages": [ 49 | "deu" 50 | ], 51 | "application_id": 449, 52 | "thumbnail": "/get/thumb/449/eBooks", 53 | "pubdate": "1994-12-15T18:48:22+00:00", 54 | "authors": [ 55 | "Orwell, George" 56 | ], 57 | "formats": [ 58 | "epub" 59 | ], 60 | "main_format": { 61 | "epub": "/get..." 62 | }, 63 | "other_formats": {} 64 | }, 65 | "2": { 66 | "identifiers": { 67 | "isbn": "9783548234106", 68 | "ddc": "820|B" 69 | }, 70 | "user_categories": {}, 71 | "title": "1984 : Roman", 72 | "cover": "/get/cover/449/eBooks", 73 | "user_metadata": { 74 | "#read": { 75 | "name": "Gelesen", 76 | "datatype": "enumeration", 77 | "label": "read", 78 | "display": { 79 | "description": "" 80 | } 81 | }, 82 | "#type": { 83 | "name": "Type", 84 | "label": "type", 85 | "datatype": "enumeration", 86 | "display": { 87 | "enum_values": [ 88 | "eBook", 89 | "PaperBook", 90 | "Magazine" 91 | ], 92 | "enum_colors": [], 93 | "use_decorations": 0, 94 | "description": "Type" 95 | }, 96 | "#value#": "PaperBook" 97 | } 98 | }, 99 | "rating": 4, 100 | "comments": "Der Zukunftsroman 1984 beschreibt einen totalitären Staat", 101 | "timestamp": "2021-12-28T18:47:33+00:00", 102 | "last_modified": "2022-02-14T16:33:51+00:00", 103 | "tags": [ 104 | "Zukunft", 105 | "paper", 106 | "Polizeistaat" 107 | ], 108 | "series": "Orwell", 109 | "uuid": "84cba8a8-ce3a-432d-8a07-2b207e628642", 110 | "publisher": "Ullstein", 111 | "languages": [ 112 | "deu" 113 | ], 114 | "application_id": 2, 115 | "thumbnail": "/get/thumb/449/eBooks", 116 | "pubdate": "1994-12-15T18:48:22+00:00", 117 | "authors": [ 118 | "Orwell, George" 119 | ], 120 | "formats": [ 121 | "epub" 122 | ], 123 | "main_format": { 124 | "epub": "/get..." 125 | }, 126 | "other_formats": {} 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /src/modals/BookSuggestModal.ts: -------------------------------------------------------------------------------- 1 | import {debounce, Debouncer, htmlToMarkdown, Instruction, MarkdownRenderer, SuggestModal} from "obsidian"; 2 | import CalibrePlugin from "../main"; 3 | import {createNote, pasteToNote} from "../templating/templateProcessing"; 4 | import {BookInfoModal} from "./BookInfoModal"; 5 | import {Book} from "../sources/CalibreSourceTypes"; 6 | 7 | export class BookSuggestModal extends SuggestModal { 8 | private readonly plugin: CalibrePlugin; 9 | private readonly select: boolean; 10 | 11 | private results: Book[] = []; 12 | private query: string; 13 | 14 | private readonly debouncedSearch: Debouncer<[query: string]>; 15 | 16 | private resolve: (book: Book) => void; 17 | 18 | constructor(plugin: CalibrePlugin, select = false) { 19 | super(plugin.app); 20 | this.plugin = plugin; 21 | this.limit = 25; 22 | this.select = select; 23 | this.debouncedSearch = debounce(this.updateSearchResults, 700); 24 | 25 | this.setPlaceholder("Please search here"); 26 | 27 | if(!select) { 28 | const instructions: Instruction[] = [ 29 | { 30 | command: "Enter", 31 | purpose: "Show information about Book" 32 | }, 33 | { 34 | command: "Shift+Enter", 35 | purpose: "Create note" 36 | } 37 | ]; 38 | 39 | const activeFile = plugin.app.workspace.getActiveFile(); 40 | if (activeFile !== null) { 41 | instructions.push({ 42 | command: "Alt+Enter", 43 | purpose: "Paste to current note" 44 | }); 45 | } 46 | 47 | this.setInstructions(instructions); 48 | } 49 | } 50 | 51 | async updateSearchResults(query: string) { 52 | if(query !== this.query) { 53 | this.query = query; 54 | this.results = await this.plugin.getSource().search(query); 55 | //@ts-ignore 56 | this.updateSuggestions(); 57 | } 58 | } 59 | 60 | 61 | async getSuggestions(query: string): Promise { 62 | this.debouncedSearch(query); 63 | return this.results; 64 | } 65 | 66 | async onChooseSuggestion(item: Book, event: MouseEvent | KeyboardEvent): Promise { 67 | if(this.select) { 68 | this.resolve(item); 69 | return; 70 | } 71 | 72 | if(event.getModifierState("Shift")) { 73 | await createNote(this.plugin, item); 74 | return; 75 | } 76 | if(event.getModifierState("Alt") && this.plugin.app.workspace.getActiveFile()) { 77 | await pasteToNote(this.plugin, item); 78 | return; 79 | } 80 | new BookInfoModal(this.plugin, item).open(); 81 | 82 | } 83 | 84 | async renderSuggestion(value: Book, el: HTMLElement): Promise { 85 | const wrapper = el.createDiv({cls: ["calibre-suggest-wrapper"]}); 86 | const text = wrapper.createDiv({cls: ["calibre-suggest-text"]}); 87 | text.createEl("strong",{ text: value.title, cls: ["calibre-suggest-title"]}); 88 | text.createEl("small", { text: value.authors.join(", "), cls: ["calibre-suggest-authors"]}); 89 | 90 | const comments = text.createEl("div", {cls: ["calibre-suggest-comments"]}); 91 | await MarkdownRenderer.renderMarkdown(htmlToMarkdown(value.description), comments, "", this.plugin); 92 | 93 | const img = wrapper.createDiv({cls: ["calibre-suggest-img"]}); 94 | img.createEl("img", {attr: {src: value.cover, alt: "Cover"}, cls: ["calibre-suggest-cover"]}); 95 | } 96 | 97 | async openAndGetValue(resolve: (book: Book) => void) : Promise { 98 | this.resolve = resolve; 99 | await this.open(); 100 | } 101 | 102 | } 103 | -------------------------------------------------------------------------------- /src/templating/templateProcessing.ts: -------------------------------------------------------------------------------- 1 | import CalibrePlugin from "../main"; 2 | import {MarkdownView, normalizePath, Notice, TextComponent} from "obsidian"; 3 | import {TextInputPrompt} from "../modals/TextInputPrompt"; 4 | import t from "../l10n/locale"; 5 | import {Book} from "../sources/CalibreSourceTypes"; 6 | import {FILE_NAME_REGEX} from "../sources/CalibreContentServerTypes"; 7 | import {Environment} from "nunjucks"; 8 | 9 | export async function pasteToNote(plugin: CalibrePlugin, book: Book) : Promise { 10 | const file = plugin.app.workspace.getActiveFile(); 11 | if (file === null) { 12 | new Notice("no file active"); 13 | return; 14 | } 15 | 16 | const view = plugin.app.workspace.getActiveViewOfType(MarkdownView); 17 | if (view) { 18 | const appliedTemplate = await applyTemplate(plugin, book, plugin.settings.template); 19 | 20 | const editor = view.editor; 21 | 22 | editor.replaceRange(appliedTemplate, editor.getCursor()); 23 | 24 | new Notice("pasted to note"); 25 | } 26 | } 27 | 28 | export async function createNote(plugin: CalibrePlugin, book: Book) : Promise { 29 | const appliedTemplate = await applyTemplate(plugin, book, plugin.settings.template); 30 | const activeFile = plugin.app.workspace.getActiveFile(); 31 | let dir = plugin.app.fileManager.getNewFileParent(activeFile ? activeFile.path : "").path; 32 | 33 | if (plugin.settings.saveLocation === "custom") { 34 | dir = plugin.settings.saveLocationFolder; 35 | } 36 | 37 | //make sure there are no slashes in the title. 38 | const filename = book.title.replace(/[\/\\:]/g, ' '); 39 | 40 | if (plugin.settings.askForFilename) { 41 | const inputPrompt = new TextInputPrompt(plugin.app, t("specify_name"), t("cannot_contain") + " * \" \\ / < > : | ?", filename, filename); 42 | await inputPrompt 43 | .openAndGetValue(async (text: TextComponent) => { 44 | const value = text.getValue(); 45 | if (value.match(FILE_NAME_REGEX)) { 46 | inputPrompt.setValidationError(text, t("invalid_filename")); 47 | return; 48 | } 49 | const filePath = normalizePath([dir, `${value}.md`].join('/')); 50 | 51 | //is there a file with that name already? 52 | if (plugin.app.metadataCache.getFirstLinkpathDest(filePath, '')) { 53 | inputPrompt.setValidationError(text, t("note_exists")); 54 | return; 55 | } 56 | inputPrompt.close(); 57 | await createNewFile(plugin, filePath, appliedTemplate); 58 | }); 59 | } else { 60 | const replacedTitle = filename.replace(FILE_NAME_REGEX, ''); 61 | const filePath = normalizePath([dir, `${replacedTitle}.md`].join('/')); 62 | await createNewFile(plugin, filePath, appliedTemplate); 63 | } 64 | 65 | } 66 | 67 | async function createNewFile(plugin: CalibrePlugin, path: string, content: string) { 68 | const file = await plugin.app.vault.create(path, content); 69 | 70 | await plugin.app.workspace.activeLeaf.openFile(file, { 71 | state: { mode: 'edit' }, 72 | }); 73 | 74 | new Notice("Created note"); 75 | } 76 | 77 | export async function applyTemplate(_: CalibrePlugin, book: Book, template: string, logError = true) : Promise { 78 | const env = new Environment(); 79 | env.addFilter("strip", (str: string) => { 80 | return str.replace(/ /g, ''); 81 | }); 82 | try { 83 | return env.renderString(template, book); 84 | } catch (e: any) { 85 | if(logError) { 86 | console.error(e); 87 | new Notice("Error while processing template, please check the console for more information", 1000); 88 | new Notice(e.message, 1000); 89 | } 90 | } 91 | return ""; 92 | 93 | } 94 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Build plugin 2 | 3 | on: 4 | push: 5 | # Sequence of patterns matched against refs/tags 6 | tags: 7 | - "*" # Push events to matching any tag format, i.e. 1.0, 20.15.10 8 | 9 | env: 10 | PLUGIN_NAME: calibre-import 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: Use Node.js 19 | uses: actions/setup-node@v1 20 | with: 21 | node-version: "14.x" # You might need to adjust this value to your own version 22 | - name: Build 23 | id: build 24 | run: | 25 | npm install -g yarn 26 | yarn 27 | yarn run build 28 | mkdir ${{ env.PLUGIN_NAME }} 29 | cp build/main.js build/manifest.json build/styles.css ${{ env.PLUGIN_NAME }} 30 | zip -r ${{ env.PLUGIN_NAME }}.zip ${{ env.PLUGIN_NAME }} 31 | ls 32 | echo "::set-output name=tag_name::$(git tag --sort version:refname | tail -n 1)" 33 | - name: Create Release 34 | id: create_release 35 | uses: actions/create-release@v1 36 | env: 37 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 38 | VERSION: ${{ github.ref }} 39 | with: 40 | tag_name: ${{ github.ref }} 41 | release_name: ${{ github.ref }} 42 | draft: false 43 | prerelease: false 44 | - name: Upload zip file 45 | id: upload-zip 46 | uses: actions/upload-release-asset@v1 47 | env: 48 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 49 | with: 50 | upload_url: ${{ steps.create_release.outputs.upload_url }} 51 | asset_path: ./${{ env.PLUGIN_NAME }}.zip 52 | asset_name: ${{ env.PLUGIN_NAME }}-${{ steps.build.outputs.tag_name }}.zip 53 | asset_content_type: application/zip 54 | - name: Upload main.js 55 | id: upload-main 56 | uses: actions/upload-release-asset@v1 57 | env: 58 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 59 | with: 60 | upload_url: ${{ steps.create_release.outputs.upload_url }} 61 | asset_path: ./build/main.js 62 | asset_name: main.js 63 | asset_content_type: text/javascript 64 | - name: Upload manifest.json 65 | id: upload-manifest 66 | uses: actions/upload-release-asset@v1 67 | env: 68 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 69 | with: 70 | upload_url: ${{ steps.create_release.outputs.upload_url }} 71 | asset_path: ./build/manifest.json 72 | asset_name: manifest.json 73 | asset_content_type: application/json 74 | - name: Upload styles.scss 75 | id: upload-styles 76 | uses: actions/upload-release-asset@v1 77 | env: 78 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 79 | with: 80 | upload_url: ${{ steps.create_release.outputs.upload_url }} 81 | asset_path: ./build/styles.css 82 | asset_name: styles.css 83 | asset_content_type: text/css 84 | -------------------------------------------------------------------------------- /src/settings/SettingTab.ts: -------------------------------------------------------------------------------- 1 | import {App, debounce, DropdownComponent, Notice, PluginSettingTab, SearchComponent, Setting} from "obsidian"; 2 | import CalibrePlugin from "../main"; 3 | import {FolderSuggest} from "../FolderSuggestor"; 4 | import t from "../l10n/locale"; 5 | import {DEFAULT_SETTINGS} from "./SettingData"; 6 | import {TemplateEditorModal} from "../templating/TemplateEditor"; 7 | 8 | export class SettingTab extends PluginSettingTab { 9 | plugin: CalibrePlugin; 10 | 11 | constructor(app: App, plugin: CalibrePlugin) { 12 | super(app, plugin); 13 | this.plugin = plugin; 14 | } 15 | 16 | debouncedSettingsSave = debounce(async () => { 17 | await this.plugin.saveSettings(); 18 | this.display(); 19 | }, 2000, true); 20 | 21 | display(): void { 22 | const {containerEl} = this; 23 | containerEl.empty(); 24 | 25 | containerEl.createEl("h1", {text: "Calibre Importer"}); 26 | 27 | new Setting(containerEl) 28 | .setName("Server") 29 | .addText(text => { 30 | text 31 | .setValue(this.plugin.settings.server) 32 | .setPlaceholder(DEFAULT_SETTINGS.server) 33 | .onChange(async (value) => { 34 | this.plugin.settings.server = value; 35 | this.debouncedSettingsSave(); 36 | }); 37 | }); 38 | 39 | new Setting(containerEl) 40 | .setName("Library") 41 | .addDropdown(async dropdown => { 42 | const libraries = await this.plugin.getSource().libraryInfo(); 43 | if (libraries === null) { 44 | dropdown.setDisabled(true); 45 | new Notice(t("server_offline")); 46 | return; 47 | } 48 | for (const library of libraries) { 49 | dropdown.addOption(library, library); 50 | } 51 | dropdown 52 | .setValue(this.plugin.settings.library) 53 | .onChange(async (value: string) => { 54 | this.plugin.settings.library = value; 55 | await this.plugin.saveSettings(); 56 | }); 57 | }); 58 | 59 | new Setting(containerEl) 60 | .setName("Template") 61 | .addButton(async (button) => { 62 | button 63 | .setButtonText("Customize") 64 | .onClick(async () => { 65 | const modal = new TemplateEditorModal(this.plugin); 66 | modal.onClose = async() => { 67 | if(modal.saved) { 68 | this.plugin.settings.template = modal.template; 69 | await this.plugin.saveSettings(); 70 | } 71 | } 72 | 73 | modal.open(); 74 | }); 75 | }); 76 | 77 | new Setting(containerEl) 78 | .setName(t("file_location")) 79 | .setDesc(t("file_location_help")) 80 | .addDropdown(async (dropdown: DropdownComponent) => { 81 | dropdown 82 | .addOption("default", t("file_location_default")) 83 | .addOption("custom", t("file_location_custom")) 84 | .setValue(this.plugin.settings.saveLocation) 85 | .onChange(async (value: string) => { 86 | this.plugin.settings.saveLocation = value; 87 | await this.plugin.saveSettings(); 88 | this.display(); 89 | }); 90 | }); 91 | 92 | if (this.plugin.settings.saveLocation == "custom") { 93 | new Setting(containerEl) 94 | .setName(t("file_location_folder")) 95 | .setDesc(t("file_location_folder_help")) 96 | .addSearch(async (search: SearchComponent) => { 97 | new FolderSuggest(this.app, search.inputEl); 98 | search 99 | .setValue(this.plugin.settings.saveLocationFolder) 100 | .setPlaceholder(DEFAULT_SETTINGS.saveLocationFolder) 101 | .onChange(async (value: string) => { 102 | this.plugin.settings.saveLocationFolder = value; 103 | await this.plugin.saveSettings(); 104 | }); 105 | }); 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /test/CalibreContentServer.ts: -------------------------------------------------------------------------------- 1 | import CalibreContentServer from "../src/sources/CalibreContentServer"; 2 | 3 | const books = [{ 4 | authors: ["Orwell, George"], 5 | cover: "http://localhost:8080/get/cover/449/eBooks", 6 | description: "Der Zukunftsroman 1984 beschreibt einen totalitären Staat", 7 | formats: { 8 | "epub": "http://localhost:8080/#book_id=2&fmt=epub&library_id=eBooks&mode=read_book" 9 | }, 10 | main_format: "epub", 11 | highlights: [], 12 | id: 2, 13 | identifiers: { 14 | ddc: "820|B", 15 | isbn: "9783548234106" 16 | }, 17 | languages: ["deu"], 18 | published: "1994-12-15T18:48:22+00:00", 19 | last_modified: "2022-02-14T16:33:51+00:00", 20 | publisher: "Ullstein", 21 | rating: 4, 22 | series: "Orwell", 23 | tags: ["Zukunft", "paper", "Polizeistaat"], 24 | title: "1984 : Roman", 25 | custom: [ 26 | { 27 | datatype: "enumeration", 28 | description: "", 29 | label: "read", 30 | name: "Gelesen", 31 | value: undefined 32 | }, 33 | { 34 | datatype: "enumeration", 35 | description: "Type", 36 | label: "type", 37 | name: "Type", 38 | value: "PaperBook" 39 | } 40 | ] 41 | }, { 42 | authors: ["Orwell, George"], 43 | cover: "http://localhost:8080/get/cover/449/eBooks", 44 | description: "Der Zukunftsroman 1984 beschreibt einen totalitären Staat", 45 | formats: { 46 | "epub": "http://localhost:8080/#book_id=449&fmt=epub&library_id=eBooks&mode=read_book" 47 | }, 48 | highlights: [{ 49 | location: [ 50 | "2", 51 | "2.2" 52 | ], 53 | text: "Wissenschaft ist die Suche nach Wahrheit.", 54 | timestamp: "2021-12-26T07:10:04.407Z", 55 | type: "highlight", 56 | which: "yellow" 57 | }], 58 | id: 449, 59 | identifiers: { 60 | ddc: "820|B", 61 | isbn: "9783548234106" 62 | }, 63 | languages: ["deu"], 64 | published: "1994-12-15T18:48:22+00:00", 65 | last_modified: "2022-02-14T16:33:51+00:00", 66 | publisher: "Ullstein", 67 | rating: 4, 68 | main_format: "epub", 69 | series: "Orwell", 70 | tags: ["Zukunft", "paper", "Polizeistaat"], 71 | title: "1984 : Roman", 72 | custom: [ 73 | { 74 | datatype: "enumeration", 75 | description: "", 76 | label: "read", 77 | name: "Gelesen", 78 | value: undefined 79 | }, 80 | { 81 | datatype: "enumeration", 82 | description: "Type", 83 | label: "type", 84 | name: "Type", 85 | value: "PaperBook" 86 | } 87 | ] 88 | }]; 89 | 90 | let server: CalibreContentServer; 91 | beforeEach(() => { 92 | server = new CalibreContentServer("http://localhost:8080", "eBooks"); 93 | }); 94 | 95 | describe('Library Info', () => { 96 | test('returns valid information if server is reachable', async () => { 97 | expect(await server.libraryInfo()).toEqual(["eBooks"]); 98 | }); 99 | 100 | test('returns null if server is not reachable', async () => { 101 | server.setHostname("http://localhost:8081"); 102 | expect(await server.libraryInfo()).toBeNull(); 103 | }); 104 | 105 | }) 106 | 107 | describe('All Books', () => { 108 | test('returns correct value', async () => { 109 | expect(expect.arrayContaining(await server.allBooks())).toEqual(expect.arrayContaining(books)); 110 | }); 111 | 112 | test('return null when server is unreachable', async () => { 113 | server.setHostname("http://localhost:8081"); 114 | expect(await server.allBooks()).toBeNull(); 115 | }); 116 | }); 117 | 118 | describe('single book', () => { 119 | test('correct value if exists', async () => { 120 | expect(await server.book(449)).toEqual(books[1]); 121 | }); 122 | test('null when book does not exist', async () => { 123 | expect(await server.book(1)).toBeNull(); 124 | }); 125 | }); 126 | 127 | describe('Annotations', () => { 128 | test('null when annotations endpoint ', async () => { 129 | const book = await server.book(2); 130 | expect(book.highlights).toEqual([]); 131 | }); 132 | }); 133 | -------------------------------------------------------------------------------- /src/templating/TemplateEditor.ts: -------------------------------------------------------------------------------- 1 | import {BaseModal} from "../modals/BaseModal"; 2 | import CalibrePlugin from "../main"; 3 | import {MarkdownPreviewView, Setting} from "obsidian"; 4 | import {BookSuggestModal} from "../modals/BookSuggestModal"; 5 | import {applyTemplate} from "./templateProcessing"; 6 | import t from "../l10n/locale"; 7 | import {Book} from "../sources/CalibreSourceTypes"; 8 | import {PredefinedTemplatesSelector} from "./PredefinedTemplatesSelector"; 9 | 10 | export class TemplateEditorModal extends BaseModal { 11 | 12 | private readonly plugin: CalibrePlugin; 13 | private book: Book; 14 | private templatePreview: HTMLDivElement; 15 | 16 | template: string; 17 | saved: boolean; 18 | 19 | 20 | constructor(plugin: CalibrePlugin) { 21 | super(plugin.app); 22 | this.plugin = plugin; 23 | this.template = plugin.settings.template; 24 | } 25 | 26 | async showTemplatePreview(): Promise { 27 | const processed = await applyTemplate(this.plugin, this.book, this.template, false); 28 | this.templatePreview.empty(); 29 | if (processed.length === 0) { 30 | this.templatePreview.createEl("h2", {text: "Could not render template"}); 31 | return; 32 | } 33 | 34 | await MarkdownPreviewView.renderMarkdown(processed, this.templatePreview, "", this.plugin); 35 | } 36 | 37 | async display(): Promise { 38 | this.modalEl.addClass("calibre-template-editor"); 39 | const {contentEl} = this; 40 | contentEl.empty(); 41 | 42 | new Setting(contentEl) 43 | .setName("Select a Book for a preview of the final note") 44 | .setDesc(this.book ? "Currently selected: " + this.book.title : "No selection") 45 | .addButton(async (button) => { 46 | button 47 | .setButtonText("Choose Book") 48 | .onClick(async () => { 49 | const selection = new BookSuggestModal(this.plugin, true); 50 | await selection.openAndGetValue(async (book) => { 51 | this.book = book; 52 | await this.display(); 53 | await this.showTemplatePreview(); 54 | }) 55 | }); 56 | }); 57 | 58 | new Setting(contentEl) 59 | .setName("Predefined Templates") 60 | .setDesc("Choose from a selection of predefined templates") 61 | .setDisabled(!this.book) 62 | .addButton(async (button) => { 63 | button 64 | .setDisabled(!this.book) 65 | .setButtonText("Choose predefined Template") 66 | .onClick(async () => { 67 | const selection = new PredefinedTemplatesSelector(this.plugin, this.book); 68 | await selection.openAndGetValue(async (template) => { 69 | this.template = template.content; 70 | await this.display(); 71 | await this.showTemplatePreview(); 72 | }); 73 | } 74 | ); 75 | }); 76 | 77 | const templateEl = contentEl.createDiv({cls: "editor-section"}); 78 | 79 | new Setting(templateEl) 80 | .addTextArea(async (textArea) => { 81 | textArea 82 | .setValue(this.template) 83 | .onChange(async (value) => { 84 | this.template = value; 85 | if (this.book) { 86 | await this.showTemplatePreview(); 87 | } 88 | }); 89 | textArea.inputEl.setAttr("rows", 100); 90 | textArea.inputEl.setAttr("cols", 60); 91 | }); 92 | 93 | this.templatePreview = templateEl.createDiv({cls: "template-preview"}); 94 | 95 | const footerEl = contentEl.createDiv(); 96 | const footerButtons = new Setting(footerEl); 97 | footerButtons.addButton((b) => { 98 | b.setTooltip(t("save")) 99 | .setIcon("checkmark") 100 | .onClick(async () => { 101 | this.saved = true; 102 | this.close(); 103 | }); 104 | return b; 105 | }); 106 | footerButtons.addExtraButton((b) => { 107 | b.setIcon("cross") 108 | .setTooltip(t("cancel")) 109 | .onClick(() => { 110 | this.saved = false; 111 | this.close(); 112 | }); 113 | return b; 114 | }); 115 | } 116 | 117 | async onClose(): Promise { 118 | const {contentEl} = this; 119 | contentEl.empty(); 120 | } 121 | 122 | async onOpen(): Promise { 123 | await this.display(); 124 | } 125 | 126 | } 127 | -------------------------------------------------------------------------------- /src/modals/BookInfoModal.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ButtonComponent, 3 | htmlToMarkdown, 4 | MarkdownRenderer, 5 | Modal, moment, setIcon, 6 | } from "obsidian"; 7 | import CalibrePlugin, {VIEW_ID} from "../main"; 8 | import t from "../l10n/locale"; 9 | import {Book} from "../sources/CalibreSourceTypes"; 10 | import {createNote, pasteToNote} from "../templating/templateProcessing"; 11 | 12 | export class BookInfoModal extends Modal { 13 | plugin: CalibrePlugin; 14 | book: Book; 15 | 16 | constructor(plugin: CalibrePlugin, book: Book) { 17 | super(plugin.app); 18 | this.plugin = plugin; 19 | this.book = book; 20 | } 21 | 22 | 23 | async display(): Promise { 24 | this.modalEl.addClass("calibre-modal"); 25 | const {contentEl} = this; 26 | contentEl.empty(); 27 | 28 | const topButtons = contentEl.createDiv('topButtons'); 29 | 30 | new ButtonComponent(topButtons) 31 | .setIcon("create-new") 32 | .setTooltip(t("create_note")) 33 | .onClick(async() => { 34 | await createNote(this.plugin, this.book); 35 | }); 36 | 37 | if(this.plugin.app.workspace.getActiveFile()) { 38 | new ButtonComponent(topButtons) 39 | .setIcon("paste") 40 | .setTooltip(t("paste_note")) 41 | .onClick(async() => { 42 | await pasteToNote(this.plugin, this.book); 43 | }); 44 | } 45 | 46 | for (const formatsKey in this.book.formats) { 47 | new ButtonComponent(topButtons) 48 | .setButtonText("open as " + formatsKey.toUpperCase()) 49 | .onClick(async() => { 50 | await this.plugin.initLeaf(); 51 | await this.plugin.app.workspace.getLeavesOfType(VIEW_ID)[0].setEphemeralState({ 52 | book: this.book, 53 | format: formatsKey 54 | }); 55 | this.close(); 56 | }); 57 | } 58 | 59 | contentEl.createEl("h1", {text: this.book.title}); 60 | 61 | const wrapper = contentEl.createDiv({cls: "data-wrapper"}); 62 | 63 | const img = wrapper.createDiv({cls: ["img"]}); 64 | img.createEl("img", {attr: {src: this.book.cover, alt: "Cover"}, cls: ["cover"]}); 65 | 66 | const metadata = wrapper.createDiv({cls: "metadata"}); 67 | 68 | metadata.createEl("strong", {text: t("written_by")}); 69 | metadata.createEl("span", {text: this.book.authors.join(" & ")}); 70 | metadata.createEl("br"); 71 | 72 | metadata.createEl("strong", {text: t("publisher")}); 73 | metadata.createEl("span", {text: this.book.publisher}); 74 | metadata.createEl("br"); 75 | 76 | metadata.createEl("strong", {text: t("publish_date")}); 77 | metadata.createEl("span", {text: moment(this.book.published).format("DD.MM.YYYY")}); 78 | metadata.createEl("br"); 79 | 80 | if (this.book.series) { 81 | metadata.createEl("strong", {text: t("series")}); 82 | metadata.createEl("span", {text: this.book.series}); 83 | metadata.createEl("br"); 84 | } 85 | 86 | metadata.createEl("strong", {text: t("tags")}); 87 | const tagEl = metadata.createSpan("tags"); 88 | this.book.tags.forEach((tag) => { 89 | const tagA = tagEl.createEl("a"); 90 | tagA.setText(tag); 91 | tagA.addClass("tag", "calibre-tag"); 92 | }); 93 | metadata.createEl("br"); 94 | 95 | metadata.createEl("strong", {text: t("rating")}); 96 | const rating = metadata.createSpan(); 97 | for (let i = 0; i < this.book.rating; i++) { 98 | const span = rating.createSpan(); 99 | setIcon(span, "star"); 100 | } 101 | 102 | 103 | for (const custom of this.book.custom) { 104 | const div = metadata.createEl("div"); 105 | if (!custom.value) { 106 | continue; 107 | } 108 | if (custom.description !== "") { 109 | div.createEl("strong", {text: custom.description + ": "}); 110 | } else { 111 | div.createEl("strong", {text: custom.name + ": "}); 112 | } 113 | if (custom.datatype === "bool") { 114 | if (!custom.value) { 115 | const span = div.createSpan(); 116 | setIcon(span, "cross"); 117 | } else { 118 | const span = div.createSpan(); 119 | setIcon(span, "checkmark"); 120 | } 121 | } else { 122 | div.createEl("span", {text: custom.value}); 123 | } 124 | } 125 | 126 | metadata.createEl("hr"); 127 | 128 | if (this.book.description) { 129 | const description = metadata.createDiv( {cls: ["description"]}); 130 | const html = this.book.description.replace(/\n/g, "
"); 131 | const markdown = htmlToMarkdown(html); 132 | await MarkdownRenderer.renderMarkdown(markdown, description, "", this.plugin); 133 | } 134 | 135 | metadata.createEl("hr"); 136 | 137 | metadata.createEl("h3", {text: "Highlights"}); 138 | 139 | const highlightsDiv = metadata.createEl("ul", {cls: ["highlights"]}); 140 | for (const highlight of this.book.highlights) { 141 | const span = highlightsDiv.createEl("li",{text: highlight.text}); 142 | if(highlight.type === "highlight") { 143 | span.style.backgroundColor = highlight.which; 144 | } 145 | if(highlight.type === "builtin") { 146 | span.style.textDecoration = 'underline'; 147 | } 148 | 149 | if(highlight.notes) { 150 | span.title = highlight.notes; 151 | } 152 | } 153 | } 154 | 155 | async onClose(): Promise { 156 | const {contentEl} = this; 157 | contentEl.empty(); 158 | } 159 | 160 | async onOpen(): Promise { 161 | await this.display(); 162 | } 163 | 164 | } 165 | -------------------------------------------------------------------------------- /src/suggest.ts: -------------------------------------------------------------------------------- 1 | // Credits go to Liam's Periodic Notes Plugin: https://github.com/liamcain/obsidian-periodic-notes 2 | 3 | import { App, ISuggestOwner, Scope } from "obsidian"; 4 | import { createPopper, Instance as PopperInstance } from "@popperjs/core"; 5 | 6 | const wrapAround = (value: number, size: number): number => { 7 | return ((value % size) + size) % size; 8 | }; 9 | 10 | class Suggest { 11 | private owner: ISuggestOwner; 12 | private values: T[]; 13 | private suggestions: HTMLDivElement[]; 14 | private selectedItem: number; 15 | private containerEl: HTMLElement; 16 | 17 | constructor( 18 | owner: ISuggestOwner, 19 | containerEl: HTMLElement, 20 | scope: Scope 21 | ) { 22 | this.owner = owner; 23 | this.containerEl = containerEl; 24 | 25 | containerEl.on( 26 | "click", 27 | ".suggestion-item", 28 | this.onSuggestionClick.bind(this) 29 | ); 30 | containerEl.on( 31 | "mousemove", 32 | ".suggestion-item", 33 | this.onSuggestionMouseover.bind(this) 34 | ); 35 | 36 | scope.register([], "ArrowUp", (event) => { 37 | if (!event.isComposing) { 38 | this.setSelectedItem(this.selectedItem - 1, true); 39 | return false; 40 | } 41 | }); 42 | 43 | scope.register([], "ArrowDown", (event) => { 44 | if (!event.isComposing) { 45 | this.setSelectedItem(this.selectedItem + 1, true); 46 | return false; 47 | } 48 | }); 49 | 50 | scope.register([], "Enter", (event) => { 51 | if (!event.isComposing) { 52 | this.useSelectedItem(event); 53 | return false; 54 | } 55 | }); 56 | } 57 | 58 | onSuggestionClick(event: MouseEvent, el: HTMLDivElement): void { 59 | event.preventDefault(); 60 | 61 | const item = this.suggestions.indexOf(el); 62 | this.setSelectedItem(item, false); 63 | this.useSelectedItem(event); 64 | } 65 | 66 | onSuggestionMouseover(_event: MouseEvent, el: HTMLDivElement): void { 67 | const item = this.suggestions.indexOf(el); 68 | this.setSelectedItem(item, false); 69 | } 70 | 71 | setSuggestions(values: T[]) { 72 | this.containerEl.empty(); 73 | const suggestionEls: HTMLDivElement[] = []; 74 | 75 | values.forEach((value) => { 76 | const suggestionEl = this.containerEl.createDiv("suggestion-item"); 77 | this.owner.renderSuggestion(value, suggestionEl); 78 | suggestionEls.push(suggestionEl); 79 | }); 80 | 81 | this.values = values; 82 | this.suggestions = suggestionEls; 83 | this.setSelectedItem(0, false); 84 | } 85 | 86 | useSelectedItem(event: MouseEvent | KeyboardEvent) { 87 | const currentValue = this.values[this.selectedItem]; 88 | if (currentValue) { 89 | this.owner.selectSuggestion(currentValue, event); 90 | } 91 | } 92 | 93 | setSelectedItem(selectedIndex: number, scrollIntoView: boolean) { 94 | const normalizedIndex = wrapAround( 95 | selectedIndex, 96 | this.suggestions.length 97 | ); 98 | const prevSelectedSuggestion = this.suggestions[this.selectedItem]; 99 | const selectedSuggestion = this.suggestions[normalizedIndex]; 100 | 101 | prevSelectedSuggestion?.removeClass("is-selected"); 102 | selectedSuggestion?.addClass("is-selected"); 103 | 104 | this.selectedItem = normalizedIndex; 105 | 106 | if (scrollIntoView) { 107 | selectedSuggestion.scrollIntoView(false); 108 | } 109 | } 110 | } 111 | 112 | export abstract class TextInputSuggest implements ISuggestOwner { 113 | protected app: App; 114 | protected inputEl: HTMLInputElement | HTMLTextAreaElement; 115 | 116 | private popper: PopperInstance; 117 | private scope: Scope; 118 | private suggestEl: HTMLElement; 119 | private suggest: Suggest; 120 | 121 | constructor(app: App, inputEl: HTMLInputElement | HTMLTextAreaElement) { 122 | this.app = app; 123 | this.inputEl = inputEl; 124 | this.scope = new Scope(); 125 | 126 | this.suggestEl = createDiv("suggestion-container"); 127 | const suggestion = this.suggestEl.createDiv("suggestion"); 128 | this.suggest = new Suggest(this, suggestion, this.scope); 129 | 130 | this.scope.register([], "Escape", this.close.bind(this)); 131 | 132 | this.inputEl.addEventListener("input", this.onInputChanged.bind(this)); 133 | this.inputEl.addEventListener("focus", this.onInputChanged.bind(this)); 134 | this.inputEl.addEventListener("blur", this.close.bind(this)); 135 | this.suggestEl.on( 136 | "mousedown", 137 | ".suggestion-container", 138 | (event: MouseEvent) => { 139 | event.preventDefault(); 140 | } 141 | ); 142 | } 143 | 144 | onInputChanged(): void { 145 | const inputStr = this.inputEl.value; 146 | const suggestions = this.getSuggestions(inputStr); 147 | 148 | if (!suggestions) { 149 | this.close(); 150 | return; 151 | } 152 | 153 | if (suggestions.length > 0) { 154 | this.suggest.setSuggestions(suggestions); 155 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 156 | this.open((this.app).dom.appContainerEl, this.inputEl); 157 | } else { 158 | this.close(); 159 | } 160 | } 161 | 162 | open(container: HTMLElement, inputEl: HTMLElement): void { 163 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 164 | (this.app).keymap.pushScope(this.scope); 165 | 166 | container.appendChild(this.suggestEl); 167 | this.popper = createPopper(inputEl, this.suggestEl, { 168 | placement: "bottom-start", 169 | modifiers: [ 170 | { 171 | name: "sameWidth", 172 | enabled: true, 173 | fn: ({ state, instance }) => { 174 | // Note: positioning needs to be calculated twice - 175 | // first pass - positioning it according to the width of the popper 176 | // second pass - position it with the width bound to the reference element 177 | // we need to early exit to avoid an infinite loop 178 | const targetWidth = `${state.rects.reference.width}px`; 179 | if (state.styles.popper.width === targetWidth) { 180 | return; 181 | } 182 | state.styles.popper.width = targetWidth; 183 | instance.update(); 184 | }, 185 | phase: "beforeWrite", 186 | requires: ["computeStyles"], 187 | }, 188 | ], 189 | }); 190 | } 191 | 192 | close(): void { 193 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 194 | (this.app).keymap.popScope(this.scope); 195 | 196 | this.suggest.setSuggestions([]); 197 | if (this.popper) this.popper.destroy(); 198 | this.suggestEl.detach(); 199 | } 200 | 201 | abstract getSuggestions(inputStr: string): T[]; 202 | abstract renderSuggestion(item: T, el: HTMLElement): void; 203 | abstract selectSuggestion(item: T): void; 204 | } 205 | -------------------------------------------------------------------------------- /src/sources/CalibreContentServer.ts: -------------------------------------------------------------------------------- 1 | import { 2 | CcsAnnotations, 3 | CcsBook, 4 | CcsBookManifest, 5 | CcsBooks, 6 | CcsBookSearchResults, CcsChapter, 7 | CcsHighlight, 8 | CcsLibraryInfo 9 | } from "./CalibreContentServerTypes"; 10 | import CalibreSource from "./CalibreSource"; 11 | import {htmlToMarkdown, requestUrl} from "obsidian"; 12 | import {Book, BookManifest, Chapter, CustomMetadata, Format, Highlight} from "./CalibreSourceTypes"; 13 | import {poll} from "../functions"; 14 | 15 | export default class CalibreContentServer implements CalibreSource { 16 | hostname: string; 17 | library: string; 18 | 19 | constructor(hostname: string, library: string) { 20 | this.hostname = hostname; 21 | this.library = library; 22 | } 23 | 24 | setHostname(hostname: string) { 25 | this.hostname = hostname; 26 | } 27 | 28 | setLibrary(library: string) { 29 | this.library = library; 30 | } 31 | 32 | async book(id: number): Promise { 33 | const raw = await requestUrl({url: this.hostname + "/ajax/book/" + id }); 34 | if (raw.status !== 200) { 35 | return null; 36 | } 37 | const rawBook = raw.json as CcsBook; 38 | return this.convertBook(rawBook); 39 | } 40 | 41 | async libraryInfo(): Promise { 42 | const raw = await requestUrl({url: this.hostname + "/ajax/library-info"}); 43 | if (raw.status !== 200) { 44 | return null; 45 | } 46 | const info = raw.json as CcsLibraryInfo; 47 | return Object.keys(info.library_map); 48 | } 49 | 50 | async search(query: string): Promise { 51 | const raw = await requestUrl({url: this.hostname + "/ajax/search/" + this.library + "?query=" + query}); 52 | if (raw.status !== 200) { 53 | return []; 54 | } 55 | const result: Book[] = []; 56 | for (const bookId of (raw.json as CcsBookSearchResults).book_ids) { 57 | const book = await this.book(bookId); 58 | result.push(book); 59 | } 60 | return result; 61 | } 62 | 63 | async manifest(book: Book): Promise { 64 | return poll(async () => { 65 | const raw = await requestUrl({url: this.hostname + "/book-manifest/" + book.id + "/" + book.formats[0]}); 66 | if(raw.status !== 200) return false; 67 | if(raw.json.job_status) return false; 68 | 69 | return raw; 70 | }).then(value => { 71 | const rawManifest = value.json as CcsBookManifest; 72 | if(!rawManifest.toc) return null; 73 | const chapter = this.chapters(rawManifest.toc); 74 | 75 | const manifest: BookManifest = {chapter: chapter}; 76 | return manifest; 77 | 78 | }).catch(value => { 79 | console.error(value); 80 | return null; 81 | }); 82 | } 83 | 84 | private chapters(rawChapter: CcsChapter, level = 0) : Chapter { 85 | const chapter: Chapter = { 86 | children: [], 87 | id: rawChapter.id, 88 | title: rawChapter.title, 89 | level: level 90 | 91 | } 92 | for (const child of rawChapter.children) { 93 | const chapters = this.chapters(child, level + 1); 94 | chapter.children.push(chapters); 95 | } 96 | 97 | return chapter; 98 | } 99 | 100 | async allBooks(): Promise { 101 | const raw = await requestUrl({url: this.hostname + "/ajax/books"}); 102 | if (raw.status !== 200) { 103 | return null; 104 | } 105 | const tmp = raw.json as CcsBooks; 106 | const result: Book[] = []; 107 | for (const resultKey in tmp) { 108 | const book = await this.convertBook(tmp[resultKey]); 109 | if(book) { 110 | result.push(book); 111 | } 112 | } 113 | return result; 114 | } 115 | 116 | async convertBook(rawBook: CcsBook) : Promise { 117 | const customMetadata: CustomMetadata[] = []; 118 | if(!rawBook) { 119 | return null; 120 | } 121 | for (const userMetadataKey in rawBook.user_metadata) { 122 | const element = rawBook.user_metadata[userMetadataKey]; 123 | customMetadata.push({ 124 | datatype: element.datatype, 125 | description: element.display.description, 126 | label: element.label, 127 | name: element.name, 128 | value: element['#value#'] 129 | }); 130 | } 131 | 132 | const formats = rawBook.main_format; 133 | for (const key in rawBook.other_formats) { 134 | formats[key] = rawBook.other_formats[key]; 135 | } 136 | 137 | for (const key in formats) { 138 | formats[key] = this.hostname + "/#book_id=" + rawBook.application_id + "&fmt=" + key + "&library_id=" + this.library + "&mode=read_book"; 139 | } 140 | 141 | return { 142 | authors: rawBook.authors, 143 | cover: this.hostname + rawBook.cover, 144 | description: rawBook.comments ? htmlToMarkdown(rawBook.comments) : "", 145 | formats: formats as Format, 146 | highlights: await this.convertAnnotations(rawBook), 147 | id: rawBook.application_id, 148 | identifiers: rawBook.identifiers, 149 | languages: rawBook.languages, 150 | last_modified: rawBook.last_modified, 151 | published: rawBook.pubdate, 152 | publisher: rawBook.publisher, 153 | rating: rawBook.rating, 154 | series: rawBook.series, 155 | tags: rawBook.tags, 156 | title: rawBook.title, 157 | custom: customMetadata, 158 | main_format: rawBook.main_format ? Object.keys(rawBook.main_format)[0] : "" 159 | }; 160 | } 161 | 162 | async convertAnnotations(rawBook: CcsBook) : Promise { 163 | const result: Highlight[] = []; 164 | const annotations = await this.annotations(rawBook); 165 | if(!annotations) { 166 | return result; 167 | } 168 | for (const annotation of annotations) { 169 | result.push({ 170 | location: annotation.toc_family_titles, 171 | text: annotation.highlighted_text, 172 | timestamp: annotation.timestamp, 173 | type: annotation.type, 174 | which: annotation.style.which, 175 | notes: annotation.notes 176 | 177 | }); 178 | } 179 | 180 | return result.reverse(); 181 | } 182 | 183 | private async annotations(book: CcsBook): Promise { 184 | const highlights: CcsHighlight[] = []; 185 | for (const format of book.formats) { 186 | const raw = await requestUrl({url: this.hostname + "/book-get-annotations/" + this.library + "/" + book.application_id + "-" + format}); 187 | if (raw.status !== 200) { 188 | return null; 189 | } 190 | 191 | const annotations = Object.entries(raw.json as CcsAnnotations); 192 | for (const annotationKey in annotations) { 193 | const annotation = annotations[annotationKey]; 194 | if(annotation[1].annotations_map.highlight) { 195 | highlights.push(...annotation[1].annotations_map.highlight); 196 | } 197 | } 198 | } 199 | 200 | return highlights; 201 | } 202 | 203 | } 204 | 205 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------