├── .eslintrc.js ├── .github └── workflows │ └── Email-Plugin-CI.yml ├── .gitignore ├── .npmignore ├── GENERATOR_DOC.md ├── README.md ├── api ├── Global.d.ts ├── Joplin.d.ts ├── JoplinClipboard.d.ts ├── JoplinCommands.d.ts ├── JoplinContentScripts.d.ts ├── JoplinData.d.ts ├── JoplinFilters.d.ts ├── JoplinInterop.d.ts ├── JoplinPlugins.d.ts ├── JoplinSettings.d.ts ├── JoplinViews.d.ts ├── JoplinViewsDialogs.d.ts ├── JoplinViewsMenuItems.d.ts ├── JoplinViewsMenus.d.ts ├── JoplinViewsPanels.d.ts ├── JoplinViewsToolbarButtons.d.ts ├── JoplinWindow.d.ts ├── JoplinWorkspace.d.ts ├── index.ts └── types.ts ├── jest.config.js ├── package-lock.json ├── package.json ├── plugin.config.json ├── src ├── constants.ts ├── core │ ├── emailConfigure.ts │ ├── emailParser.ts │ ├── emailProviders.ts │ ├── emailSubjectParser.ts │ ├── imap.ts │ ├── postAttachments.ts │ ├── postNote.ts │ └── setupTempFolder.ts ├── index.ts ├── init.ts ├── manifest.json ├── model │ ├── Query.model.ts │ ├── account.model.ts │ ├── attachmentProperties.model.ts │ ├── emailProvider.model.ts │ ├── exportCriteria.model.ts │ ├── exportNote.model.ts │ ├── folder.model.ts │ ├── imapConfig.model.ts │ ├── joplinFolders.model.ts │ ├── joplinTags.model.ts │ ├── message.model.ts │ ├── note.model.ts │ ├── postCriteria.model.ts │ ├── state.model.ts │ ├── subjectMetadata.model.ts │ └── tag.model.ts ├── setting.ts ├── ui │ ├── img │ │ └── icon.webp │ ├── panel.ts │ ├── screens.ts │ ├── style │ │ ├── bootstrap.css │ │ ├── style.css │ │ ├── tagify.css │ │ └── tagify.js │ └── webview.js └── utils │ └── stringOps.ts ├── test ├── emailConfigure.test.ts ├── emailSubjectParser.test.ts └── emailparser.test.ts ├── tsconfig.json └── webpack.config.js /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | 'env': { 3 | 'browser': true, 4 | 'es2021': true, 5 | }, 6 | 'extends': [ 7 | 'google', 8 | ], 9 | 'parser': '@typescript-eslint/parser', 10 | 'parserOptions': { 11 | 'ecmaVersion': 'latest', 12 | 'sourceType': 'module', 13 | }, 14 | 'ignorePatterns': [ 15 | 'node_modules/*', 16 | 'api/*', 17 | 'dist/*', 18 | 'publish/*', 19 | 'webpack.config.js', 20 | 'jest.config.js', 21 | ], 22 | 'plugins': [ 23 | '@typescript-eslint', 24 | ], 25 | 'rules': { 26 | 'max-len': 'off', 27 | 'require-jsdoc': 'off', 28 | 'eqeqeq': ['error', 'always'], 29 | 'indent': ['error', 4], 30 | }, 31 | }; 32 | -------------------------------------------------------------------------------- /.github/workflows/Email-Plugin-CI.yml: -------------------------------------------------------------------------------- 1 | name: Email Plugin Continuous Integration 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | 14 | strategy: 15 | matrix: 16 | node-version: [14.x] 17 | 18 | steps: 19 | - uses: actions/checkout@v3 20 | - name: Use Node.js ${{ matrix.node-version }} 21 | uses: actions/setup-node@v3 22 | with: 23 | node-version: ${{ matrix.node-version }} 24 | cache: 'npm' 25 | - run: npm install 26 | - run: npm test -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | node_modules/ 3 | publish/ 4 | .vscode/ 5 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | *.md 2 | !README.md 3 | /*.jpl 4 | /api 5 | /src 6 | /dist 7 | tsconfig.json 8 | webpack.config.js 9 | -------------------------------------------------------------------------------- /GENERATOR_DOC.md: -------------------------------------------------------------------------------- 1 | # generator-joplin 2 | 3 | Scaffolds out a new Joplin plugin 4 | 5 | ## Installation 6 | 7 | First, install [Yeoman](http://yeoman.io) and generator-joplin using [npm](https://www.npmjs.com/) (we assume you have pre-installed [node.js](https://nodejs.org/)). 8 | 9 | ```bash 10 | npm install -g yo 11 | npm install -g generator-joplin 12 | ``` 13 | 14 | Then generate your new project: 15 | 16 | ```bash 17 | yo joplin 18 | ``` 19 | 20 | ## Development 21 | 22 | To test the generator for development purposes, follow the instructions there: https://yeoman.io/authoring/#running-the-generator 23 | This is a template to create a new Joplin plugin. 24 | 25 | ## Structure 26 | 27 | The main two files you will want to look at are: 28 | 29 | - `/src/index.ts`, which contains the entry point for the plugin source code. 30 | - `/src/manifest.json`, which is the plugin manifest. It contains information such as the plugin a name, version, etc. 31 | 32 | The file `/plugin.config.json` could also be useful if you intend to use [external scripts](#external-script-files), such as content scripts or webview scripts. 33 | 34 | ## Building the plugin 35 | 36 | The plugin is built using Webpack, which creates the compiled code in `/dist`. A JPL archive will also be created at the root, which can use to distribute the plugin. 37 | 38 | To build the plugin, simply run `npm run dist`. 39 | 40 | The project is setup to use TypeScript, although you can change the configuration to use plain JavaScript. 41 | 42 | ## Publishing the plugin 43 | 44 | To publish the plugin, add it to npmjs.com by running `npm publish`. Later on, a script will pick up your plugin and add it automatically to the Joplin plugin repository as long as the package satisfies these conditions: 45 | 46 | - In `package.json`, the name starts with "joplin-plugin-". For example, "joplin-plugin-toc". 47 | - In `package.json`, the keywords include "joplin-plugin". 48 | - In the `publish/` directory, there should be a .jpl and .json file (which are built by `npm run dist`) 49 | 50 | In general all this is done automatically by the plugin generator, which will set the name and keywords of package.json, and will put the right files in the "publish" directory. But if something doesn't work and your plugin doesn't appear in the repository, double-check the above conditions. 51 | 52 | ## Updating the plugin framework 53 | 54 | To update the plugin framework, run `npm run update`. 55 | 56 | In general this command tries to do the right thing - in particular it's going to merge the changes in package.json and .gitignore instead of overwriting. It will also leave "/src" as well as README.md untouched. 57 | 58 | The file that may cause problem is "webpack.config.js" because it's going to be overwritten. For that reason, if you want to change it, consider creating a separate JavaScript file and include it in webpack.config.js. That way, when you update, you only have to restore the line that include your file. 59 | 60 | ## External script files 61 | 62 | By default, the compiler (webpack) is going to compile `src/index.ts` only (as well as any file it imports), and any other file will simply be copied to the plugin package. In some cases this is sufficient, however if you have [content scripts](https://joplinapp.org/api/references/plugin_api/classes/joplincontentscripts.html) or [webview scripts](https://joplinapp.org/api/references/plugin_api/classes/joplinviewspanels.html#addscript) you might want to compile them too, in particular in these two cases: 63 | 64 | - The script is a TypeScript file - in which case it has to be compiled to JavaScript. 65 | 66 | - The script requires modules you've added to package.json. In that case, the script, whether JS or TS, must be compiled so that the dependencies are bundled with the JPL file. 67 | 68 | To get such an external script file to compile, you need to add it to the `extraScripts` array in `plugin.config.json`. The path you add should be relative to /src. For example, if you have a file in "/src/webviews/index.ts", the path should be set to "webviews/index.ts". Once compiled, the file will always be named with a .js extension. So you will get "webviews/index.js" in the plugin package, and that's the path you should use to reference the file. 69 | 70 | ## License 71 | 72 | MIT © Laurent Cozic 73 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

Email Plugin

2 | 3 | This plugin adds the ability to fetch email messages (including attachments) and converts them to Joplin notes in various formats, either by monitoring any `new` or `unread` messages from a specific email address or a specific mailbox, or by uploading downloaded email messages to the plugin without having to be logged in. 4 | 5 | *** 6 | 7 | ## Installing Plugin 8 | 9 | - Open Joplin 10 | - Go to Tools > Options > Plugins 11 | - Search for `Email Plugin` 12 | - Click Install plugin 13 | - Restart Joplin to enable the plugin 14 | 15 | *** 16 | 17 | ## Features 18 | 19 | - Monitoring and fetching any `new` or `unread` messages from a specific email address. 20 | 21 | - Monitoring and fetching any `new` or `unread` messages from a specific mailbox. 22 | 23 | - Send the converted message to specific notebooks and add tags to the note by using `@` or `#` in the email subject or first line of email content and then forward the email to yourself. 24 | 25 | - Convert emails (including attachments) to notes without having to be logged into the plugin. 26 | 27 | - Convert email messages to notes in different formats (`HTML`, `Markdown`, `Text`). 28 | 29 | - Show attachments in different styles, whether they are in the form of a `Table` or `Links`. 30 | 31 | *** 32 | 33 | ## How to use 34 | 35 | - ### Monitoring and fetching from a specific email address 36 | 37 | - Open Email Plugin. 38 | 39 | - Login to the plugin with your email address and password. 40 | 41 | - Enter the email account you want to start fetching and monitoring `new` or `unread` messages from and click on the `Fetching & Monitoring` toggle. 42 | 43 | - If you enter your email address in the `from` field, simply forward the email message to yourself after adding some easy syntax to the end of the email subject, or add this syntax in a new line at the beginning of the message content, and the plugin will handle the rest. 44 | 45 | - **Set a note title** : Change note title by changing the subject of the email. 46 | - **Add to a notebook** : Add `@notebook` to send it to a specific notebook. 47 | - **Add tags** : Add `#tag` to organize the note with a tag. 48 | 49 | > **For example**: Say you want this email located in the **joplin** and **gmail** folders and also want to add **gmail** and **email** as tags to the note. Just edit the email subject or add a new line at the beginning of the message content like this: 50 | >>Email subject: My message @**joplin** @**email** #**gmail** #**email** 51 | 52 | https://user-images.githubusercontent.com/58605547/188909511-479bff3b-bb9c-42da-9d48-a29d8b22fd4b.mp4 53 | 54 | - Otherwise the email messages will be in the `email messages` folder. 55 | 56 | *** 57 | 58 | - ### Monitoring and fetching from a specific mailbox 59 | 60 | - Open Email Plugin. 61 | 62 | - Login to the plugin with your email address and password. 63 | 64 | - Select a specific mailbox and notebook in which you want the email messages to be located and click on the `Fetching & Monitoring Mailbox` toggle. 65 | 66 | *** 67 | 68 | - ### Upload downloaded email messages 69 | 70 | - Open Email Plugin. 71 | 72 | - Click on the `convert saved messages` button. 73 | 74 | - Upload `.eml` format files of email messages that you want to convert to notes. 75 | 76 | - Select a notebook, enter the tags, select the export options, and click on the `convert` button. 77 | 78 | ## Important Notes 79 | 80 | - ⚠️ Make sure the email provider allows login using the original password; otherwise, use the [app password](https://support.google.com/accounts/answer/185833?hl=en#:~:text=Create%20%26%20use%20App%20Passwords). 81 | 82 | - If you want to change the note format, remove attachments from the note, or change the attachments style while monitoring, go to `Tools` > `Email Plugin`. 83 | 84 | - If you mention folders or tags that don't exist in Joplin, they will be created automatically. 85 | 86 | - If you open the email message, the message is no longer `new` or `unread`, but you can easily mark it as unread again. 87 | 88 | ## Building the plugin 89 | 90 | The plugin is built using Webpack, which creates the compiled code in `/dist`. A JPL archive will also be created at the root, which can use to distribute the plugin. 91 | 92 | To build the plugin, simply run `npm run dist`. 93 | 94 | The project is setup to use TypeScript, although you can change the configuration to use plain JavaScript. 95 | 96 | ## Testing 97 | 98 | To test the plugin, simply run `npm test`. The testing library used is [Jest](https://jestjs.io/). 99 | -------------------------------------------------------------------------------- /api/Global.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | import Joplin from './Joplin'; 3 | /** 4 | * @ignore 5 | */ 6 | /** 7 | * @ignore 8 | */ 9 | export default class Global { 10 | private joplin_; 11 | constructor(implementation: any, plugin: Plugin, store: any); 12 | get joplin(): Joplin; 13 | get process(): any; 14 | } 15 | -------------------------------------------------------------------------------- /api/Joplin.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | import JoplinData from './JoplinData'; 3 | import JoplinPlugins from './JoplinPlugins'; 4 | import JoplinWorkspace from './JoplinWorkspace'; 5 | import JoplinFilters from './JoplinFilters'; 6 | import JoplinCommands from './JoplinCommands'; 7 | import JoplinViews from './JoplinViews'; 8 | import JoplinInterop from './JoplinInterop'; 9 | import JoplinSettings from './JoplinSettings'; 10 | import JoplinContentScripts from './JoplinContentScripts'; 11 | import JoplinClipboard from './JoplinClipboard'; 12 | import JoplinWindow from './JoplinWindow'; 13 | /** 14 | * This is the main entry point to the Joplin API. You can access various services using the provided accessors. 15 | * 16 | * The API is now relatively stable and in general maintaining backward compatibility is a top priority, so you shouldn't except much breakages. 17 | * 18 | * If a breaking change ever becomes needed, best effort will be done to: 19 | * 20 | * - Deprecate features instead of removing them, so as to give you time to fix the issue; 21 | * - Document breaking changes in the changelog; 22 | * 23 | * So if you are developing a plugin, please keep an eye on the changelog as everything will be in there with information about how to update your code. 24 | */ 25 | export default class Joplin { 26 | private data_; 27 | private plugins_; 28 | private workspace_; 29 | private filters_; 30 | private commands_; 31 | private views_; 32 | private interop_; 33 | private settings_; 34 | private contentScripts_; 35 | private clipboard_; 36 | private window_; 37 | constructor(implementation: any, plugin: Plugin, store: any); 38 | get data(): JoplinData; 39 | get clipboard(): JoplinClipboard; 40 | get window(): JoplinWindow; 41 | get plugins(): JoplinPlugins; 42 | get workspace(): JoplinWorkspace; 43 | get contentScripts(): JoplinContentScripts; 44 | /** 45 | * @ignore 46 | * 47 | * Not sure if it's the best way to hook into the app 48 | * so for now disable filters. 49 | */ 50 | get filters(): JoplinFilters; 51 | get commands(): JoplinCommands; 52 | get views(): JoplinViews; 53 | get interop(): JoplinInterop; 54 | get settings(): JoplinSettings; 55 | /** 56 | * It is not possible to bundle native packages with a plugin, because they 57 | * need to work cross-platforms. Instead access to certain useful native 58 | * packages is provided using this function. 59 | * 60 | * Currently these packages are available: 61 | * 62 | * - [sqlite3](https://www.npmjs.com/package/sqlite3) 63 | * - [fs-extra](https://www.npmjs.com/package/fs-extra) 64 | * 65 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/nativeModule) 66 | */ 67 | require(_path: string): any; 68 | } 69 | -------------------------------------------------------------------------------- /api/JoplinClipboard.d.ts: -------------------------------------------------------------------------------- 1 | export default class JoplinClipboard { 2 | private electronClipboard_; 3 | private electronNativeImage_; 4 | constructor(electronClipboard: any, electronNativeImage: any); 5 | readText(): Promise; 6 | writeText(text: string): Promise; 7 | readHtml(): Promise; 8 | writeHtml(html: string): Promise; 9 | /** 10 | * Returns the image in [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) format. 11 | */ 12 | readImage(): Promise; 13 | /** 14 | * Takes an image in [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) format. 15 | */ 16 | writeImage(dataUrl: string): Promise; 17 | /** 18 | * Returns the list available formats (mime types). 19 | * 20 | * For example [ 'text/plain', 'text/html' ] 21 | */ 22 | availableFormats(): Promise; 23 | } 24 | -------------------------------------------------------------------------------- /api/JoplinCommands.d.ts: -------------------------------------------------------------------------------- 1 | import { Command } from './types'; 2 | /** 3 | * This class allows executing or registering new Joplin commands. Commands 4 | * can be executed or associated with 5 | * {@link JoplinViewsToolbarButtons | toolbar buttons} or 6 | * {@link JoplinViewsMenuItems | menu items}. 7 | * 8 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/register_command) 9 | * 10 | * ## Executing Joplin's internal commands 11 | * 12 | * It is also possible to execute internal Joplin's commands which, as of 13 | * now, are not well documented. You can find the list directly on GitHub 14 | * though at the following locations: 15 | * 16 | * * [Main screen commands](https://github.com/laurent22/joplin/tree/dev/packages/app-desktop/gui/MainScreen/commands) 17 | * * [Global commands](https://github.com/laurent22/joplin/tree/dev/packages/app-desktop/commands) 18 | * * [Editor commands](https://github.com/laurent22/joplin/tree/dev/packages/app-desktop/gui/NoteEditor/commands/editorCommandDeclarations.ts) 19 | * 20 | * To view what arguments are supported, you can open any of these files 21 | * and look at the `execute()` command. 22 | * 23 | * ## Executing editor commands 24 | * 25 | * There might be a situation where you want to invoke editor commands 26 | * without using a {@link JoplinContentScripts | contentScript}. For this 27 | * reason Joplin provides the built in `editor.execCommand` command. 28 | * 29 | * `editor.execCommand` should work with any core command in both the 30 | * [CodeMirror](https://codemirror.net/doc/manual.html#execCommand) and 31 | * [TinyMCE](https://www.tiny.cloud/docs/api/tinymce/tinymce.editorcommands/#execcommand) editors, 32 | * as well as most functions calls directly on a CodeMirror editor object (extensions). 33 | * 34 | * * [CodeMirror commands](https://codemirror.net/doc/manual.html#commands) 35 | * * [TinyMCE core editor commands](https://www.tiny.cloud/docs/advanced/editor-command-identifiers/#coreeditorcommands) 36 | * 37 | * `editor.execCommand` supports adding arguments for the commands. 38 | * 39 | * ```typescript 40 | * await joplin.commands.execute('editor.execCommand', { 41 | * name: 'madeUpCommand', // CodeMirror and TinyMCE 42 | * args: [], // CodeMirror and TinyMCE 43 | * ui: false, // TinyMCE only 44 | * value: '', // TinyMCE only 45 | * }); 46 | * ``` 47 | * 48 | * [View the example using the CodeMirror editor](https://github.com/laurent22/joplin/blob/dev/packages/app-cli/tests/support/plugins/codemirror_content_script/src/index.ts) 49 | * 50 | */ 51 | export default class JoplinCommands { 52 | /** 53 | * desktop Executes the given 54 | * command. 55 | * 56 | * The command can take any number of arguments, and the supported 57 | * arguments will vary based on the command. For custom commands, this 58 | * is the `args` passed to the `execute()` function. For built-in 59 | * commands, you can find the supported arguments by checking the links 60 | * above. 61 | * 62 | * ```typescript 63 | * // Create a new note in the current notebook: 64 | * await joplin.commands.execute('newNote'); 65 | * 66 | * // Create a new sub-notebook under the provided notebook 67 | * // Note: internally, notebooks are called "folders". 68 | * await joplin.commands.execute('newFolder', "SOME_FOLDER_ID"); 69 | * ``` 70 | */ 71 | execute(commandName: string, ...args: any[]): Promise; 72 | /** 73 | * desktop Registers a new command. 74 | * 75 | * ```typescript 76 | * // Register a new commmand called "testCommand1" 77 | * 78 | * await joplin.commands.register({ 79 | * name: 'testCommand1', 80 | * label: 'My Test Command 1', 81 | * iconName: 'fas fa-music', 82 | * execute: () => { 83 | * alert('Testing plugin command 1'); 84 | * }, 85 | * }); 86 | * ``` 87 | */ 88 | register(command: Command): Promise; 89 | } 90 | -------------------------------------------------------------------------------- /api/JoplinContentScripts.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | import { ContentScriptType } from './types'; 3 | export default class JoplinContentScripts { 4 | private plugin; 5 | constructor(plugin: Plugin); 6 | /** 7 | * Registers a new content script. Unlike regular plugin code, which runs in 8 | * a separate process, content scripts run within the main process code and 9 | * thus allow improved performances and more customisations in specific 10 | * cases. It can be used for example to load a Markdown or editor plugin. 11 | * 12 | * Note that registering a content script in itself will do nothing - it 13 | * will only be loaded in specific cases by the relevant app modules (eg. 14 | * the Markdown renderer or the code editor). So it is not a way to inject 15 | * and run arbitrary code in the app, which for safety and performance 16 | * reasons is not supported. 17 | * 18 | * The plugin generator provides a way to build any content script you might 19 | * want to package as well as its dependencies. See the [Plugin Generator 20 | * doc](https://github.com/laurent22/joplin/blob/dev/packages/generator-joplin/README.md) 21 | * for more information. 22 | * 23 | * * [View the renderer demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/content_script) 24 | * * [View the editor demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/codemirror_content_script) 25 | * 26 | * See also the [postMessage demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/post_messages) 27 | * 28 | * @param type Defines how the script will be used. See the type definition for more information about each supported type. 29 | * @param id A unique ID for the content script. 30 | * @param scriptPath Must be a path relative to the plugin main script. For example, if your file content_script.js is next to your index.ts file, you would set `scriptPath` to `"./content_script.js`. 31 | */ 32 | register(type: ContentScriptType, id: string, scriptPath: string): Promise; 33 | /** 34 | * Listens to a messages sent from the content script using postMessage(). 35 | * See {@link ContentScriptType} for more information as well as the 36 | * [postMessage 37 | * demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/post_messages) 38 | */ 39 | onMessage(contentScriptId: string, callback: any): Promise; 40 | } 41 | -------------------------------------------------------------------------------- /api/JoplinData.d.ts: -------------------------------------------------------------------------------- 1 | import { ModelType } from '../../../BaseModel'; 2 | import { Path } from './types'; 3 | /** 4 | * This module provides access to the Joplin data API: https://joplinapp.org/api/references/rest_api/ 5 | * This is the main way to retrieve data, such as notes, notebooks, tags, etc. 6 | * or to update them or delete them. 7 | * 8 | * This is also what you would use to search notes, via the `search` endpoint. 9 | * 10 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/simple) 11 | * 12 | * In general you would use the methods in this class as if you were using a REST API. There are four methods that map to GET, POST, PUT and DELETE calls. 13 | * And each method takes these parameters: 14 | * 15 | * * `path`: This is an array that represents the path to the resource in the form `["resouceName", "resourceId", "resourceLink"]` (eg. ["tags", ":id", "notes"]). The "resources" segment is the name of the resources you want to access (eg. "notes", "folders", etc.). If not followed by anything, it will refer to all the resources in that collection. The optional "resourceId" points to a particular resources within the collection. Finally, an optional "link" can be present, which links the resource to a collection of resources. This can be used in the API for example to retrieve all the notes associated with a tag. 16 | * * `query`: (Optional) The query parameters. In a URL, this is the part after the question mark "?". In this case, it should be an object with key/value pairs. 17 | * * `data`: (Optional) Applies to PUT and POST calls only. The request body contains the data you want to create or modify, for example the content of a note or folder. 18 | * * `files`: (Optional) Used to create new resources and associate them with files. 19 | * 20 | * Please refer to the [Joplin API documentation](https://joplinapp.org/api/references/rest_api/) for complete details about each call. As the plugin runs within the Joplin application **you do not need an authorisation token** to use this API. 21 | * 22 | * For example: 23 | * 24 | * ```typescript 25 | * // Get a note ID, title and body 26 | * const noteId = 'some_note_id'; 27 | * const note = await joplin.data.get(['notes', noteId], { fields: ['id', 'title', 'body'] }); 28 | * 29 | * // Get all folders 30 | * const folders = await joplin.data.get(['folders']); 31 | * 32 | * // Set the note body 33 | * await joplin.data.put(['notes', noteId], null, { body: "New note body" }); 34 | * 35 | * // Create a new note under one of the folders 36 | * await joplin.data.post(['notes'], null, { body: "my new note", title: "some title", parent_id: folders[0].id }); 37 | * ``` 38 | */ 39 | export default class JoplinData { 40 | private api_; 41 | private pathSegmentRegex_; 42 | private serializeApiBody; 43 | private pathToString; 44 | get(path: Path, query?: any): Promise; 45 | post(path: Path, query?: any, body?: any, files?: any[]): Promise; 46 | put(path: Path, query?: any, body?: any, files?: any[]): Promise; 47 | delete(path: Path, query?: any): Promise; 48 | itemType(itemId: string): Promise; 49 | resourcePath(resourceId: string): Promise; 50 | } 51 | -------------------------------------------------------------------------------- /api/JoplinFilters.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @ignore 3 | * 4 | * Not sure if it's the best way to hook into the app 5 | * so for now disable filters. 6 | */ 7 | export default class JoplinFilters { 8 | on(name: string, callback: Function): Promise; 9 | off(name: string, callback: Function): Promise; 10 | } 11 | -------------------------------------------------------------------------------- /api/JoplinInterop.d.ts: -------------------------------------------------------------------------------- 1 | import { ExportModule, ImportModule } from './types'; 2 | /** 3 | * Provides a way to create modules to import external data into Joplin or to export notes into any arbitrary format. 4 | * 5 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/json_export) 6 | * 7 | * To implement an import or export module, you would simply define an object with various event handlers that are called 8 | * by the application during the import/export process. 9 | * 10 | * See the documentation of the [[ExportModule]] and [[ImportModule]] for more information. 11 | * 12 | * You may also want to refer to the Joplin API documentation to see the list of properties for each item (note, notebook, etc.) - https://joplinapp.org/api/references/rest_api/ 13 | */ 14 | export default class JoplinInterop { 15 | registerExportModule(module: ExportModule): Promise; 16 | registerImportModule(module: ImportModule): Promise; 17 | } 18 | -------------------------------------------------------------------------------- /api/JoplinPlugins.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | import { ContentScriptType, Script } from './types'; 3 | /** 4 | * This class provides access to plugin-related features. 5 | */ 6 | export default class JoplinPlugins { 7 | private plugin; 8 | constructor(plugin: Plugin); 9 | /** 10 | * Registers a new plugin. This is the entry point when creating a plugin. You should pass a simple object with an `onStart` method to it. 11 | * That `onStart` method will be executed as soon as the plugin is loaded. 12 | * 13 | * ```typescript 14 | * joplin.plugins.register({ 15 | * onStart: async function() { 16 | * // Run your plugin code here 17 | * } 18 | * }); 19 | * ``` 20 | */ 21 | register(script: Script): Promise; 22 | /** 23 | * @deprecated Use joplin.contentScripts.register() 24 | */ 25 | registerContentScript(type: ContentScriptType, id: string, scriptPath: string): Promise; 26 | /** 27 | * Gets the plugin own data directory path. Use this to store any 28 | * plugin-related data. Unlike [[installationDir]], any data stored here 29 | * will be persisted. 30 | */ 31 | dataDir(): Promise; 32 | /** 33 | * Gets the plugin installation directory. This can be used to access any 34 | * asset that was packaged with the plugin. This directory should be 35 | * considered read-only because any data you store here might be deleted or 36 | * re-created at any time. To store new persistent data, use [[dataDir]]. 37 | */ 38 | installationDir(): Promise; 39 | /** 40 | * @deprecated Use joplin.require() 41 | */ 42 | require(_path: string): any; 43 | } 44 | -------------------------------------------------------------------------------- /api/JoplinSettings.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | import { SettingItem, SettingSection } from './types'; 3 | export interface ChangeEvent { 4 | /** 5 | * Setting keys that have been changed 6 | */ 7 | keys: string[]; 8 | } 9 | export declare type ChangeHandler = (event: ChangeEvent) => void; 10 | /** 11 | * This API allows registering new settings and setting sections, as well as getting and setting settings. Once a setting has been registered it will appear in the config screen and be editable by the user. 12 | * 13 | * Settings are essentially key/value pairs. 14 | * 15 | * Note: Currently this API does **not** provide access to Joplin's built-in settings. This is by design as plugins that modify user settings could give unexpected results 16 | * 17 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/settings) 18 | */ 19 | export default class JoplinSettings { 20 | private plugin_; 21 | constructor(plugin: Plugin); 22 | private get keyPrefix(); 23 | private namespacedKey; 24 | /** 25 | * Registers new settings. 26 | * Note that registering a setting item is dynamic and will be gone next time Joplin starts. 27 | * What it means is that you need to register the setting every time the plugin starts (for example in the onStart event). 28 | * The setting value however will be preserved from one launch to the next so there is no risk that it will be lost even if for some 29 | * reason the plugin fails to start at some point. 30 | */ 31 | registerSettings(settings: Record): Promise; 32 | /** 33 | * @deprecated Use joplin.settings.registerSettings() 34 | * 35 | * Registers a new setting. 36 | */ 37 | registerSetting(key: string, settingItem: SettingItem): Promise; 38 | /** 39 | * Registers a new setting section. Like for registerSetting, it is dynamic and needs to be done every time the plugin starts. 40 | */ 41 | registerSection(name: string, section: SettingSection): Promise; 42 | /** 43 | * Gets a setting value (only applies to setting you registered from your plugin) 44 | */ 45 | value(key: string): Promise; 46 | /** 47 | * Sets a setting value (only applies to setting you registered from your plugin) 48 | */ 49 | setValue(key: string, value: any): Promise; 50 | /** 51 | * Gets a global setting value, including app-specific settings and those set by other plugins. 52 | * 53 | * The list of available settings is not documented yet, but can be found by looking at the source code: 54 | * 55 | * https://github.com/laurent22/joplin/blob/dev/packages/lib/models/Setting.ts#L142 56 | */ 57 | globalValue(key: string): Promise; 58 | /** 59 | * Called when one or multiple settings of your plugin have been changed. 60 | * - For performance reasons, this event is triggered with a delay. 61 | * - You will only get events for your own plugin settings. 62 | */ 63 | onChange(handler: ChangeHandler): Promise; 64 | } 65 | -------------------------------------------------------------------------------- /api/JoplinViews.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | import JoplinViewsDialogs from './JoplinViewsDialogs'; 3 | import JoplinViewsMenuItems from './JoplinViewsMenuItems'; 4 | import JoplinViewsMenus from './JoplinViewsMenus'; 5 | import JoplinViewsToolbarButtons from './JoplinViewsToolbarButtons'; 6 | import JoplinViewsPanels from './JoplinViewsPanels'; 7 | /** 8 | * This namespace provides access to view-related services. 9 | * 10 | * All view services provide a `create()` method which you would use to create the view object, whether it's a dialog, a toolbar button or a menu item. 11 | * In some cases, the `create()` method will return a [[ViewHandle]], which you would use to act on the view, for example to set certain properties or call some methods. 12 | */ 13 | export default class JoplinViews { 14 | private store; 15 | private plugin; 16 | private dialogs_; 17 | private panels_; 18 | private menuItems_; 19 | private menus_; 20 | private toolbarButtons_; 21 | private implementation_; 22 | constructor(implementation: any, plugin: Plugin, store: any); 23 | get dialogs(): JoplinViewsDialogs; 24 | get panels(): JoplinViewsPanels; 25 | get menuItems(): JoplinViewsMenuItems; 26 | get menus(): JoplinViewsMenus; 27 | get toolbarButtons(): JoplinViewsToolbarButtons; 28 | } 29 | -------------------------------------------------------------------------------- /api/JoplinViewsDialogs.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | import { ButtonSpec, ViewHandle, DialogResult } from './types'; 3 | /** 4 | * Allows creating and managing dialogs. A dialog is modal window that 5 | * contains a webview and a row of buttons. You can update the 6 | * webview using the `setHtml` method. Dialogs are hidden by default and 7 | * you need to call `open()` to open them. Once the user clicks on a 8 | * button, the `open` call will return an object indicating what button was 9 | * clicked on. 10 | * 11 | * ## Retrieving form values 12 | * 13 | * If your HTML content included one or more forms, a `formData` object 14 | * will also be included with the key/value for each form. 15 | * 16 | * ## Special button IDs 17 | * 18 | * The following buttons IDs have a special meaning: 19 | * 20 | * - `ok`, `yes`, `submit`, `confirm`: They are considered "submit" buttons 21 | * - `cancel`, `no`, `reject`: They are considered "dismiss" buttons 22 | * 23 | * This information is used by the application to determine what action 24 | * should be done when the user presses "Enter" or "Escape" within the 25 | * dialog. If they press "Enter", the first "submit" button will be 26 | * automatically clicked. If they press "Escape" the first "dismiss" button 27 | * will be automatically clicked. 28 | * 29 | * [View the demo 30 | * plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/dialog) 31 | */ 32 | export default class JoplinViewsDialogs { 33 | private store; 34 | private plugin; 35 | private implementation_; 36 | constructor(implementation: any, plugin: Plugin, store: any); 37 | private controller; 38 | /** 39 | * Creates a new dialog 40 | */ 41 | create(id: string): Promise; 42 | /** 43 | * Displays a message box with OK/Cancel buttons. Returns the button index that was clicked - "0" for OK and "1" for "Cancel" 44 | */ 45 | showMessageBox(message: string): Promise; 46 | /** 47 | * Sets the dialog HTML content 48 | */ 49 | setHtml(handle: ViewHandle, html: string): Promise; 50 | /** 51 | * Adds and loads a new JS or CSS files into the dialog. 52 | */ 53 | addScript(handle: ViewHandle, scriptPath: string): Promise; 54 | /** 55 | * Sets the dialog buttons. 56 | */ 57 | setButtons(handle: ViewHandle, buttons: ButtonSpec[]): Promise; 58 | /** 59 | * Opens the dialog 60 | */ 61 | open(handle: ViewHandle): Promise; 62 | /** 63 | * Toggle on whether to fit the dialog size to the content or not. 64 | * When set to false, the dialog is set to 90vw and 80vh 65 | * @default true 66 | */ 67 | setFitToContent(handle: ViewHandle, status: boolean): Promise; 68 | } 69 | -------------------------------------------------------------------------------- /api/JoplinViewsMenuItems.d.ts: -------------------------------------------------------------------------------- 1 | import { CreateMenuItemOptions, MenuItemLocation } from './types'; 2 | import Plugin from '../Plugin'; 3 | /** 4 | * Allows creating and managing menu items. 5 | * 6 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/register_command) 7 | */ 8 | export default class JoplinViewsMenuItems { 9 | private store; 10 | private plugin; 11 | constructor(plugin: Plugin, store: any); 12 | /** 13 | * Creates a new menu item and associate it with the given command. You can specify under which menu the item should appear using the `location` parameter. 14 | */ 15 | create(id: string, commandName: string, location?: MenuItemLocation, options?: CreateMenuItemOptions): Promise; 16 | } 17 | -------------------------------------------------------------------------------- /api/JoplinViewsMenus.d.ts: -------------------------------------------------------------------------------- 1 | import { MenuItem, MenuItemLocation } from './types'; 2 | import Plugin from '../Plugin'; 3 | /** 4 | * Allows creating menus. 5 | * 6 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/menu) 7 | */ 8 | export default class JoplinViewsMenus { 9 | private store; 10 | private plugin; 11 | constructor(plugin: Plugin, store: any); 12 | private registerCommandAccelerators; 13 | /** 14 | * Creates a new menu from the provided menu items and place it at the given location. As of now, it is only possible to place the 15 | * menu as a sub-menu of the application build-in menus. 16 | */ 17 | create(id: string, label: string, menuItems: MenuItem[], location?: MenuItemLocation): Promise; 18 | } 19 | -------------------------------------------------------------------------------- /api/JoplinViewsPanels.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | import { ViewHandle } from './types'; 3 | /** 4 | * Allows creating and managing view panels. View panels currently are 5 | * displayed at the right of the sidebar and allows displaying any HTML 6 | * content (within a webview) and update it in real-time. For example it 7 | * could be used to display a table of content for the active note, or 8 | * display various metadata or graph. 9 | * 10 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/toc) 11 | */ 12 | export default class JoplinViewsPanels { 13 | private store; 14 | private plugin; 15 | constructor(plugin: Plugin, store: any); 16 | private controller; 17 | /** 18 | * Creates a new panel 19 | */ 20 | create(id: string): Promise; 21 | /** 22 | * Sets the panel webview HTML 23 | */ 24 | setHtml(handle: ViewHandle, html: string): Promise; 25 | /** 26 | * Adds and loads a new JS or CSS files into the panel. 27 | */ 28 | addScript(handle: ViewHandle, scriptPath: string): Promise; 29 | /** 30 | * Called when a message is sent from the webview (using postMessage). 31 | * 32 | * To post a message from the webview to the plugin use: 33 | * 34 | * ```javascript 35 | * const response = await webviewApi.postMessage(message); 36 | * ``` 37 | * 38 | * - `message` can be any JavaScript object, string or number 39 | * - `response` is whatever was returned by the `onMessage` handler 40 | * 41 | * Using this mechanism, you can have two-way communication between the 42 | * plugin and webview. 43 | * 44 | * See the [postMessage 45 | * demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/post_messages) for more details. 46 | * 47 | */ 48 | onMessage(handle: ViewHandle, callback: Function): Promise; 49 | /** 50 | * Sends a message to the webview. 51 | * 52 | * The webview must have registered a message handler prior, otherwise the message is ignored. Use; 53 | * 54 | * ```javascript 55 | * webviewApi.onMessage((message) => { ... }); 56 | * ``` 57 | * 58 | * - `message` can be any JavaScript object, string or number 59 | * 60 | * The view API may have only one onMessage handler defined. 61 | * This method is fire and forget so no response is returned. 62 | * 63 | * It is particularly useful when the webview needs to react to events emitted by the plugin or the joplin api. 64 | */ 65 | postMessage(handle: ViewHandle, message: any): void; 66 | /** 67 | * Shows the panel 68 | */ 69 | show(handle: ViewHandle, show?: boolean): Promise; 70 | /** 71 | * Hides the panel 72 | */ 73 | hide(handle: ViewHandle): Promise; 74 | /** 75 | * Tells whether the panel is visible or not 76 | */ 77 | visible(handle: ViewHandle): Promise; 78 | } 79 | -------------------------------------------------------------------------------- /api/JoplinViewsToolbarButtons.d.ts: -------------------------------------------------------------------------------- 1 | import { ToolbarButtonLocation } from './types'; 2 | import Plugin from '../Plugin'; 3 | /** 4 | * Allows creating and managing toolbar buttons. 5 | * 6 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/register_command) 7 | */ 8 | export default class JoplinViewsToolbarButtons { 9 | private store; 10 | private plugin; 11 | constructor(plugin: Plugin, store: any); 12 | /** 13 | * Creates a new toolbar button and associate it with the given command. 14 | */ 15 | create(id: string, commandName: string, location: ToolbarButtonLocation): Promise; 16 | } 17 | -------------------------------------------------------------------------------- /api/JoplinWindow.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | export interface Implementation { 3 | injectCustomStyles(elementId: string, cssFilePath: string): Promise; 4 | } 5 | export default class JoplinWindow { 6 | private plugin_; 7 | private store_; 8 | private implementation_; 9 | constructor(implementation: Implementation, plugin: Plugin, store: any); 10 | /** 11 | * Loads a chrome CSS file. It will apply to the window UI elements, except 12 | * for the note viewer. It is the same as the "Custom stylesheet for 13 | * Joplin-wide app styles" setting. See the [Load CSS Demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/load_css) 14 | * for an example. 15 | */ 16 | loadChromeCssFile(filePath: string): Promise; 17 | /** 18 | * Loads a note CSS file. It will apply to the note viewer, as well as any 19 | * exported or printed note. It is the same as the "Custom stylesheet for 20 | * rendered Markdown" setting. See the [Load CSS Demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/load_css) 21 | * for an example. 22 | */ 23 | loadNoteCssFile(filePath: string): Promise; 24 | } 25 | -------------------------------------------------------------------------------- /api/JoplinWorkspace.d.ts: -------------------------------------------------------------------------------- 1 | import { FolderEntity } from '../../database/types'; 2 | import { Disposable, MenuItem } from './types'; 3 | export interface EditContextMenuFilterObject { 4 | items: MenuItem[]; 5 | } 6 | declare type FilterHandler = (object: T) => Promise; 7 | declare enum ItemChangeEventType { 8 | Create = 1, 9 | Update = 2, 10 | Delete = 3 11 | } 12 | interface ItemChangeEvent { 13 | id: string; 14 | event: ItemChangeEventType; 15 | } 16 | interface SyncStartEvent { 17 | withErrors: boolean; 18 | } 19 | declare type ItemChangeHandler = (event: ItemChangeEvent) => void; 20 | declare type SyncStartHandler = (event: SyncStartEvent) => void; 21 | /** 22 | * The workspace service provides access to all the parts of Joplin that 23 | * are being worked on - i.e. the currently selected notes or notebooks as 24 | * well as various related events, such as when a new note is selected, or 25 | * when the note content changes. 26 | * 27 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins) 28 | */ 29 | export default class JoplinWorkspace { 30 | private store; 31 | constructor(store: any); 32 | /** 33 | * Called when a new note or notes are selected. 34 | */ 35 | onNoteSelectionChange(callback: Function): Promise; 36 | /** 37 | * Called when the content of a note changes. 38 | * @deprecated Use `onNoteChange()` instead, which is reliably triggered whenever the note content, or any note property changes. 39 | */ 40 | onNoteContentChange(callback: Function): Promise; 41 | /** 42 | * Called when the content of the current note changes. 43 | */ 44 | onNoteChange(handler: ItemChangeHandler): Promise; 45 | /** 46 | * Called when an alarm associated with a to-do is triggered. 47 | */ 48 | onNoteAlarmTrigger(handler: Function): Promise; 49 | /** 50 | * Called when the synchronisation process is starting. 51 | */ 52 | onSyncStart(handler: SyncStartHandler): Promise; 53 | /** 54 | * Called when the synchronisation process has finished. 55 | */ 56 | onSyncComplete(callback: Function): Promise; 57 | /** 58 | * Called just before the editor context menu is about to open. Allows 59 | * adding items to it. 60 | */ 61 | filterEditorContextMenu(handler: FilterHandler): void; 62 | /** 63 | * Gets the currently selected note 64 | */ 65 | selectedNote(): Promise; 66 | /** 67 | * Gets the currently selected folder. In some cases, for example during 68 | * search or when viewing a tag, no folder is actually selected in the user 69 | * interface. In that case, that function would return the last selected 70 | * folder. 71 | */ 72 | selectedFolder(): Promise; 73 | /** 74 | * Gets the IDs of the selected notes (can be zero, one, or many). Use the data API to retrieve information about these notes. 75 | */ 76 | selectedNoteIds(): Promise; 77 | } 78 | export {}; 79 | -------------------------------------------------------------------------------- /api/index.ts: -------------------------------------------------------------------------------- 1 | import type Joplin from './Joplin'; 2 | 3 | declare const joplin: Joplin; 4 | 5 | export default joplin; 6 | -------------------------------------------------------------------------------- /api/types.ts: -------------------------------------------------------------------------------- 1 | // ================================================================= 2 | // Command API types 3 | // ================================================================= 4 | 5 | export interface Command { 6 | /** 7 | * Name of command - must be globally unique 8 | */ 9 | name: string; 10 | 11 | /** 12 | * Label to be displayed on menu items or keyboard shortcut editor for example. 13 | * If it is missing, it's assumed it's a private command, to be called programmatically only. 14 | * In that case the command will not appear in the shortcut editor or command panel, and logically 15 | * should not be used as a menu item. 16 | */ 17 | label?: string; 18 | 19 | /** 20 | * Icon to be used on toolbar buttons for example 21 | */ 22 | iconName?: string; 23 | 24 | /** 25 | * Code to be ran when the command is executed. It may return a result. 26 | */ 27 | execute(...args: any[]): Promise; 28 | 29 | /** 30 | * Defines whether the command should be enabled or disabled, which in turns 31 | * affects the enabled state of any associated button or menu item. 32 | * 33 | * The condition should be expressed as a "when-clause" (as in Visual Studio 34 | * Code). It's a simple boolean expression that evaluates to `true` or 35 | * `false`. It supports the following operators: 36 | * 37 | * Operator | Symbol | Example 38 | * -- | -- | -- 39 | * Equality | == | "editorType == markdown" 40 | * Inequality | != | "currentScreen != config" 41 | * Or | \|\| | "noteIsTodo \|\| noteTodoCompleted" 42 | * And | && | "oneNoteSelected && !inConflictFolder" 43 | * 44 | * Joplin, unlike VSCode, also supports parenthesis, which allows creating 45 | * more complex expressions such as `cond1 || (cond2 && cond3)`. Only one 46 | * level of parenthesis is possible (nested ones aren't supported). 47 | * 48 | * Currently the supported context variables aren't documented, but you can 49 | * find the list below: 50 | * 51 | * - [Global When Clauses](https://github.com/laurent22/joplin/blob/dev/packages/lib/services/commands/stateToWhenClauseContext.ts) 52 | * - [Desktop app When Clauses](https://github.com/laurent22/joplin/blob/dev/packages/app-desktop/services/commands/stateToWhenClauseContext.ts) 53 | * 54 | * Note: Commands are enabled by default unless you use this property. 55 | */ 56 | enabledCondition?: string; 57 | } 58 | 59 | // ================================================================= 60 | // Interop API types 61 | // ================================================================= 62 | 63 | export enum FileSystemItem { 64 | File = 'file', 65 | Directory = 'directory', 66 | } 67 | 68 | export enum ImportModuleOutputFormat { 69 | Markdown = 'md', 70 | Html = 'html', 71 | } 72 | 73 | /** 74 | * Used to implement a module to export data from Joplin. [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/json_export) for an example. 75 | * 76 | * In general, all the event handlers you'll need to implement take a `context` object as a first argument. This object will contain the export or import path as well as various optional properties, such as which notes or notebooks need to be exported. 77 | * 78 | * To get a better sense of what it will contain it can be useful to print it using `console.info(context)`. 79 | */ 80 | export interface ExportModule { 81 | /** 82 | * The format to be exported, eg "enex", "jex", "json", etc. 83 | */ 84 | format: string; 85 | 86 | /** 87 | * The description that will appear in the UI, for example in the menu item. 88 | */ 89 | description: string; 90 | 91 | /** 92 | * Whether the module will export a single file or multiple files in a directory. It affects the open dialog that will be presented to the user when using your exporter. 93 | */ 94 | target: FileSystemItem; 95 | 96 | /** 97 | * Only applies to single file exporters or importers 98 | * It tells whether the format can package multiple notes into one file. 99 | * For example JEX or ENEX can, but HTML cannot. 100 | */ 101 | isNoteArchive: boolean; 102 | 103 | /** 104 | * The extensions of the files exported by your module. For example, it is `["htm", "html"]` for the HTML module, and just `["jex"]` for the JEX module. 105 | */ 106 | fileExtensions?: string[]; 107 | 108 | /** 109 | * Called when the export process starts. 110 | */ 111 | onInit(context: ExportContext): Promise; 112 | 113 | /** 114 | * Called when an item needs to be processed. An "item" can be any Joplin object, such as a note, a folder, a notebook, etc. 115 | */ 116 | onProcessItem(context: ExportContext, itemType: number, item: any): Promise; 117 | 118 | /** 119 | * Called when a resource file needs to be exported. 120 | */ 121 | onProcessResource(context: ExportContext, resource: any, filePath: string): Promise; 122 | 123 | /** 124 | * Called when the export process is done. 125 | */ 126 | onClose(context: ExportContext): Promise; 127 | } 128 | 129 | export interface ImportModule { 130 | /** 131 | * The format to be exported, eg "enex", "jex", "json", etc. 132 | */ 133 | format: string; 134 | 135 | /** 136 | * The description that will appear in the UI, for example in the menu item. 137 | */ 138 | description: string; 139 | 140 | /** 141 | * Only applies to single file exporters or importers 142 | * It tells whether the format can package multiple notes into one file. 143 | * For example JEX or ENEX can, but HTML cannot. 144 | */ 145 | isNoteArchive: boolean; 146 | 147 | /** 148 | * The type of sources that are supported by the module. Tells whether the module can import files or directories or both. 149 | */ 150 | sources: FileSystemItem[]; 151 | 152 | /** 153 | * Tells the file extensions of the exported files. 154 | */ 155 | fileExtensions?: string[]; 156 | 157 | /** 158 | * Tells the type of notes that will be generated, either HTML or Markdown (default). 159 | */ 160 | outputFormat?: ImportModuleOutputFormat; 161 | 162 | /** 163 | * Called when the import process starts. There is only one event handler within which you should import the complete data. 164 | */ 165 | onExec(context: ImportContext): Promise; 166 | } 167 | 168 | export interface ExportOptions { 169 | format?: string; 170 | path?: string; 171 | sourceFolderIds?: string[]; 172 | sourceNoteIds?: string[]; 173 | // modulePath?: string; 174 | target?: FileSystemItem; 175 | } 176 | 177 | export interface ExportContext { 178 | destPath: string; 179 | options: ExportOptions; 180 | 181 | /** 182 | * You can attach your own custom data using this propery - it will then be passed to each event handler, allowing you to keep state from one event to the next. 183 | */ 184 | userData?: any; 185 | } 186 | 187 | export interface ImportContext { 188 | sourcePath: string; 189 | options: any; 190 | warnings: string[]; 191 | } 192 | 193 | // ================================================================= 194 | // Misc types 195 | // ================================================================= 196 | 197 | export interface Script { 198 | onStart?(event: any): Promise; 199 | } 200 | 201 | export interface Disposable { 202 | // dispose():void; 203 | } 204 | 205 | export enum ModelType { 206 | Note = 1, 207 | Folder = 2, 208 | Setting = 3, 209 | Resource = 4, 210 | Tag = 5, 211 | NoteTag = 6, 212 | Search = 7, 213 | Alarm = 8, 214 | MasterKey = 9, 215 | ItemChange = 10, 216 | NoteResource = 11, 217 | ResourceLocalState = 12, 218 | Revision = 13, 219 | Migration = 14, 220 | SmartFilter = 15, 221 | Command = 16, 222 | } 223 | 224 | // ================================================================= 225 | // Menu types 226 | // ================================================================= 227 | 228 | export interface CreateMenuItemOptions { 229 | accelerator: string; 230 | } 231 | 232 | export enum MenuItemLocation { 233 | File = 'file', 234 | Edit = 'edit', 235 | View = 'view', 236 | Note = 'note', 237 | Tools = 'tools', 238 | Help = 'help', 239 | 240 | /** 241 | * @deprecated Do not use - same as NoteListContextMenu 242 | */ 243 | Context = 'context', 244 | 245 | // If adding an item here, don't forget to update isContextMenuItemLocation() 246 | 247 | /** 248 | * When a command is called from the note list context menu, the 249 | * command will receive the following arguments: 250 | * 251 | * - `noteIds:string[]`: IDs of the notes that were right-clicked on. 252 | */ 253 | NoteListContextMenu = 'noteListContextMenu', 254 | 255 | EditorContextMenu = 'editorContextMenu', 256 | 257 | /** 258 | * When a command is called from a folder context menu, the 259 | * command will receive the following arguments: 260 | * 261 | * - `folderId:string`: ID of the folder that was right-clicked on 262 | */ 263 | FolderContextMenu = 'folderContextMenu', 264 | 265 | /** 266 | * When a command is called from a tag context menu, the 267 | * command will receive the following arguments: 268 | * 269 | * - `tagId:string`: ID of the tag that was right-clicked on 270 | */ 271 | TagContextMenu = 'tagContextMenu', 272 | } 273 | 274 | export function isContextMenuItemLocation(location: MenuItemLocation): boolean { 275 | return [ 276 | MenuItemLocation.Context, 277 | MenuItemLocation.NoteListContextMenu, 278 | MenuItemLocation.EditorContextMenu, 279 | MenuItemLocation.FolderContextMenu, 280 | MenuItemLocation.TagContextMenu, 281 | ].includes(location); 282 | } 283 | 284 | export interface MenuItem { 285 | /** 286 | * Command that should be associated with the menu item. All menu item should 287 | * have a command associated with them unless they are a sub-menu. 288 | */ 289 | commandName?: string; 290 | 291 | /** 292 | * Arguments that should be passed to the command. They will be as rest 293 | * parameters. 294 | */ 295 | commandArgs?: any[]; 296 | 297 | /** 298 | * Set to "separator" to create a divider line 299 | */ 300 | type?: string; 301 | 302 | /** 303 | * Accelerator associated with the menu item 304 | */ 305 | accelerator?: string; 306 | 307 | /** 308 | * Menu items that should appear below this menu item. Allows creating a menu tree. 309 | */ 310 | submenu?: MenuItem[]; 311 | 312 | /** 313 | * Menu item label. If not specified, the command label will be used instead. 314 | */ 315 | label?: string; 316 | } 317 | 318 | // ================================================================= 319 | // View API types 320 | // ================================================================= 321 | 322 | export interface ButtonSpec { 323 | id: ButtonId; 324 | title?: string; 325 | onClick?(): void; 326 | } 327 | 328 | export type ButtonId = string; 329 | 330 | export enum ToolbarButtonLocation { 331 | /** 332 | * This toolbar in the top right corner of the application. It applies to the note as a whole, including its metadata. 333 | */ 334 | NoteToolbar = 'noteToolbar', 335 | 336 | /** 337 | * This toolbar is right above the text editor. It applies to the note body only. 338 | */ 339 | EditorToolbar = 'editorToolbar', 340 | } 341 | 342 | export type ViewHandle = string; 343 | 344 | export interface EditorCommand { 345 | name: string; 346 | value?: any; 347 | } 348 | 349 | export interface DialogResult { 350 | id: ButtonId; 351 | formData?: any; 352 | } 353 | 354 | // ================================================================= 355 | // Settings types 356 | // ================================================================= 357 | 358 | export enum SettingItemType { 359 | Int = 1, 360 | String = 2, 361 | Bool = 3, 362 | Array = 4, 363 | Object = 5, 364 | Button = 6, 365 | } 366 | 367 | export enum AppType { 368 | Desktop = 'desktop', 369 | Mobile = 'mobile', 370 | Cli = 'cli', 371 | } 372 | 373 | export enum SettingStorage { 374 | Database = 1, 375 | File = 2, 376 | } 377 | 378 | // Redefine a simplified interface to mask internal details 379 | // and to remove function calls as they would have to be async. 380 | export interface SettingItem { 381 | value: any; 382 | type: SettingItemType; 383 | 384 | label: string; 385 | description?: string; 386 | 387 | /** 388 | * A public setting will appear in the Configuration screen and will be 389 | * modifiable by the user. A private setting however will not appear there, 390 | * and can only be changed programmatically. You may use this to store some 391 | * values that you do not want to directly expose. 392 | */ 393 | public: boolean; 394 | 395 | /** 396 | * You would usually set this to a section you would have created 397 | * specifically for the plugin. 398 | */ 399 | section?: string; 400 | 401 | /** 402 | * To create a setting with multiple options, set this property to `true`. 403 | * That setting will render as a dropdown list in the configuration screen. 404 | */ 405 | isEnum?: boolean; 406 | 407 | /** 408 | * This property is required when `isEnum` is `true`. In which case, it 409 | * should contain a map of value => label. 410 | */ 411 | options?: Record; 412 | 413 | /** 414 | * Reserved property. Not used at the moment. 415 | */ 416 | appTypes?: AppType[]; 417 | 418 | /** 419 | * Set this to `true` to store secure data, such as passwords. Any such 420 | * setting will be stored in the system keychain if one is available. 421 | */ 422 | secure?: boolean; 423 | 424 | /** 425 | * An advanced setting will be moved under the "Advanced" button in the 426 | * config screen. 427 | */ 428 | advanced?: boolean; 429 | 430 | /** 431 | * Set the min, max and step values if you want to restrict an int setting 432 | * to a particular range. 433 | */ 434 | minimum?: number; 435 | maximum?: number; 436 | step?: number; 437 | 438 | /** 439 | * Either store the setting in the database or in settings.json. Defaults to database. 440 | */ 441 | storage?: SettingStorage; 442 | } 443 | 444 | export interface SettingSection { 445 | label: string; 446 | iconName?: string; 447 | description?: string; 448 | name?: string; 449 | } 450 | 451 | // ================================================================= 452 | // Data API types 453 | // ================================================================= 454 | 455 | /** 456 | * An array of at least one element and at most three elements. 457 | * 458 | * - **[0]**: Resource name (eg. "notes", "folders", "tags", etc.) 459 | * - **[1]**: (Optional) Resource ID. 460 | * - **[2]**: (Optional) Resource link. 461 | */ 462 | export type Path = string[]; 463 | 464 | // ================================================================= 465 | // Content Script types 466 | // ================================================================= 467 | 468 | export type PostMessageHandler = (message: any)=> Promise; 469 | 470 | /** 471 | * When a content script is initialised, it receives a `context` object. 472 | */ 473 | export interface ContentScriptContext { 474 | /** 475 | * The plugin ID that registered this content script 476 | */ 477 | pluginId: string; 478 | 479 | /** 480 | * The content script ID, which may be necessary to post messages 481 | */ 482 | contentScriptId: string; 483 | 484 | /** 485 | * Can be used by CodeMirror content scripts to post a message to the plugin 486 | */ 487 | postMessage: PostMessageHandler; 488 | } 489 | 490 | export enum ContentScriptType { 491 | /** 492 | * Registers a new Markdown-It plugin, which should follow the template 493 | * below. 494 | * 495 | * ```javascript 496 | * module.exports = { 497 | * default: function(context) { 498 | * return { 499 | * plugin: function(markdownIt, options) { 500 | * // ... 501 | * }, 502 | * assets: { 503 | * // ... 504 | * }, 505 | * } 506 | * } 507 | * } 508 | * ``` 509 | * See [the 510 | * demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/content_script) 511 | * for a simple Markdown-it plugin example. 512 | * 513 | * ## Exported members 514 | * 515 | * - The `context` argument is currently unused but could be used later on 516 | * to provide access to your own plugin so that the content script and 517 | * plugin can communicate. 518 | * 519 | * - The **required** `plugin` key is the actual Markdown-It plugin - check 520 | * the [official doc](https://github.com/markdown-it/markdown-it) for more 521 | * information. The `options` parameter is of type 522 | * [RuleOptions](https://github.com/laurent22/joplin/blob/dev/packages/renderer/MdToHtml.ts), 523 | * which contains a number of options, mostly useful for Joplin's internal 524 | * code. 525 | * 526 | * - Using the **optional** `assets` key you may specify assets such as JS 527 | * or CSS that should be loaded in the rendered HTML document. Check for 528 | * example the Joplin [Mermaid 529 | * plugin](https://github.com/laurent22/joplin/blob/dev/packages/renderer/MdToHtml/rules/mermaid.ts) 530 | * to see how the data should be structured. 531 | * 532 | * ## Posting messages from the content script to your plugin 533 | * 534 | * The application provides the following function to allow executing 535 | * commands from the rendered HTML code: 536 | * 537 | * ```javascript 538 | * const response = await webviewApi.postMessage(contentScriptId, message); 539 | * ``` 540 | * 541 | * - `contentScriptId` is the ID you've defined when you registered the 542 | * content script. You can retrieve it from the 543 | * {@link ContentScriptContext | context}. 544 | * - `message` can be any basic JavaScript type (number, string, plain 545 | * object), but it cannot be a function or class instance. 546 | * 547 | * When you post a message, the plugin can send back a `response` thus 548 | * allowing two-way communication: 549 | * 550 | * ```javascript 551 | * await joplin.contentScripts.onMessage(contentScriptId, (message) => { 552 | * // Process message 553 | * return response; // Can be any object, string or number 554 | * }); 555 | * ``` 556 | * 557 | * See {@link JoplinContentScripts.onMessage} for more details, as well as 558 | * the [postMessage 559 | * demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/post_messages). 560 | * 561 | * ## Registering an existing Markdown-it plugin 562 | * 563 | * To include a regular Markdown-It plugin, that doesn't make use of any 564 | * Joplin-specific features, you would simply create a file such as this: 565 | * 566 | * ```javascript 567 | * module.exports = { 568 | * default: function(context) { 569 | * return { 570 | * plugin: require('markdown-it-toc-done-right'); 571 | * } 572 | * } 573 | * } 574 | * ``` 575 | */ 576 | MarkdownItPlugin = 'markdownItPlugin', 577 | 578 | /** 579 | * Registers a new CodeMirror plugin, which should follow the template 580 | * below. 581 | * 582 | * ```javascript 583 | * module.exports = { 584 | * default: function(context) { 585 | * return { 586 | * plugin: function(CodeMirror) { 587 | * // ... 588 | * }, 589 | * codeMirrorResources: [], 590 | * codeMirrorOptions: { 591 | * // ... 592 | * }, 593 | * assets: { 594 | * // ... 595 | * }, 596 | * } 597 | * } 598 | * } 599 | * ``` 600 | * 601 | * - The `context` argument is currently unused but could be used later on 602 | * to provide access to your own plugin so that the content script and 603 | * plugin can communicate. 604 | * 605 | * - The `plugin` key is your CodeMirror plugin. This is where you can 606 | * register new commands with CodeMirror or interact with the CodeMirror 607 | * instance as needed. 608 | * 609 | * - The `codeMirrorResources` key is an array of CodeMirror resources that 610 | * will be loaded and attached to the CodeMirror module. These are made up 611 | * of addons, keymaps, and modes. For example, for a plugin that want's to 612 | * enable clojure highlighting in code blocks. `codeMirrorResources` would 613 | * be set to `['mode/clojure/clojure']`. 614 | * 615 | * - The `codeMirrorOptions` key contains all the 616 | * [CodeMirror](https://codemirror.net/doc/manual.html#config) options 617 | * that will be set or changed by this plugin. New options can alse be 618 | * declared via 619 | * [`CodeMirror.defineOption`](https://codemirror.net/doc/manual.html#defineOption), 620 | * and then have their value set here. For example, a plugin that enables 621 | * line numbers would set `codeMirrorOptions` to `{'lineNumbers': true}`. 622 | * 623 | * - Using the **optional** `assets` key you may specify **only** CSS assets 624 | * that should be loaded in the rendered HTML document. Check for example 625 | * the Joplin [Mermaid 626 | * plugin](https://github.com/laurent22/joplin/blob/dev/packages/renderer/MdToHtml/rules/mermaid.ts) 627 | * to see how the data should be structured. 628 | * 629 | * One of the `plugin`, `codeMirrorResources`, or `codeMirrorOptions` keys 630 | * must be provided for the plugin to be valid. Having multiple or all 631 | * provided is also okay. 632 | * 633 | * See also the [demo 634 | * plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/codemirror_content_script) 635 | * for an example of all these keys being used in one plugin. 636 | * 637 | * ## Posting messages from the content script to your plugin 638 | * 639 | * In order to post messages to the plugin, you can use the postMessage 640 | * function passed to the {@link ContentScriptContext | context}. 641 | * 642 | * ```javascript 643 | * const response = await context.postMessage('messageFromCodeMirrorContentScript'); 644 | * ``` 645 | * 646 | * When you post a message, the plugin can send back a `response` thus 647 | * allowing two-way communication: 648 | * 649 | * ```javascript 650 | * await joplin.contentScripts.onMessage(contentScriptId, (message) => { 651 | * // Process message 652 | * return response; // Can be any object, string or number 653 | * }); 654 | * ``` 655 | * 656 | * See {@link JoplinContentScripts.onMessage} for more details, as well as 657 | * the [postMessage 658 | * demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/post_messages). 659 | * 660 | */ 661 | CodeMirrorPlugin = 'codeMirrorPlugin', 662 | } 663 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | transform: { '^.+\\.ts?$': 'ts-jest' }, 3 | testEnvironment: 'node', 4 | testRegex: '/test/.*\\.(test|spec)?\\.ts$', 5 | moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'] 6 | }; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "joplin-plugin-email", 3 | "version": "1.0.0", 4 | "scripts": { 5 | "dist": "webpack --joplin-plugin-config buildMain && webpack --joplin-plugin-config buildExtraScripts && webpack --joplin-plugin-config createArchive", 6 | "prepare": "npm run dist", 7 | "update": "npm install -g generator-joplin && yo joplin --update", 8 | "test": "jest" 9 | }, 10 | "license": "MIT", 11 | "keywords": [ 12 | "joplin-plugin" 13 | ], 14 | "devDependencies": { 15 | "@types/jest": "^26.0.23", 16 | "@types/node": "^14.0.14", 17 | "@typescript-eslint/eslint-plugin": "^5.30.7", 18 | "@typescript-eslint/parser": "^5.30.7", 19 | "chalk": "^4.1.0", 20 | "copy-webpack-plugin": "^6.1.0", 21 | "cross-blob": "^2.0.0", 22 | "eslint": "^8.20.0", 23 | "eslint-config-google": "^0.14.0", 24 | "fs-extra": "^9.0.1", 25 | "glob": "^7.1.6", 26 | "jest": "^27.0.4", 27 | "on-build-webpack": "^0.1.0", 28 | "tar": "^6.0.5", 29 | "ts-jest": "<27.0.3", 30 | "ts-loader": "^7.0.5", 31 | "typescript": "^3.9.3", 32 | "webpack": "^4.43.0", 33 | "webpack-cli": "^3.3.11", 34 | "yargs": "^16.2.0" 35 | }, 36 | "dependencies": { 37 | "@types/imap": "^0.8.35", 38 | "html-to-text": "^8.2.1", 39 | "imap": "^0.8.19", 40 | "net": "^1.0.2", 41 | "postal-mime": "^1.0.16", 42 | "tls": "^0.0.1" 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /plugin.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "extraScripts": [] 3 | } -------------------------------------------------------------------------------- /src/constants.ts: -------------------------------------------------------------------------------- 1 | export const SECTION_NAME = 'Email_Plugin'; 2 | export const EXPORT_TYPE = 'Export_Type'; 3 | export const ATTACHMENTS = 'Attachments'; 4 | export const PLUGIN_ICON = 'fa fa-envelope'; 5 | export const ATTACHMENTS_STYLE = 'Attachments_Style'; 6 | export const ACCOUNTS = 'Accounts'; 7 | export const LAST_STATE = 'Last_State'; 8 | 9 | // This regexs from https://github.com/regexhq/mentions-regex/blob/master/index.js 10 | // @folder regex Regular expression for matching @foldre mentions 11 | export const MENTIONS_REGEX = /(?:^|[^a-zA-Z0-9_@!@#$%&*])(?:(?:﹫|@|@)(?!\/))([a-zA-Z0-9/_.]{1,150})(?:\b(?!﹫|@|@|#|⋕|♯|⌗)|$)/g; 12 | 13 | // #tag regex Regular expression for matching #tag mentions 14 | export const TAGS_REGEX = /(?:^|[^a-zA-Z0-9_@!@#$%&*])(?:(?:#|⋕|♯|⌗)(?!\/))([a-zA-Z0-9/_.]{1,150})(?:\b(?!﹫|@|@|#|⋕|♯|⌗)|$)/g; 15 | -------------------------------------------------------------------------------- /src/core/emailConfigure.ts: -------------------------------------------------------------------------------- 1 | import {Login} from '../model/message.model'; 2 | import {emailProviders} from './emailProviders'; 3 | import {ImapConfig} from '../model/imapConfig.model'; 4 | import {EmailProvider} from 'src/model/emailProvider.model'; 5 | 6 | export function emailConfigure(login: Login): ImapConfig | never { 7 | let user = login.email; 8 | const password = login.password; 9 | 10 | user = user.toLocaleLowerCase(); 11 | 12 | // Remove extra spaces from an email. 13 | user = user.replace(/\s+/g, ''); 14 | 15 | 16 | const config: EmailProvider = emailProviders.find(({type}) => user.includes('@' + type)); 17 | 18 | // In the case that the email provider is not present in the email providers list, it will be returned as "undefined". 19 | if (!config) { 20 | throw new Error(`Sorry, an email provider couldn't be found, Please use the manual connection.`); 21 | } 22 | 23 | const imapConfig: ImapConfig = { 24 | user: user, 25 | password: password, 26 | ...config, 27 | }; 28 | 29 | return imapConfig; 30 | } 31 | -------------------------------------------------------------------------------- /src/core/emailParser.ts: -------------------------------------------------------------------------------- 1 | const postalMime = require('postal-mime/dist/node').postalMime.default; 2 | import {Email} from 'postal-mime'; 3 | import StringOps from '../utils/stringOps'; 4 | 5 | export default class EmailParser extends postalMime { 6 | emailContent: Email; 7 | 8 | constructor() { 9 | super(); 10 | } 11 | 12 | // Email in RFC 822 format. 13 | async parse(message: string): Promise { 14 | // A message is invalid if it starts with a space. 15 | message = message.trim(); 16 | this.emailContent = await super.parse(message); 17 | this.emailContent.subject = this.getSubject(); 18 | this.emailContent.html = this.getHTML(); 19 | 20 | return (this.emailContent); 21 | } 22 | 23 | getSubject() { 24 | return this.emailContent.subject || 'No Subject'; 25 | } 26 | 27 | getHTML() { 28 | const {html, text} = this.emailContent; 29 | const {escapeHTML} = StringOps; 30 | 31 | // If HTML content does not exist, email text content (wrapping with html) will be returned if it does. 32 | if (!html && text) { 33 | const linebreaks = text.split('\n'); 34 | const splitText = (line: string) => (line.trim() === '' ? '
' : `
${escapeHTML(line)}
`); 35 | const emailText = linebreaks.map(splitText).join(''); 36 | 37 | return emailText; 38 | } 39 | 40 | return html || '

This Email Has No Body

\n'; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/core/emailProviders.ts: -------------------------------------------------------------------------------- 1 | import {EmailProvider} from '../model/emailProvider.model'; 2 | 3 | export const emailProviders: EmailProvider[] = [ 4 | 5 | { 6 | type: 'gmail', 7 | host: 'imap.gmail.com', 8 | port: 993, 9 | tls: true, 10 | }, 11 | 12 | { 13 | type: 'outlook', 14 | host: 'outlook.office365.com', 15 | port: 993, 16 | tls: true, 17 | }, 18 | 19 | { 20 | type: 'icloud', 21 | host: 'imap.mail.me.com', 22 | port: 993, 23 | tls: true, 24 | }, 25 | 26 | { 27 | type: 'yahoo', 28 | host: 'imap.mail.yahoo.com', 29 | port: 993, 30 | tls: true, 31 | }, 32 | 33 | { 34 | type: 'aol', 35 | host: 'imap.aol.com', 36 | port: 993, 37 | tls: true, 38 | }, 39 | 40 | { 41 | type: 'zoho', 42 | host: 'imap.zoho.com', 43 | port: 993, 44 | tls: true, 45 | }, 46 | 47 | { 48 | type: 'yandex', 49 | host: 'imap.yandex.com', 50 | port: 993, 51 | tls: true, 52 | }, 53 | 54 | { 55 | type: 'strato', 56 | host: 'imap.strato.de', 57 | port: 993, 58 | tls: true, 59 | }, 60 | ]; 61 | -------------------------------------------------------------------------------- /src/core/emailSubjectParser.ts: -------------------------------------------------------------------------------- 1 | import StringOps from '../utils/stringOps'; 2 | import {MENTIONS_REGEX, TAGS_REGEX} from '../constants'; 3 | import SubjectMetadata from '../model/subjectMetadata.model'; 4 | 5 | class EmailSubjectParser { 6 | subjectMetadata: SubjectMetadata; 7 | subject: string; 8 | subjectPattern: string; 9 | 10 | constructor(subject: string) { 11 | this.subject = subject; 12 | this.subjectPattern = ''; 13 | this.subjectMetadata = { 14 | isTodo: 0, 15 | folders: ['email messages'], // Default note location if no specific folder is mentioned. 16 | tags: [], 17 | }; 18 | } 19 | 20 | parse(): SubjectMetadata { 21 | this.removeIrregularSpaces() 22 | .checkDir() 23 | .generateSubjectPattern() 24 | .extractFolders() 25 | .extractTags() 26 | .isTodo(); 27 | 28 | return this.subjectMetadata; 29 | }; 30 | 31 | removeIrregularSpaces() { 32 | const {subject} = this; 33 | const {removeIrregularSpaces} = StringOps; 34 | this.subject = removeIrregularSpaces(subject); 35 | return this; 36 | }; 37 | 38 | checkDir() { 39 | const {subject} = this; 40 | const {wrapDir, isRTL} = StringOps; 41 | this.subject = isRTL(subject) ? wrapDir(subject): subject; 42 | return this; 43 | }; 44 | 45 | isTodo() { 46 | const {subject} = this; 47 | this.subjectMetadata.isTodo = subject.startsWith('!') ? 1 : 0; 48 | return this; 49 | }; 50 | 51 | // to add the ability to run regex extraction on different languages and different regular emojis, e.g. @joplin -> @xxxxxx. 52 | generateSubjectPattern() { 53 | const {subject} = this; 54 | const allowedSymbols = [' ', '@', '@', '﹫', '#', '♯', '⌗', '⋕', '!']; 55 | const patternFun = (c: string) => allowedSymbols.includes(c) ? c : 'x'; 56 | 57 | this.subjectPattern = Array.from(subject, patternFun) 58 | .join(''); 59 | 60 | return this; 61 | }; 62 | 63 | extractFolders() { 64 | const {subject, subjectPattern} = this; 65 | const folders: string[] = []; 66 | let match: RegExpExecArray; 67 | 68 | while (match = MENTIONS_REGEX.exec(subjectPattern)) { 69 | const mention = Array.from(subject) 70 | .slice(match.index, MENTIONS_REGEX.lastIndex) 71 | .join('') 72 | .trim() 73 | .substring(1); // remove mention symbol 74 | 75 | folders.push(mention); 76 | } 77 | 78 | folders.length && (this.subjectMetadata.folders = folders); 79 | 80 | return this; 81 | }; 82 | 83 | extractTags() { 84 | const {subject, subjectPattern} = this; 85 | const tags: string[] = []; 86 | let match: RegExpExecArray; 87 | 88 | while (match = TAGS_REGEX.exec(subjectPattern)) { 89 | const tag = Array.from(subject) 90 | .slice(match.index, TAGS_REGEX.lastIndex) 91 | .join('') 92 | .trim() 93 | .substring(1); // remove tag symbol 94 | 95 | tags.push(tag); 96 | } 97 | 98 | // To lowercase all tags to avoid overwriting the same tag again. 99 | this.subjectMetadata.tags = [...new Set(tags.map((e) => e.toLowerCase()))]; 100 | 101 | return this; 102 | }; 103 | } 104 | 105 | export default EmailSubjectParser; 106 | -------------------------------------------------------------------------------- /src/core/imap.ts: -------------------------------------------------------------------------------- 1 | import joplin from 'api'; 2 | import * as Imap from 'imap'; 3 | import {ATTACHMENTS, ATTACHMENTS_STYLE, EXPORT_TYPE} from '../constants'; 4 | import {ExportCriteria} from '../model/exportCriteria.model'; 5 | import {PostCriteria} from '../model/postCriteria.model'; 6 | import {Query} from '../model/Query.model'; 7 | import EmailParser from './emailParser'; 8 | import {PostNote} from './postNote'; 9 | import {SetupTempFolder} from './setupTempFolder'; 10 | 11 | export class IMAP { 12 | private imap: Imap = null; 13 | private monitorId = null; 14 | private fromMonitoring: Query = null; 15 | private mailBoxMonitoring = null; 16 | private switcher = 1; 17 | private delayTime = 1000 * 60; 18 | private accountConfig: Imap.Config; 19 | 20 | // To check if there is a query not completed yet. 21 | private pending = false; 22 | view: string = ''; 23 | 24 | constructor(config: Imap.Config) { 25 | this.accountConfig = { 26 | ...config, 27 | authTimeout: 10000, 28 | connTimeout: 30000, 29 | tlsOptions: { 30 | rejectUnauthorized: false, 31 | }, 32 | 33 | }; 34 | this.imap = new Imap(this.accountConfig); 35 | } 36 | 37 | get config() { 38 | return this.accountConfig; 39 | } 40 | 41 | get email() { 42 | return this.accountConfig.user; 43 | } 44 | 45 | init() { 46 | return new Promise((resolve, reject) => { 47 | this.imap.connect(); 48 | 49 | this.imap.once('ready', async ()=> { 50 | console.log('%c--------------------- SUCCESSFUL IMAP CONNECTION --------------------', 'color: Green'); 51 | resolve(); 52 | }); 53 | 54 | this.imap.once('error', function(err: Error) { 55 | reject(err); 56 | }); 57 | }); 58 | } 59 | 60 | setEmailMonitoring(query: Query) { 61 | this.fromMonitoring = query; 62 | } 63 | 64 | setMailBoxMonitoring(query: Query) { 65 | this.mailBoxMonitoring = query; 66 | } 67 | 68 | openBox(mailBox: string, readOnly = false) { 69 | return new Promise((resolve, reject) => { 70 | this.imap.openBox(mailBox, readOnly, (err: Error, box: Imap.Box) => { 71 | if (err) { 72 | reject(err); 73 | } else { 74 | resolve(); 75 | } 76 | }); 77 | }); 78 | } 79 | 80 | search(criteria: any[]) { 81 | return new Promise((resolve, reject) => { 82 | this.imap.search(criteria, (err: Error, uids: number[]) => { 83 | if (err) { 84 | reject(err); 85 | } else { 86 | resolve(uids); 87 | } 88 | }); 89 | }); 90 | } 91 | 92 | state() { 93 | return new Promise(async (resolve, reject) => { 94 | if (!navigator.onLine) { 95 | reject(new Error('No internet Connection')); 96 | } else if (!this.imap) { 97 | reject(new Error('Please Re-login')); 98 | } else if (this.imap.state === 'authenticated') { 99 | resolve(); 100 | } else { 101 | try { 102 | // Reconnecting 103 | await this.init(); 104 | resolve(); 105 | } catch (err) { 106 | reject(err); 107 | } 108 | } 109 | }); 110 | } 111 | 112 | fetchAll(messages: number[], options: Imap.FetchOptions) { 113 | return new Promise((resolve, reject) => { 114 | const fetch = this.imap.fetch(messages, options); 115 | const convertedMessages: string[] = []; 116 | 117 | // For each message 118 | fetch.on('message', (message: Imap.ImapMessage, seqno: number) => { 119 | let data = ''; 120 | 121 | message.on('body', (stream: NodeJS.ReadableStream) => { 122 | stream.on('data', function(chunk: NodeJS.ReadableStream) { 123 | // push data 124 | data += chunk; 125 | }); 126 | }); 127 | 128 | message.once('end', () => { 129 | convertedMessages.push(data); 130 | }); 131 | }); 132 | 133 | // All messages have been fetched of type RFC 822. 134 | fetch.on('end', () => { 135 | resolve(convertedMessages); 136 | }); 137 | 138 | this.imap.once('error', function(err: Error) { 139 | reject(err); 140 | }); 141 | }); 142 | } 143 | 144 | getBoxes() { 145 | return new Promise((resolve, reject)=>{ 146 | this.imap.getBoxes((err, mailBoxes: Imap.MailBoxes)=>{ 147 | if (err) { 148 | reject(err); 149 | } else { 150 | resolve(mailBoxes); 151 | } 152 | }); 153 | }); 154 | } 155 | 156 | getBoxesPath() { 157 | return new Promise<{path: string, value: string}[]>(async (resolve, reject)=>{ 158 | const paths: {path: string, value: string}[] = []; 159 | const boxes = await this.getBoxes(); 160 | 161 | const getPathes = (path: string, value: string, boxes: Imap.MailBoxes)=>{ 162 | for (const box of Object.keys(boxes)) { 163 | let newPath = path + box; 164 | let newValue = value + box; 165 | if (!boxes[box].attribs.includes('\\Noselect')) { 166 | paths.push({value: newValue, path: newPath}); 167 | } 168 | 169 | if (boxes[box].children) { 170 | const children: Imap.MailBoxes = boxes[box].children; 171 | newPath = newPath + '/'; 172 | newValue = newValue + boxes[box].delimiter; 173 | getPathes(newPath, newValue, children); 174 | } 175 | } 176 | }; 177 | getPathes('', '', boxes); 178 | 179 | return resolve(paths); 180 | }); 181 | } 182 | 183 | markAsSeen(messages: number[]) { 184 | return new Promise(async (resolve, reject)=>{ 185 | this.imap.addFlags(messages, ['SEEN'], (err)=>{ 186 | if (err) { 187 | reject(err); 188 | } else { 189 | resolve(); 190 | } 191 | }); 192 | }); 193 | } 194 | 195 | monitor() { 196 | const setupTempFolder: SetupTempFolder = null; 197 | this.monitorId = setInterval(async () => { 198 | if ((this.fromMonitoring || this.mailBoxMonitoring) && !this.pending) { 199 | const {mailBox, criteria, folderId} = this.switcher^1 && this.fromMonitoring ? this.fromMonitoring : this.mailBoxMonitoring || this.fromMonitoring; 200 | this.switcher ^= 1; 201 | 202 | try { 203 | // Check if the connection is still stable. 204 | await this.state(); 205 | 206 | await this.openBox(mailBox); 207 | 208 | const newMessages = await this.search(criteria); 209 | console.log(newMessages, 'new Messages'); 210 | 211 | if (newMessages.length && !this.pending) { 212 | this.pending = true; 213 | 214 | SetupTempFolder.createTempFolder(); 215 | const tempFolderPath = SetupTempFolder.tempFolderPath; 216 | 217 | const data = await this.fetchAll(newMessages, {bodies: ''}); 218 | 219 | const includeAttachments = await joplin.settings.value(ATTACHMENTS); 220 | const exportType = await joplin.settings.value(EXPORT_TYPE); 221 | const attachmentsStyle = await joplin.settings.value(ATTACHMENTS_STYLE); 222 | const exportCriteria: ExportCriteria = {includeAttachments, exportType, attachmentsStyle}; 223 | 224 | for (let i = 0; i < data.length; i++) { 225 | // post email 226 | const post = new PostNote(); 227 | const ep = new EmailParser(); 228 | const temp = await ep.parse(data[i]); 229 | const postCriteria : PostCriteria = { 230 | emailContent: temp, 231 | tempFolderPath: tempFolderPath, 232 | exportCriteria: exportCriteria, 233 | }; 234 | 235 | if (folderId) { 236 | postCriteria['folderId'] = folderId, 237 | postCriteria['tags'] = []; 238 | } 239 | 240 | await post.post(postCriteria); 241 | } 242 | 243 | await this.markAsSeen(newMessages); 244 | 245 | SetupTempFolder.removeTempFolder(); 246 | this.pending = false; 247 | } 248 | } catch (err) { 249 | // Revoke the query 250 | this.mailBoxMonitoring = this.fromMonitoring = null; 251 | this.pending = false; 252 | if (setupTempFolder) { 253 | SetupTempFolder.removeTempFolder(); 254 | } 255 | joplin.views.panels.postMessage(this.view, 'monitoringError'); 256 | alert(err); 257 | throw err; 258 | } 259 | } 260 | }, this.delayTime); 261 | } 262 | 263 | close() { 264 | clearInterval(this.monitorId); 265 | this.imap.end(); 266 | console.log('%c--------------------- Close IMAP CONNECTION --------------------', 'color: Red'); 267 | } 268 | } 269 | -------------------------------------------------------------------------------- /src/core/postAttachments.ts: -------------------------------------------------------------------------------- 1 | import * as path from 'path'; 2 | import joplin from 'api'; 3 | import {AttachmentProperties} from '../model/attachmentProperties.model'; 4 | import {Attachment} from 'postal-mime'; 5 | const fs = joplin.require('fs-extra'); 6 | 7 | export class Attachments { 8 | tempFolderPath: string; 9 | attachments: Attachment[]; 10 | 11 | constructor(attachments: Attachment[], tempFolderPath: string) { 12 | this.attachments = attachments.filter((e: Attachment)=>e.filename !== ''); 13 | this.tempFolderPath = tempFolderPath; 14 | } 15 | 16 | 17 | async postAttachments(): Promise { 18 | const attachmentsProp: AttachmentProperties[] = []; 19 | const tempFolder = this.tempFolderPath; 20 | 21 | // for each attachment will create an actual file of the attachment and posting to Joplin. 22 | for (let i = 0; i < this.attachments.length; i++) { 23 | const {contentId, filename, mimeType} = this.attachments[i]; 24 | const filePath = path.join(tempFolder, this.attachments[i].filename); 25 | 26 | // to create a file 27 | fs.writeFileSync(filePath, Buffer.from(this.attachments[i].content)); 28 | 29 | // To post a file to Joplin 30 | const resource = await joplin.data.post( 31 | ['resources'], 32 | null, 33 | {title: filename}, // Resource metadata 34 | [ 35 | { 36 | path: filePath, // Actual file 37 | }, 38 | ], 39 | ); 40 | attachmentsProp.push({contentId: contentId, id: resource.id, fileName: filename, mimeType: mimeType}); 41 | } 42 | 43 | return attachmentsProp; 44 | } 45 | 46 | async postInlineAttachment(attachment: Attachment): Promise { 47 | const tempFolder = this.tempFolderPath; 48 | 49 | // Will create an actual file of the attachment and post it to Joplin. 50 | const {contentId, filename, mimeType, content} = attachment; 51 | const filePath = path.join(tempFolder, filename); 52 | 53 | // to create a file 54 | fs.writeFileSync(filePath, Buffer.from(content)); 55 | 56 | // To post a file to Joplin 57 | const resource = await joplin.data.post( 58 | ['resources'], 59 | null, 60 | {title: filename}, // Resource metadata 61 | [ 62 | { 63 | path: filePath, // Actual file 64 | }, 65 | ], 66 | ); 67 | 68 | return {contentId: contentId, id: resource.id, fileName: filename, mimeType: mimeType}; 69 | } 70 | } 71 | 72 | 73 | -------------------------------------------------------------------------------- /src/core/postNote.ts: -------------------------------------------------------------------------------- 1 | import joplin from 'api'; 2 | import {Attachments} from './postAttachments'; 3 | import {Note} from '../model/note.model'; 4 | import {AttachmentProperties} from 'src/model/attachmentProperties.model'; 5 | import {Tag} from '../model/tag.model'; 6 | import {ExportCriteria} from '../model/exportCriteria.model'; 7 | import {isPostByFolderId, isPostBySubject, PostCriteria} from '../model/postCriteria.model'; 8 | import {convert as htmlToText} from 'html-to-text'; 9 | import {Attachment} from 'postal-mime'; 10 | import EmailSubjectParser from './emailSubjectParser'; 11 | 12 | export class PostNote { 13 | emailHtmlBody: string; 14 | subject: string; 15 | tempFolderPath: string; 16 | attachments: Attachment[]; 17 | folders: string[] = []; 18 | note: Note = {title: null, parent_id: null, body: null, is_todo: 0, body_html: null, markup_language: null}; 19 | 20 | async createFolder(folder: string): Promise { 21 | return await joplin.data.post(['folders'], null, {title: folder}); 22 | } 23 | 24 | async createTag(tag: string): Promise { 25 | return await joplin.data.post(['tags'], null, {title: tag}); 26 | } 27 | 28 | async addFolders(folders: string[]): Promise { 29 | let joplinFolders : {items: any[], has_more: boolean}; 30 | let page = 1; 31 | // copy of tags 32 | const tempFolders = [...folders]; 33 | const emailFolders: any[] = []; 34 | 35 | do { 36 | joplinFolders = await joplin.data.get(['folders'], {page: page++}); 37 | 38 | for (let i = 0; i < joplinFolders.items.length; i++) { 39 | const joplinFolder: any = joplinFolders.items[i]; 40 | 41 | if (tempFolders.includes(joplinFolder.title)) { 42 | emailFolders.push(joplinFolder); 43 | const index = tempFolders.indexOf(joplinFolder.title); 44 | tempFolders.splice(index, 1); 45 | } 46 | } 47 | } while (joplinFolders.has_more); 48 | 49 | for (let i = 0; i < tempFolders.length; i++) { 50 | const folder: any = await this.createFolder(tempFolders[i]); 51 | emailFolders.push(folder); 52 | } 53 | return emailFolders; 54 | } 55 | 56 | async addTags(tags: string[]): Promise { 57 | let joplinTags : {items: Tag[], has_more: boolean}; 58 | let page = 1; 59 | // copy of tags 60 | const tempTags = [...tags]; 61 | const emailTags: Tag[] = []; 62 | 63 | do { 64 | joplinTags = await joplin.data.get(['tags'], {page: page++}); 65 | 66 | for (let i = 0; i < joplinTags.items.length; i++) { 67 | const joplinTag: Tag = joplinTags.items[i]; 68 | 69 | if (tempTags.includes(joplinTag.title)) { 70 | emailTags.push(joplinTag); 71 | const index = tempTags.indexOf(joplinTag.title); 72 | tempTags.splice(index, 1); 73 | } 74 | } 75 | } while (joplinTags.has_more); 76 | 77 | for (let i = 0; i < tempTags.length; i++) { 78 | const tag: Tag = await this.createTag(tempTags[i]); 79 | emailTags.push(tag); 80 | } 81 | 82 | return emailTags; 83 | } 84 | 85 | async post(postCriteria: PostCriteria): Promise { 86 | this.attachments = postCriteria['emailContent'].attachments; 87 | this.subject = postCriteria['emailContent'].subject; 88 | this.emailHtmlBody = postCriteria['emailContent'].html; 89 | this.tempFolderPath = postCriteria['tempFolderPath']; 90 | let emailTags = []; 91 | let emailFolders = []; 92 | 93 | // Converting email to (html, markdown, text) depends on what export type is in the plugin settings. 94 | await this.convert(postCriteria['exportCriteria']); 95 | 96 | if (isPostByFolderId(postCriteria)) { 97 | this.note['parent_id'] = postCriteria['folderId']; 98 | const subject = postCriteria['emailContent'].subject; 99 | const emailText = htmlToText(this.emailHtmlBody, {wordwrap: 130, selectors: [{selector: 'img', format: 'skip'}]}); 100 | const firstLine = (emailText || '').trim().split('\n')[0]; 101 | const emailSubjectParser = new EmailSubjectParser(subject + ' ' + firstLine); 102 | const {tags, isTodo} = emailSubjectParser.parse(); 103 | this.note['is_todo'] = isTodo; 104 | 105 | emailTags = await this.addTags([...tags, ...postCriteria['tags']]); 106 | 107 | // Post the note to Joplin. 108 | const note = await joplin.data.post(['notes'], null, this.note); 109 | 110 | // assign the tags for the note. 111 | for (let j = 0; j < emailTags.length; j++) { 112 | const tag = emailTags[j]; 113 | await joplin.data.post(['tags', tag.id, 'notes'], null, {id: note.id}); 114 | } 115 | } else if (isPostBySubject(postCriteria)) { 116 | const subject = postCriteria['emailContent'].subject; 117 | const emailText = htmlToText(this.emailHtmlBody, {wordwrap: 130, selectors: [{selector: 'img', format: 'skip'}]}); 118 | const firstLine = (emailText || '').trim().split('\n')[0]; 119 | const emailSubjectParser = new EmailSubjectParser(subject + ' ' + firstLine); 120 | const {folders, tags, isTodo} = emailSubjectParser.parse(); 121 | this.note['is_todo'] = isTodo; 122 | 123 | emailTags = await this.addTags(tags); 124 | emailFolders = await this.addFolders(folders); 125 | 126 | for (let i = 0; i < emailFolders.length; i++) { 127 | this.note['parent_id'] = emailFolders[i].id; 128 | const note = await joplin.data.post(['notes'], null, this.note); 129 | 130 | for (let j = 0; j < emailTags.length; j++) { 131 | const tag = emailTags[j]; 132 | await joplin.data.post(['tags', tag.id, 'notes'], null, {id: note.id}); 133 | } 134 | } 135 | } 136 | } 137 | 138 | async convert(exportNote: ExportCriteria): Promise { 139 | // to get only the HTML body of the email and ignore unnecessary data. 140 | this.emailHtmlBody = new DOMParser().parseFromString(this.emailHtmlBody, 'text/html').body.innerHTML; 141 | 142 | const attachmentsLinks = exportNote['includeAttachments']? await this.addAttachments(exportNote['attachmentsStyle']): ''; 143 | const {exportType} = exportNote; 144 | 145 | if (exportType === 'HTML') { 146 | // Replace each attachment img src with the ID of the attachment location in Joplin resources. 147 | await this.addInlineImages(); 148 | 149 | this.note['title'] = this.subject; 150 | this.note['body'] = this.emailHtmlBody + attachmentsLinks; 151 | this.note['markup_language'] = 2; 152 | } else if (exportType === 'Markdown') { 153 | // Replace each attachment img src with the ID of the attachment location in Joplin resources. 154 | await this.addInlineImages(); 155 | 156 | this.note['title'] = this.subject; 157 | this.note['body_html'] = this.emailHtmlBody + attachmentsLinks; 158 | this.note['markup_language'] = 1; 159 | } else if (exportType === 'Text') { 160 | this.note['title'] = this.subject; 161 | 162 | const domParser = new DOMParser(); 163 | const dom: Document = domParser.parseFromString(this.emailHtmlBody, 'text/html'); 164 | const images = dom.getElementsByTagName('img'); 165 | 166 | // Remove all images 167 | while (images.length > 0) { 168 | images[0].parentNode.removeChild(images[0]); 169 | } 170 | 171 | const htmlToText = dom.body.innerHTML 172 | .replace(/<\/?(table|tr|td|th)\b[^>]*>/gi, '\n\n') 173 | .replace(/\r?\n/g, '\u0001') 174 | 175 | // convert linebreak placeholders back to newlines 176 | .replace(/\u0001/g, '\n'); 177 | 178 | this.note['body_html'] = htmlToText + attachmentsLinks; 179 | this.note['markup_language'] = 1; 180 | } 181 | } 182 | 183 | async addInlineImages(): Promise { 184 | const domParser = new DOMParser(); 185 | const dom: Document = domParser.parseFromString(this.emailHtmlBody, 'text/html'); 186 | const imgs = dom.body.querySelectorAll('img'); 187 | const postAttachments = new Attachments(this.attachments, this.tempFolderPath); 188 | 189 | for (let i = 0; i < imgs.length; i++) { 190 | const img = imgs[i]; 191 | 192 | // replace with inline attachment. 193 | if (/^cid:/.test(img.src)) { 194 | const cid = img.src.substr(4).trim(); 195 | const attachment = this.attachments.find((attachment)=>attachment.contentId && attachment.contentId === `<${cid}>`); 196 | 197 | if (attachment) { 198 | const resource = await postAttachments.postInlineAttachment(attachment); 199 | img.src = `:/${resource.id}`; 200 | } 201 | } 202 | }; 203 | this.emailHtmlBody = dom.body.innerHTML; 204 | } 205 | 206 | async addAttachments(attachmentsStyle: 'Table' | 'Link'): Promise { 207 | const postAttachments = new Attachments(this.attachments, this.tempFolderPath); 208 | const attachmentsProp: AttachmentProperties[] = await postAttachments.postAttachments(); 209 | 210 | let attachments: string =''; 211 | let attachmentsLinks: string = ''; 212 | 213 | if (attachmentsStyle === 'Link') { 214 | attachmentsProp.forEach((att)=>{ 215 | const link = `${att.fileName}
`; 216 | attachments += link; 217 | }); 218 | attachmentsLinks = attachments !== ''? `

Attachments

${attachments}` : ''; 219 | } else { 220 | attachmentsProp.forEach((att)=>{ 221 | if (att.mimeType.startsWith('image/')) { 222 | const link = `${att.fileName} ${att.fileName} `; 223 | attachments+= link; 224 | } else { 225 | const link =`${att.fileName} ${att.fileName} `; 226 | attachments+= link; 227 | } 228 | }); 229 | attachmentsLinks = attachments !== ''? `

Attachments

${attachments}
FilenameLink
`: ''; 230 | } 231 | return attachmentsLinks; 232 | } 233 | } 234 | -------------------------------------------------------------------------------- /src/core/setupTempFolder.ts: -------------------------------------------------------------------------------- 1 | import {tmpdir} from 'os'; 2 | import * as path from 'path'; 3 | import joplin from 'api'; 4 | const fs = joplin.require('fs-extra'); 5 | 6 | 7 | export class SetupTempFolder { 8 | static tempFolder = path.join(tmpdir(), 'joplin-email-plugin'); 9 | 10 | static get tempFolderPath() { 11 | return SetupTempFolder.tempFolder; 12 | } 13 | 14 | static createTempFolder() { 15 | fs.mkdirSync(SetupTempFolder.tempFolder, {recursive: true}); 16 | } 17 | 18 | static removeTempFolder() { 19 | fs.rmdirSync(SetupTempFolder.tempFolder, {recursive: true}); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import joplin from 'api'; 2 | import App from './init'; 3 | 4 | const app = new App(); 5 | 6 | joplin.plugins.register({ 7 | onStart: async function() { 8 | console.info('Email Plugin Started!'); 9 | await app.init(); 10 | }, 11 | }); 12 | -------------------------------------------------------------------------------- /src/init.ts: -------------------------------------------------------------------------------- 1 | import joplin from 'api'; 2 | import {ToolbarButtonLocation, MenuItemLocation} from 'api/types'; 3 | import {SECTION_NAME, PLUGIN_ICON} from './constants'; 4 | import {setting} from './setting'; 5 | import {Panel} from './ui/panel'; 6 | 7 | 8 | export default class App { 9 | panel: Panel; 10 | 11 | async init() { 12 | await this.setupSetting(); 13 | await this.setupToolbar(); 14 | 15 | this.panel = new Panel(); 16 | await this.panel.setupPanel(); 17 | } 18 | 19 | async setupSetting() { 20 | await joplin.settings.registerSection(SECTION_NAME, { 21 | label: 'Email Plugin', 22 | iconName: PLUGIN_ICON, 23 | description: 'Fetch your important emails as notes.', 24 | }); 25 | 26 | await joplin.settings.registerSettings(setting); 27 | } 28 | 29 | async setupToolbar() { 30 | await joplin.commands.register({ 31 | name: 'toolBar', 32 | label: 'Email Plugin', 33 | iconName: PLUGIN_ICON, 34 | execute: async () => { 35 | // When clicking on an email icon or an email plugin button in Tools, it will close the panel if the panel is open and vice versa. 36 | this.panel.closeOpenPanel(); 37 | }, 38 | }); 39 | 40 | // Two starting points. 41 | await joplin.views.toolbarButtons.create('toolbarButton', 'toolBar', ToolbarButtonLocation.NoteToolbar); 42 | await joplin.views.menuItems.create('menuItem', 'toolBar', MenuItemLocation.Tools); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 1, 3 | "id": "Bishoy.EmailPlugin", 4 | "app_min_version": "2.7", 5 | "version": "1.0.0", 6 | "name": "Email Plugin", 7 | "description": "Fetch your important emails as notes.", 8 | "author": "Bishoy Magdy", 9 | "homepage_url": "https://github.com/joplin/plugin-email", 10 | "repository_url": "https://github.com/joplin/plugin-email", 11 | "keywords": ["Email", "email"] 12 | } -------------------------------------------------------------------------------- /src/model/Query.model.ts: -------------------------------------------------------------------------------- 1 | 2 | export interface Query { 3 | 4 | mailBox: string, 5 | criteria: string[] 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/model/account.model.ts: -------------------------------------------------------------------------------- 1 | import {Config} from 'imap'; 2 | 3 | export interface Account{ 4 | 'email': Config 5 | } 6 | -------------------------------------------------------------------------------- /src/model/attachmentProperties.model.ts: -------------------------------------------------------------------------------- 1 | 2 | export interface AttachmentProperties{ 3 | contentId: string, 4 | id: string, 5 | fileName: string, 6 | mimeType: string 7 | } 8 | -------------------------------------------------------------------------------- /src/model/emailProvider.model.ts: -------------------------------------------------------------------------------- 1 | 2 | export interface EmailProvider { 3 | type: string, 4 | host: string, 5 | port: number, 6 | tls?: boolean, 7 | } 8 | -------------------------------------------------------------------------------- /src/model/exportCriteria.model.ts: -------------------------------------------------------------------------------- 1 | export interface ExportCriteria{ 2 | exportType: 'HTML' | 'Markdown' | 'Text', 3 | includeAttachments: boolean, 4 | attachmentsStyle: 'Table' | 'Link' 5 | } 6 | -------------------------------------------------------------------------------- /src/model/exportNote.model.ts: -------------------------------------------------------------------------------- 1 | export interface ExportNote{ 2 | title: string, 3 | parent_id:string, 4 | body?: string, 5 | body_html?: string, 6 | markup_language: number 7 | } 8 | -------------------------------------------------------------------------------- /src/model/folder.model.ts: -------------------------------------------------------------------------------- 1 | export interface Folder{ 2 | id: string, 3 | parent_id: string, 4 | title: string 5 | } 6 | -------------------------------------------------------------------------------- /src/model/imapConfig.model.ts: -------------------------------------------------------------------------------- 1 | 2 | export interface ImapConfig { 3 | user: string, 4 | password: string, 5 | type: string, 6 | host: string, 7 | port: number, 8 | tls?: boolean, 9 | tlsOptions?: object, 10 | } 11 | -------------------------------------------------------------------------------- /src/model/joplinFolders.model.ts: -------------------------------------------------------------------------------- 1 | import {Folder} from './folder.model'; 2 | 3 | export interface JopinFolders{ 4 | 5 | items: Folder[], 6 | has_more: boolean 7 | } 8 | -------------------------------------------------------------------------------- /src/model/joplinTags.model.ts: -------------------------------------------------------------------------------- 1 | import {Tag} from './tag.model'; 2 | 3 | export interface JoplinTags{ 4 | items: Tag[], 5 | has_more: boolean 6 | } 7 | -------------------------------------------------------------------------------- /src/model/message.model.ts: -------------------------------------------------------------------------------- 1 | import {Config} from 'imap'; 2 | import {ImapConfig} from './imapConfig.model'; 3 | 4 | export interface Login { 5 | login: true, 6 | email: string, 7 | password: string 8 | } 9 | 10 | // Type predicates 11 | export function isLogin(message: any): message is Login { 12 | return 'login' in message && 'email' in message && 'password' in message; 13 | } 14 | 15 | export interface Hide { 16 | hide: boolean 17 | } 18 | 19 | // Type predicates 20 | export function isHide(message: any): message is Hide { 21 | return 'hide' in message; 22 | } 23 | 24 | 25 | export interface ManualConnectionScreen { 26 | manualConnectionScreen: boolean 27 | } 28 | 29 | // Type predicates 30 | export function isManualConnectionScreen(message: any): message is ManualConnectionScreen { 31 | return 'manualConnectionScreen' in message; 32 | } 33 | 34 | export interface LoginScreen { 35 | loginScreen: boolean 36 | } 37 | 38 | // Type predicates 39 | export function isLoginScreen(message: any): message is LoginScreen { 40 | return 'loginScreen' in message; 41 | } 42 | 43 | export interface LoginManually extends ImapConfig { 44 | loginManually: boolean, 45 | } 46 | 47 | // Type predicates 48 | export function isLoginManually(message: any): message is LoginManually { 49 | return 'loginManually' in message && 'user' in message && 'password' in message && 50 | 'host' in message && 'port' in message && 'tls' in message; 51 | } 52 | 53 | export interface SearchByFrom { 54 | state: 'open' | 'close', 55 | from?: string 56 | } 57 | 58 | // Type predicates 59 | export function isMonitorEmail(message: any): message is SearchByFrom { 60 | if (message.state === 'close') { 61 | return 'state' in message && 'from' in message; 62 | } else { 63 | return 'state' in message; 64 | } 65 | } 66 | 67 | export interface UploadMessagesScreen{ 68 | uploadMessagesScreen: boolean, 69 | } 70 | 71 | // Type predicates 72 | export function isUploadMessagesScreen(message: any): message is UploadMessagesScreen { 73 | return 'uploadMessagesScreen' in message; 74 | } 75 | 76 | export interface EMLtoNote{ 77 | emlFiles: string[], 78 | folderId: string, 79 | tags: string[], 80 | exportType: 'HTML' | 'Markdown' | 'Text', 81 | includeAttachments: boolean, 82 | attachmentsStyle: 'Table' | 'Link', 83 | } 84 | 85 | // Type predicates 86 | export function isUploadMessages(message: any): message is EMLtoNote { 87 | return 'emlFiles' in message && 'folderId' in message && 'tags' in message && 'exportType' in message && 'includeAttachments' in message && 'attachmentsStyle' in message; 88 | } 89 | 90 | export interface Logout{ 91 | logout: boolean 92 | } 93 | 94 | // Type predicates 95 | export function isLogout(message: any): message is Logout { 96 | return 'logout' in message; 97 | } 98 | 99 | export interface SelectAccount{ 100 | account: Config 101 | } 102 | 103 | // Type predicates 104 | export function isSelectAccount(message: any): message is SelectAccount { 105 | return 'account' in message; 106 | } 107 | 108 | export interface MonitorMailBox{ 109 | monitorMailBox: boolean, 110 | mailbox?: string, 111 | folderId?: string, 112 | } 113 | 114 | // Type predicates 115 | export function isMonitorMailBox(message: any): message is MonitorMailBox { 116 | return 'monitorMailBox' in message; 117 | } 118 | 119 | export interface Refresh{ 120 | refresh: boolean, 121 | 122 | } 123 | 124 | // Type predicates 125 | export function isRefresh(message: any): message is Refresh { 126 | return 'refresh' in message; 127 | } 128 | 129 | export type Message = Login | ManualConnectionScreen | Hide | LoginScreen | LoginManually | SearchByFrom | UploadMessagesScreen | EMLtoNote | Logout | SelectAccount | MonitorMailBox | Refresh; 130 | -------------------------------------------------------------------------------- /src/model/note.model.ts: -------------------------------------------------------------------------------- 1 | export interface Note{ 2 | title: string, 3 | parent_id:string, 4 | body?: string, 5 | body_html?: string, 6 | is_todo: number, 7 | markup_language: number 8 | } 9 | -------------------------------------------------------------------------------- /src/model/postCriteria.model.ts: -------------------------------------------------------------------------------- 1 | import {Email} from 'postal-mime'; 2 | import {ExportCriteria} from './exportCriteria.model'; 3 | 4 | export interface PostCriteria{ 5 | emailContent: Email, 6 | exportCriteria: ExportCriteria, 7 | tempFolderPath: string, 8 | folderId?: string, 9 | tags?: string[], 10 | } 11 | 12 | export function isPostBySubject(postCriteria: PostCriteria) { 13 | return 'emailContent' in postCriteria && 'exportCriteria' in postCriteria && 'tempFolderPath' in postCriteria && Object.keys(postCriteria).length === 3; 14 | } 15 | 16 | export function isPostByFolderId(postCriteria: PostCriteria) { 17 | return 'emailContent' in postCriteria && 'exportCriteria' in postCriteria && 'tempFolderPath' in postCriteria && 'folderId' in postCriteria && 'tags' in postCriteria; 18 | } 19 | -------------------------------------------------------------------------------- /src/model/state.model.ts: -------------------------------------------------------------------------------- 1 | import {Config} from 'imap'; 2 | 3 | export interface State{ 4 | accountConfig: Config, 5 | from: string, 6 | isEmailMonitor: boolean, 7 | isMailBoxMonitor: boolean, 8 | mailBox: string, 9 | mailBoxes: {path: string, value: string}[], 10 | folderId: string, 11 | } 12 | -------------------------------------------------------------------------------- /src/model/subjectMetadata.model.ts: -------------------------------------------------------------------------------- 1 | interface SubjectMetadata{ 2 | folders: string [], 3 | tags: string [], 4 | isTodo: number, 5 | } 6 | 7 | export default SubjectMetadata; 8 | -------------------------------------------------------------------------------- /src/model/tag.model.ts: -------------------------------------------------------------------------------- 1 | export interface Tag{ 2 | id: string, 3 | parent_id: string, 4 | title: string 5 | } 6 | -------------------------------------------------------------------------------- /src/setting.ts: -------------------------------------------------------------------------------- 1 | import {SettingItemType} from 'api/types'; 2 | import {SECTION_NAME, EXPORT_TYPE, ATTACHMENTS, ATTACHMENTS_STYLE, ACCOUNTS, LAST_STATE} from './constants'; 3 | 4 | export const setting = { 5 | 6 | [EXPORT_TYPE]: { 7 | value: 'HTML', 8 | type: SettingItemType.String, 9 | section: SECTION_NAME, 10 | isEnum: true, 11 | public: true, 12 | label: 'Export Type', 13 | options: { 14 | 'HTML': 'HTML', 15 | 'Markdown': 'Markdown', 16 | 'Text': 'Text', 17 | }, 18 | }, 19 | 20 | [ATTACHMENTS]: { 21 | value: true, 22 | type: SettingItemType.Bool, 23 | section: SECTION_NAME, 24 | public: true, 25 | label: 'Include Attachments', 26 | 27 | }, 28 | 29 | [ATTACHMENTS_STYLE]: { 30 | value: 'Table', 31 | type: SettingItemType.String, 32 | section: SECTION_NAME, 33 | isEnum: true, 34 | public: true, 35 | label: 'Attachments Style', 36 | options: { 37 | 'Table': 'Table', 38 | 'Link': 'Link', 39 | }, 40 | description: 'Note: Table Style displays images and videos in the note.', 41 | }, 42 | 43 | [ACCOUNTS]: { 44 | value: {}, 45 | type: SettingItemType.Object, 46 | section: SECTION_NAME, 47 | secure: true, 48 | public: true, 49 | label: 'Accounts', 50 | }, 51 | 52 | [LAST_STATE]: { 53 | value: {}, 54 | type: SettingItemType.Object, 55 | section: SECTION_NAME, 56 | secure: true, 57 | public: true, 58 | label: 'Last_State', 59 | }, 60 | 61 | }; 62 | -------------------------------------------------------------------------------- /src/ui/img/icon.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joplin/plugin-email/f59be8d0ce26cb974b9661fc3080a9e464999a4d/src/ui/img/icon.webp -------------------------------------------------------------------------------- /src/ui/panel.ts: -------------------------------------------------------------------------------- 1 | import joplin from 'api'; 2 | import JoplinViewsPanels from 'api/JoplinViewsPanels'; 3 | import {Message, Login, isLogin, isHide, isManualConnectionScreen, isLoginScreen, isLoginManually, isMonitorEmail, SearchByFrom, isUploadMessagesScreen, isUploadMessages, EMLtoNote, isLogout, isSelectAccount, SelectAccount, isMonitorMailBox, MonitorMailBox, isRefresh} from '../model/message.model'; 4 | import {ImapConfig} from '../model/imapConfig.model'; 5 | import {emailConfigure} from '../core/emailConfigure'; 6 | import {IMAP} from '../core/imap'; 7 | import {PostNote} from '../core/postNote'; 8 | import EmailParser from '../core/emailParser'; 9 | import {SetupTempFolder} from '../core/setupTempFolder'; 10 | import {ExportCriteria} from '../model/exportCriteria.model'; 11 | import {mainScreen, manualScreen, loginScreen, uploadMessagesScreen, loadingScreen} from './screens'; 12 | import {State} from '../model/state.model'; 13 | import {Config} from 'imap'; 14 | import {PostCriteria} from '../model/postCriteria.model'; 15 | import {ACCOUNTS, LAST_STATE} from '../constants'; 16 | import {Email} from 'postal-mime'; 17 | 18 | export class Panel { 19 | panels: JoplinViewsPanels; 20 | view: string; 21 | visibility: boolean; 22 | account = null; 23 | defaultState: State = {accountConfig: null, from: '', isEmailMonitor: false, mailBox: null, mailBoxes: null, isMailBoxMonitor: false, folderId: null}; 24 | lastState: State = {...this.defaultState}; 25 | 26 | async setupPanel() { 27 | if (this.view) { 28 | await this.closeOpenPanel(); 29 | return; 30 | } 31 | this.panels = joplin.views.panels; 32 | 33 | this.view = await this.panels.create('panel'); 34 | 35 | // Bootstrap v5.1.3. 36 | await this.addScript('./ui/style/bootstrap.css'); 37 | await this.addScript('./ui/style/style.css'); 38 | 39 | // for tags input style 40 | await this.addScript('./ui/style/tagify.css'); 41 | await this.addScript('./ui/style/tagify.js'); 42 | 43 | await this.addScript('./ui/webview.js'); 44 | 45 | // To get the last state before the user exits from Joplin. 46 | const state: State = await joplin.settings.value(LAST_STATE); 47 | 48 | if (state.accountConfig) { 49 | try { 50 | const htmlLoadingScreen = loadingScreen(); 51 | await this.setHtml(htmlLoadingScreen); 52 | this.lastState = {...state}; 53 | await this.login(this.lastState['accountConfig']); 54 | 55 | if (state.isEmailMonitor) { 56 | this.account.setEmailMonitoring({ 57 | mailBox: 'inbox', 58 | criteria: [['FROM', state.from], 'UNSEEN'], 59 | }); 60 | } 61 | if (state.isMailBoxMonitor) { 62 | this.account.setMailBoxMonitoring({ 63 | mailBox: state.mailBox, 64 | folderId: state.folderId, 65 | criteria: ['ALL', 'UNSEEN'], 66 | }); 67 | } 68 | const htmlMainScreen = await mainScreen(this.lastState); 69 | await this.setHtml(htmlMainScreen); 70 | } catch (err) { 71 | alert(err); 72 | const htmlLoginScreen = await loginScreen(); 73 | await this.setHtml(htmlLoginScreen); 74 | throw err; 75 | } 76 | } else { 77 | // display the login screen 78 | const htmlLoginScreen = await loginScreen(); 79 | await this.setHtml(htmlLoginScreen); 80 | } 81 | await this.constructBridge(); 82 | } 83 | 84 | async setHtml(html: string) { 85 | await this.panels.setHtml(this.view, html); 86 | } 87 | 88 | async addScript(path: string) { 89 | await this.panels.addScript(this.view, path); 90 | } 91 | 92 | async closeOpenPanel() { 93 | this.visibility = await joplin.views.panels.visible(this.view); 94 | await joplin.views.panels.show(this.view, !this.visibility); 95 | } 96 | // establishing a bridge between WebView and a plugin. 97 | async constructBridge() { 98 | await this.panels.onMessage(this.view, async (message: Message) => { 99 | this.bridge(message); 100 | }); 101 | } 102 | 103 | async login(config: Config) { 104 | this.account = new IMAP(config); 105 | await this.account.init(); 106 | this.account.view = this.view; 107 | this.account.monitor(); 108 | const mailBoxes = await this.account.getBoxesPath(); 109 | this.lastState['mailBoxes'] = mailBoxes; 110 | this.lastState['accountConfig'] = this.account.config; 111 | const htmlMainScreen = await mainScreen(this.lastState); 112 | await this.setHtml(htmlMainScreen); 113 | await joplin.settings.setValue(LAST_STATE, this.lastState); 114 | 115 | // to add or update account config 116 | const accoutns = await joplin.settings.value(ACCOUNTS); 117 | accoutns[this.account.email] = this.account.config; 118 | joplin.settings.setValue(ACCOUNTS, accoutns); 119 | } 120 | 121 | async bridge(message: Message) { 122 | if (isLoginScreen(message)) { 123 | // close old account connection if any. 124 | if (this.account) { 125 | this.account.close(); 126 | this.account = null; 127 | } 128 | const htmlLoginScreen = await loginScreen(); 129 | await this.setHtml(htmlLoginScreen); 130 | } else if (isLogin(message)) { 131 | try { 132 | // It will alert the user using the manual connection if it can't find an email provider in the email providers list. 133 | const imapConfig: ImapConfig = emailConfigure(message as Login); 134 | await this.login(imapConfig); 135 | } catch (err) { 136 | alert(err); 137 | throw err; 138 | } finally { 139 | this.panels.postMessage(this.view, 'enableLoginScreen'); 140 | } 141 | } else if (isManualConnectionScreen(message)) { 142 | const htmlManualScreen = manualScreen(); 143 | await this.setHtml(htmlManualScreen); 144 | } else if (isLoginManually(message)) { 145 | try { 146 | // close old account connection if any 147 | if (this.account) { 148 | this.account.close(); 149 | this.account = null; 150 | } 151 | // If a connection is established, it will display the main screen and start monitoring waiting for any query. 152 | await this.login(message as ImapConfig); 153 | } catch (err) { 154 | alert(err); 155 | throw err; 156 | } finally { 157 | this.panels.postMessage(this.view, 'enableManualLoginScreen'); 158 | } 159 | } else if (isMonitorEmail(message)) { 160 | const query: Message = message as SearchByFrom; 161 | 162 | if (query.state === 'close') { 163 | this.account.setEmailMonitoring({ 164 | mailBox: 'inbox', 165 | criteria: [['FROM', query.from], 'UNSEEN'], 166 | }); 167 | this.lastState['from'] = query.from; 168 | this.lastState['isEmailMonitor'] = true; 169 | 170 | const htmlMainScreen = await mainScreen(this.lastState); 171 | await this.setHtml(htmlMainScreen); 172 | await joplin.settings.setValue(LAST_STATE, this.lastState); 173 | } else { 174 | this.lastState['isEmailMonitor'] = false; 175 | this.account.setEmailMonitoring(null); 176 | 177 | const htmlMainScreen = await mainScreen(this.lastState); 178 | await this.setHtml(htmlMainScreen); 179 | await joplin.settings.setValue(LAST_STATE, this.lastState); 180 | } 181 | } else if (isMonitorMailBox(message)) { 182 | const query = message as MonitorMailBox; 183 | 184 | if (query.monitorMailBox) { 185 | this.account.setMailBoxMonitoring({ 186 | mailBox: query.mailbox, 187 | criteria: ['ALL', 'UNSEEN'], 188 | folderId: query.folderId, 189 | }); 190 | 191 | this.lastState['isMailBoxMonitor'] = true; 192 | this.lastState['mailBox'] = query.mailbox; 193 | this.lastState['folderId'] = query.folderId; 194 | await joplin.settings.setValue(LAST_STATE, this.lastState); 195 | const htmlMainScreen = await mainScreen(this.lastState); 196 | await this.setHtml(htmlMainScreen); 197 | } else { 198 | this.account.setMailBoxMonitoring(null); 199 | 200 | this.lastState['isMailBoxMonitor'] = false; 201 | await joplin.settings.setValue(LAST_STATE, this.lastState); 202 | const htmlMainScreen = await mainScreen(this.lastState); 203 | await this.setHtml(htmlMainScreen); 204 | } 205 | } else if (isUploadMessagesScreen(message)) { 206 | const htmlUploadMessagesScreen = await uploadMessagesScreen(); 207 | await this.setHtml(htmlUploadMessagesScreen); 208 | } else if (isUploadMessages(message)) { 209 | const {emlFiles, tags, folderId, exportType, includeAttachments, attachmentsStyle} = message as EMLtoNote; 210 | const exportCriteria: ExportCriteria = {exportType, includeAttachments, attachmentsStyle}; 211 | try { 212 | const tempFolderPath = SetupTempFolder.tempFolderPath; 213 | SetupTempFolder.createTempFolder(); 214 | 215 | for (let i = 0; i < emlFiles.length; i++) { 216 | const parser = new EmailParser(); 217 | const emailContent: Email = await parser.parse(emlFiles[i]); 218 | const note = new PostNote(); 219 | const postCriteria: PostCriteria = {emailContent, exportCriteria, tempFolderPath, folderId, tags}; 220 | await note.post(postCriteria); 221 | } 222 | } catch (err) { 223 | alert(err); 224 | throw err; 225 | } finally { 226 | this.panels.postMessage(this.view, 'enableUploadEMLScreen'); 227 | SetupTempFolder.removeTempFolder(); 228 | } 229 | } else if (isSelectAccount(message)) { 230 | this.lastState = {...this.defaultState}; 231 | const config = message as SelectAccount; 232 | this.account = new IMAP(config.account as ImapConfig); 233 | await this.account.init(); 234 | const htmlMainScreen = await mainScreen(this.lastState); 235 | await this.setHtml(htmlMainScreen); 236 | await joplin.settings.setValue(LAST_STATE, this.lastState); 237 | this.account.monitor(); 238 | } else if (isLogout(message)) { 239 | this.lastState = {...this.defaultState}; 240 | this.account.close(); 241 | this.account = null; 242 | const htmlLoginScreen = await loginScreen(); 243 | await this.setHtml(htmlLoginScreen); 244 | await joplin.settings.setValue(LAST_STATE, this.lastState); 245 | } else if (isHide(message)) { 246 | await this.closeOpenPanel(); 247 | } else if (isRefresh(message)) { 248 | try { 249 | await this.account.state(); 250 | 251 | // refresh mailboxes 252 | const mailBoxes = await this.account.getBoxesPath(); 253 | this.lastState['mailBoxes'] = mailBoxes; 254 | this.lastState['accountConfig'] = this.account.config; 255 | 256 | // refresh joplin notebooks 257 | const htmlMainScreen = await mainScreen(this.lastState); 258 | await this.setHtml(htmlMainScreen); 259 | await joplin.settings.setValue(LAST_STATE, this.lastState); 260 | } catch (err) { 261 | alert(err); 262 | throw err; 263 | } 264 | } 265 | } 266 | } 267 | -------------------------------------------------------------------------------- /src/ui/screens.ts: -------------------------------------------------------------------------------- 1 | import joplin from 'api'; 2 | import {State} from '../model/state.model'; 3 | import {ACCOUNTS} from '../constants'; 4 | import {JopinFolders} from '../model/joplinFolders.model'; 5 | 6 | export function loadingScreen() { 7 | return ` 8 |
9 |
10 |
11 |
12 |
13 |
14 | Loading... 15 |
16 |
17 |
18 |
19 |
20 |
21 | `; 22 | } 23 | 24 | export async function loginScreen() { 25 | const accounts = await joplin.settings.value(ACCOUNTS); 26 | const options: string[] = []; 27 | let htmlAccounts = ''; 28 | for (const key of Object.keys(accounts)) { 29 | const config = JSON.stringify( accounts[key]); 30 | const option = ``; 31 | options.push(option); 32 | } 33 | if (options.length) { 34 | htmlAccounts = ` 35 |
36 | Accounts 37 | 40 | 41 |
42 | 43 |
44 | `; 45 | } 46 | return ` 47 |
48 | 49 |
50 | 51 |
52 | 53 |
54 | 55 |
56 | 57 |

Login

58 | 59 |
60 | 61 |
62 | 63 | 64 |
65 | 66 |
67 | 68 | 69 |
70 | 71 |
72 | 73 |
74 | 75 |
76 | 77 |
78 | 79 |
80 | 81 |
82 | 83 |
84 | 85 |
86 |
87 | 88 |
89 | 90 |
91 | 92 | ${htmlAccounts} 93 | 94 |
95 | 96 |
97 | 98 |
99 |
100 |
101 |
102 |
103 | `; 104 | }; 105 | 106 | export function manualScreen() { 107 | return `
108 | 109 |
110 | 111 |
112 | 113 |
114 | 115 |
116 | 117 |

Login

118 | 119 |
120 | 121 |
122 | 123 | 124 |
125 | 126 |
127 | 128 | 129 |
130 | 131 |
132 | Server 133 | 135 |
136 | 137 |
138 | 139 |
140 | PORT 141 | 142 |
143 | 144 |
145 | 146 |
147 | 148 | 151 |
152 | 153 |
154 | 155 |
156 | 157 |
158 | 159 |
160 | 161 |
162 | 163 |
164 | 165 |
166 | 168 |
169 | 170 |
171 | 172 |
173 | 174 |
175 | 176 |
177 |
178 |
179 |
180 |
181 | `; 182 | } 183 | 184 | export async function mainScreen(lastState: State): Promise { 185 | const fromValue = lastState['from']; 186 | let readOnly = ''; 187 | let checked = ''; 188 | let disabledFolders = ''; 189 | let disabledMailBoxes = ''; 190 | let checkedTogle = ''; 191 | 192 | if (lastState['isEmailMonitor']) { 193 | readOnly = 'readOnly'; 194 | checked = 'checked'; 195 | } 196 | 197 | if (lastState['isMailBoxMonitor']) { 198 | disabledMailBoxes = 'disabled'; 199 | disabledFolders = 'disabled'; 200 | checkedTogle = 'checked'; 201 | } 202 | 203 | let joplinFolders: JopinFolders; 204 | const folders = []; 205 | let pageNum = 1; 206 | 207 | do { 208 | joplinFolders = await joplin.data.get(['folders'], {'page': pageNum++}); 209 | 210 | for (let i = 0; i < joplinFolders.items.length; i++) { 211 | const folder = joplinFolders.items[i]; 212 | let path = folder.title; 213 | let node = folder; 214 | const id = folder.id; 215 | 216 | // The parent folder path 217 | while (node.parent_id !== '') { 218 | node = await joplin.data.get(['folders', node.parent_id]); 219 | path = `${node.title}/${path}`; 220 | } 221 | folders.push({path: path, id: id}); 222 | } 223 | } while (joplinFolders.has_more); 224 | 225 | const options = []; 226 | 227 | folders.forEach((folder) => { 228 | const option = lastState['folderId'] === folder.id ? `` : ``; 229 | options.push(option); 230 | }); 231 | 232 | 233 | const mailBoxesOptions = []; 234 | lastState['mailBoxes'].forEach((element) => { 235 | const option = lastState['mailBox'] === element.path ? ``: ``; 236 | mailBoxesOptions.push(option); 237 | }); 238 | 239 | 240 | return ` 241 |
242 | 243 |
244 | 245 |
246 | 247 |
248 | 249 |
250 | 251 |

Main Screen

252 | 253 |
254 | 255 |
256 | From 257 | 259 | 260 |
261 |
262 |
263 | 265 | 266 |
267 |
268 |
269 | 270 |
271 | 272 |
273 |
274 | Mailbox 275 | 276 | 279 | 280 | 281 | 282 |
283 | 284 |
285 | Notebook 286 | 287 | 291 | 292 | 293 | 294 |
295 | 296 |
297 |
298 | 300 | 301 |
302 |
303 |
304 | 305 |
306 | 307 | 308 |
309 | 311 |
312 | 313 |
314 | 315 |
316 | 317 |
318 | 319 |
320 |
321 |
322 |
323 |
324 | `; 325 | } 326 | 327 | export async function uploadMessagesScreen() { 328 | let joplinFolders: JopinFolders; 329 | const folders = []; 330 | let pageNum = 1; 331 | 332 | do { 333 | joplinFolders = await joplin.data.get(['folders'], {'page': pageNum++}); 334 | 335 | for (let i = 0; i < joplinFolders.items.length; i++) { 336 | const folder = joplinFolders.items[i]; 337 | let path = folder.title; 338 | let node = folder; 339 | const id = folder.id; 340 | 341 | // The parent folder path 342 | while (node.parent_id !== '') { 343 | node = await joplin.data.get(['folders', node.parent_id]); 344 | path = `${node.title}/${path}`; 345 | } 346 | folders.push({path: path, id: id}); 347 | } 348 | } while (joplinFolders.has_more); 349 | 350 | const options = []; 351 | 352 | folders.forEach((folder) => { 353 | const option = ``; 354 | options.push(option); 355 | }); 356 | 357 | return ` 358 |
359 | 360 |
361 | 362 |
363 | 364 |
365 | 366 |
367 | 368 |

Upload .eml Files

369 | 370 |
371 | 372 |
373 | 374 |
375 | 376 |
377 | 378 |
379 | Notebook 380 | 381 | 385 | 386 |
387 | 388 |
389 | 390 |
391 | 392 |
393 | Export Type 394 | 399 |
400 | 401 | 402 |
403 | Attachments Style 404 | 408 |
409 | 410 | 411 |
412 | 413 | 416 |
417 | 418 |
419 | 420 | 421 | 422 |
423 | 424 |
425 | 426 |
427 | 429 |
430 | 431 |
432 | 433 |
434 | 435 |
436 | 437 |
438 |
439 |
440 |
441 |
442 | `; 443 | } 444 | -------------------------------------------------------------------------------- /src/ui/style/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | background: url('../img/icon.webp') no-repeat center center fixed; 3 | background-size: cover; 4 | } -------------------------------------------------------------------------------- /src/ui/style/tagify.css: -------------------------------------------------------------------------------- 1 | @charset "UTF-8";:root{--tagify-dd-color-primary:rgb(53,149,246);--tagify-dd-bg-color:white;--tagify-dd-item-pad:.3em .5em}.tagify{--tags-disabled-bg:#F1F1F1;--tags-border-color:#DDD;--tags-hover-border-color:#CCC;--tags-focus-border-color:#3595f6;--tag-border-radius:3px;--tag-bg:#E5E5E5;--tag-hover:#D3E2E2;--tag-text-color:black;--tag-text-color--edit:black;--tag-pad:0.3em 0.5em;--tag-inset-shadow-size:1.1em;--tag-invalid-color:#D39494;--tag-invalid-bg:rgba(211, 148, 148, 0.5);--tag-remove-bg:rgba(211, 148, 148, 0.3);--tag-remove-btn-color:black;--tag-remove-btn-bg:none;--tag-remove-btn-bg--hover:#c77777;--input-color:inherit;--tag--min-width:1ch;--tag--max-width:auto;--tag-hide-transition:0.3s;--placeholder-color:rgba(0, 0, 0, 0.4);--placeholder-color-focus:rgba(0, 0, 0, 0.25);--loader-size:.8em;--readonly-striped:1;display:inline-flex;align-items:flex-start;flex-wrap:wrap;border:1px solid var(--tags-border-color);padding:0;line-height:0;cursor:text;outline:0;position:relative;box-sizing:border-box;transition:.1s}@keyframes tags--bump{30%{transform:scale(1.2)}}@keyframes rotateLoader{to{transform:rotate(1turn)}}.tagify:hover:not(.tagify--focus):not(.tagify--invalid){--tags-border-color:var(--tags-hover-border-color)}.tagify[disabled]{background:var(--tags-disabled-bg);filter:saturate(0);opacity:.5;pointer-events:none}.tagify[disabled].tagify--select,.tagify[readonly].tagify--select{pointer-events:none}.tagify[disabled]:not(.tagify--mix):not(.tagify--select),.tagify[readonly]:not(.tagify--mix):not(.tagify--select){cursor:default}.tagify[disabled]:not(.tagify--mix):not(.tagify--select)>.tagify__input,.tagify[readonly]:not(.tagify--mix):not(.tagify--select)>.tagify__input{visibility:hidden;width:0;margin:5px 0}.tagify[disabled]:not(.tagify--mix):not(.tagify--select) .tagify__tag>div,.tagify[readonly]:not(.tagify--mix):not(.tagify--select) .tagify__tag>div{padding:var(--tag-pad)}.tagify[disabled]:not(.tagify--mix):not(.tagify--select) .tagify__tag>div::before,.tagify[readonly]:not(.tagify--mix):not(.tagify--select) .tagify__tag>div::before{animation:readonlyStyles 1s calc(-1s * (var(--readonly-striped) - 1)) paused}@keyframes readonlyStyles{0%{background:linear-gradient(45deg,var(--tag-bg) 25%,transparent 25%,transparent 50%,var(--tag-bg) 50%,var(--tag-bg) 75%,transparent 75%,transparent) 0/5px 5px;box-shadow:none;filter:brightness(.95)}}.tagify[disabled] .tagify__tag__removeBtn,.tagify[readonly] .tagify__tag__removeBtn{display:none}.tagify--loading .tagify__input>br:last-child{display:none}.tagify--loading .tagify__input::before{content:none}.tagify--loading .tagify__input::after{content:"";vertical-align:middle;opacity:1;width:.7em;height:.7em;width:var(--loader-size);height:var(--loader-size);min-width:0;border:3px solid;border-color:#eee #bbb #888 transparent;border-radius:50%;animation:rotateLoader .4s infinite linear;content:""!important;margin:-2px 0 -2px .5em}.tagify--loading .tagify__input:empty::after{margin-left:0}.tagify+input,.tagify+textarea{position:absolute!important;left:-9999em!important;transform:scale(0)!important}.tagify__tag{display:inline-flex;align-items:center;margin:5px 0 5px 5px;position:relative;z-index:1;outline:0;line-height:normal;cursor:default;transition:.13s ease-out}.tagify__tag>div{vertical-align:top;box-sizing:border-box;max-width:100%;padding:var(--tag-pad);color:var(--tag-text-color);line-height:inherit;border-radius:var(--tag-border-radius);white-space:nowrap;transition:.13s ease-out}.tagify__tag>div>*{white-space:pre-wrap;overflow:hidden;text-overflow:ellipsis;display:inline-block;vertical-align:top;min-width:var(--tag--min-width);max-width:var(--tag--max-width);transition:.8s ease,.1s color}.tagify__tag>div>[contenteditable]{outline:0;-webkit-user-select:text;user-select:text;cursor:text;margin:-2px;padding:2px;max-width:350px}.tagify__tag>div::before{content:"";position:absolute;border-radius:inherit;inset:var(--tag-bg-inset,0);z-index:-1;pointer-events:none;transition:120ms ease;animation:tags--bump .3s ease-out 1;box-shadow:0 0 0 var(--tag-inset-shadow-size) var(--tag-bg) inset}.tagify__tag:focus div::before,.tagify__tag:hover:not([readonly]) div::before{--tag-bg-inset:-2.5px;--tag-bg:var(--tag-hover)}.tagify__tag--loading{pointer-events:none}.tagify__tag--loading .tagify__tag__removeBtn{display:none}.tagify__tag--loading::after{--loader-size:.4em;content:"";vertical-align:middle;opacity:1;width:.7em;height:.7em;width:var(--loader-size);height:var(--loader-size);min-width:0;border:3px solid;border-color:#eee #bbb #888 transparent;border-radius:50%;animation:rotateLoader .4s infinite linear;margin:0 .5em 0 -.1em}.tagify__tag--flash div::before{animation:none}.tagify__tag--hide{width:0!important;padding-left:0;padding-right:0;margin-left:0;margin-right:0;opacity:0;transform:scale(0);transition:var(--tag-hide-transition);pointer-events:none}.tagify__tag--hide>div>*{white-space:nowrap}.tagify__tag.tagify--noAnim>div::before{animation:none}.tagify__tag.tagify--notAllowed:not(.tagify__tag--editable) div>span{opacity:.5}.tagify__tag.tagify--notAllowed:not(.tagify__tag--editable) div::before{--tag-bg:var(--tag-invalid-bg);transition:.2s}.tagify__tag[readonly] .tagify__tag__removeBtn{display:none}.tagify__tag[readonly]>div::before{animation:readonlyStyles 1s calc(-1s * (var(--readonly-striped) - 1)) paused}@keyframes readonlyStyles{0%{background:linear-gradient(45deg,var(--tag-bg) 25%,transparent 25%,transparent 50%,var(--tag-bg) 50%,var(--tag-bg) 75%,transparent 75%,transparent) 0/5px 5px;box-shadow:none;filter:brightness(.95)}}.tagify__tag--editable>div{color:var(--tag-text-color--edit)}.tagify__tag--editable>div::before{box-shadow:0 0 0 2px var(--tag-hover) inset!important}.tagify__tag--editable>.tagify__tag__removeBtn{pointer-events:none}.tagify__tag--editable>.tagify__tag__removeBtn::after{opacity:0;transform:translateX(100%) translateX(5px)}.tagify__tag--editable.tagify--invalid>div::before{box-shadow:0 0 0 2px var(--tag-invalid-color) inset!important}.tagify__tag__removeBtn{order:5;display:inline-flex;align-items:center;justify-content:center;border-radius:50px;cursor:pointer;font:14px/1 Arial;background:var(--tag-remove-btn-bg);color:var(--tag-remove-btn-color);width:14px;height:14px;margin-right:4.6666666667px;margin-left:auto;overflow:hidden;transition:.2s ease-out}.tagify__tag__removeBtn::after{content:"×";transition:.3s,color 0s}.tagify__tag__removeBtn:hover{color:#fff;background:var(--tag-remove-btn-bg--hover)}.tagify__tag__removeBtn:hover+div>span{opacity:.5}.tagify__tag__removeBtn:hover+div::before{box-shadow:0 0 0 var(--tag-inset-shadow-size) var(--tag-remove-bg,rgba(211,148,148,.3)) inset!important;transition:box-shadow .2s}.tagify:not(.tagify--mix) .tagify__input br{display:none}.tagify:not(.tagify--mix) .tagify__input *{display:inline;white-space:nowrap}.tagify__input{flex-grow:1;display:inline-block;min-width:110px;margin:5px;padding:var(--tag-pad);line-height:normal;position:relative;white-space:pre-wrap;color:var(--input-color);box-sizing:inherit}.tagify__input:empty::before{position:static}.tagify__input:focus{outline:0}.tagify__input:focus::before{transition:.2s ease-out;opacity:0;transform:translatex(6px)}@supports (-ms-ime-align:auto){.tagify__input:focus::before{display:none}}.tagify__input:focus:empty::before{transition:.2s ease-out;opacity:1;transform:none;color:rgba(0,0,0,.25);color:var(--placeholder-color-focus)}@-moz-document url-prefix(){.tagify__input:focus:empty::after{display:none}}.tagify__input::before{content:attr(data-placeholder);height:1em;line-height:1em;margin:auto 0;z-index:1;color:var(--placeholder-color);white-space:nowrap;pointer-events:none;opacity:0;position:absolute}.tagify__input::after{content:attr(data-suggest);display:inline-block;vertical-align:middle;position:absolute;min-width:calc(100% - 1.5em);text-overflow:ellipsis;overflow:hidden;white-space:pre;color:var(--tag-text-color);opacity:.3;pointer-events:none;max-width:100px}.tagify__input .tagify__tag{margin:0 1px}.tagify--mix{display:block}.tagify--mix .tagify__input{padding:5px;margin:0;width:100%;height:100%;line-height:1.5;display:block}.tagify--mix .tagify__input::before{height:auto;display:none;line-height:inherit}.tagify--mix .tagify__input::after{content:none}.tagify--select::after{content:">";opacity:.5;position:absolute;top:50%;right:0;bottom:0;font:16px monospace;line-height:8px;height:8px;pointer-events:none;transform:translate(-150%,-50%) scaleX(1.2) rotate(90deg);transition:.2s ease-in-out}.tagify--select[aria-expanded=true]::after{transform:translate(-150%,-50%) rotate(270deg) scaleY(1.2)}.tagify--select .tagify__tag{position:absolute;top:0;right:1.8em;bottom:0}.tagify--select .tagify__tag div{display:none}.tagify--select .tagify__input{width:100%}.tagify--empty .tagify__input::before{transition:.2s ease-out;opacity:1;transform:none;display:inline-block;width:auto}.tagify--mix .tagify--empty .tagify__input::before{display:inline-block}.tagify--focus{--tags-border-color:var(--tags-focus-border-color);transition:0s}.tagify--invalid{--tags-border-color:#D39494}.tagify__dropdown{position:absolute;z-index:9999;transform:translateY(1px);overflow:hidden}.tagify__dropdown[placement=top]{margin-top:0;transform:translateY(-100%)}.tagify__dropdown[placement=top] .tagify__dropdown__wrapper{border-top-width:1.1px;border-bottom-width:0}.tagify__dropdown[position=text]{box-shadow:0 0 0 3px rgba(var(--tagify-dd-color-primary),.1);font-size:.9em}.tagify__dropdown[position=text] .tagify__dropdown__wrapper{border-width:1px}.tagify__dropdown__wrapper{max-height:300px;overflow:auto;overflow-x:hidden;background:var(--tagify-dd-bg-color);border:1px solid;border-color:var(--tagify-dd-color-primary);border-bottom-width:1.5px;border-top-width:0;box-shadow:0 2px 4px -2px rgba(0,0,0,.2);transition:.25s cubic-bezier(0,1,.5,1)}.tagify__dropdown__header:empty{display:none}.tagify__dropdown__footer{display:inline-block;margin-top:.5em;padding:var(--tagify-dd-item-pad);font-size:.7em;font-style:italic;opacity:.5}.tagify__dropdown__footer:empty{display:none}.tagify__dropdown--initial .tagify__dropdown__wrapper{max-height:20px;transform:translateY(-1em)}.tagify__dropdown--initial[placement=top] .tagify__dropdown__wrapper{transform:translateY(2em)}.tagify__dropdown__item{box-sizing:border-box;padding:var(--tagify-dd-item-pad);margin:1px;cursor:pointer;border-radius:2px;position:relative;outline:0;max-height:60px;max-width:100%}.tagify__dropdown__item--active{background:var(--tagify-dd-color-primary);color:#fff}.tagify__dropdown__item:active{filter:brightness(105%)}.tagify__dropdown__item--hidden{padding-top:0;padding-bottom:0;margin:0 1px;pointer-events:none;overflow:hidden;max-height:0;transition:var(--tagify-dd-item--hidden-duration,.3s)!important}.tagify__dropdown__item--hidden>*{transform:translateY(-100%);opacity:0;transition:inherit} -------------------------------------------------------------------------------- /src/ui/webview.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-unused-vars */ 2 | 3 | // When clicking on the 'login' button. 4 | function login() { 5 | const email = document.getElementById('email').value; 6 | const password = document.getElementById('password').value; 7 | 8 | disabledLoginScreen(true); 9 | 10 | webviewApi.postMessage({ 11 | login: true, 12 | email: email, 13 | password: password, 14 | }); 15 | } 16 | 17 | // When clicking on the 'Manually connect to IMAP' button. 18 | function manualConnectionScreen() { 19 | webviewApi.postMessage({ 20 | manualConnectionScreen: true, 21 | }); 22 | } 23 | 24 | // When clicking on the 'close' button. 25 | function hide() { 26 | webviewApi.postMessage({ 27 | hide: true, 28 | }); 29 | } 30 | 31 | // When clicking on the 'login screen' button. 32 | function loginScreen() { 33 | webviewApi.postMessage({ 34 | loginScreen: true, 35 | }); 36 | } 37 | 38 | // When clicking on the 'login' button on the manual screen. 39 | function loginManually() { 40 | const email = document.getElementById('email').value; 41 | const password = document.getElementById('password').value; 42 | const server = document.getElementById('server').value.trim(); 43 | const port = document.getElementById('port').value; 44 | const sslTls = document.getElementById('ssl_tls').checked; 45 | 46 | disabledManualLoginScreen(true); 47 | 48 | webviewApi.postMessage({ 49 | loginManually: true, 50 | user: email, 51 | password: password, 52 | host: server, 53 | port: port, 54 | tls: sslTls, 55 | }); 56 | } 57 | 58 | function toggle() { 59 | const from = document.getElementById('from').value; 60 | const readOnly = document.getElementById('from').readOnly; 61 | 62 | if (from.trim() === '' && !readOnly) { 63 | alert('Enter an email'); 64 | document.getElementById('toggle-from').checked = false; 65 | return; 66 | } 67 | 68 | // It sends an email and then closes input. 69 | if (!readOnly) { 70 | webviewApi.postMessage({ 71 | state: 'close', 72 | from: from, 73 | }); 74 | document.getElementById('from').readOnly = !readOnly; 75 | } else { 76 | webviewApi.postMessage({ 77 | state: 'open', 78 | }); 79 | document.getElementById('from').readOnly = !readOnly; 80 | } 81 | } 82 | 83 | function uploadMessagesScreen() { 84 | webviewApi.postMessage({ 85 | uploadMessagesScreen: true, 86 | }); 87 | } 88 | 89 | function createTag() { 90 | const tagElement = document.getElementById('tags'); 91 | if (tagElement) { 92 | return; 93 | } 94 | 95 | const divTag = document.getElementById('div-tag'); 96 | 97 | const tag = document.createElement('input'); 98 | tag.classList.add('form-control'); 99 | tag.placeholder = 'Add a Tag...'; 100 | tag.id = 'tags'; 101 | 102 | divTag.appendChild(tag); 103 | new Tagify(tag); 104 | } 105 | 106 | async function readFile(file) { 107 | return new Promise((resolve, reject)=>{ 108 | const reader = new FileReader(); 109 | reader.readAsText(file); 110 | 111 | reader.onload = ()=>{ 112 | resolve(reader.result); 113 | }; 114 | 115 | reader.onerror = (err)=>{ 116 | reject(err); 117 | }; 118 | }); 119 | } 120 | 121 | async function uploadEMLfiles() { 122 | const files = document.getElementById('formFileMultiple').files; 123 | const fileListLength = files.length; 124 | const folderId = document.getElementById('notebook').value; 125 | const tags = document.getElementById('tags'); 126 | const includeAttachments = document.getElementById('include_attachments').checked; 127 | const exportType = document.getElementById('export_type').value; 128 | const attachmentsStyle = document.getElementById('attachments_style').value; 129 | 130 | disabledUploadEMLScreen(true); 131 | 132 | if (fileListLength === 0) { 133 | alert('Please upload .eml file(s)'); 134 | disabledUploadEMLScreen(false); 135 | return; 136 | } else if (!tags) { 137 | /* If tags input is not created, that means the user has not selected a notebook yet. */ 138 | alert('Please Choose a NoteBook'); 139 | disabledUploadEMLScreen(false); 140 | return; 141 | } 142 | 143 | // convert an array of type string to an actual array. 144 | const tagsList = tags.value !== ''? JSON.parse(tags.value).map((e)=>e.value.toLowerCase()): []; 145 | const emlFiles = []; 146 | 147 | // for each eml file. 148 | for (let i = 0; i < fileListLength; i++) { 149 | const emlFile = await readFile(files[i]); 150 | emlFiles.push(emlFile); 151 | } 152 | 153 | webviewApi.postMessage({ 154 | emlFiles: emlFiles, 155 | folderId: folderId, 156 | tags: tagsList, 157 | exportType: exportType, 158 | includeAttachments: includeAttachments, 159 | attachmentsStyle: attachmentsStyle, 160 | }); 161 | } 162 | 163 | function logout() { 164 | webviewApi.postMessage({ 165 | logout: true, 166 | }); 167 | } 168 | 169 | function selectedAccount() { 170 | const accountsInput = document.getElementById('accounts'); 171 | const account = accountsInput.value; 172 | const config = JSON.parse(account); 173 | 174 | disabledManualLoginScreen(true); 175 | 176 | webviewApi.postMessage({ 177 | loginManually: true, 178 | user: config.user, 179 | password: config.password, 180 | host: config.host, 181 | port: config.port, 182 | tls: config.tls, 183 | }); 184 | } 185 | 186 | function toggleBox() { 187 | const mailbox = document.getElementById('mailbox').value; 188 | const readOnly = document.getElementById('mailbox').disabled; 189 | const folderId = document.getElementById('notebook').value; 190 | 191 | if (folderId === '') { 192 | /* If tags input is not created, that means the user has not selected a notebook yet. */ 193 | alert('Please Choose a NoteBook'); 194 | document.getElementById('toggle-box').checked = false; 195 | return; 196 | } 197 | // It sends an email and then closes input. 198 | if (!readOnly) { 199 | document.getElementById('mailbox').disabled = !readOnly; 200 | document.getElementById('notebook').disabled = !readOnly; 201 | 202 | webviewApi.postMessage({ 203 | monitorMailBox: true, 204 | mailbox: mailbox, 205 | folderId: folderId, 206 | }); 207 | } else { 208 | document.getElementById('mailbox').disabled = !readOnly; 209 | document.getElementById('notebook').disabled = !readOnly; 210 | 211 | webviewApi.postMessage({ 212 | monitorMailBox: false, 213 | }); 214 | } 215 | } 216 | 217 | function disabledLoginScreen(flag) { 218 | const emailInput = document.getElementById('email'); 219 | const passwordInput = document.getElementById('password'); 220 | const loginBtn = document.getElementById('login_btn'); 221 | if (flag === false) { 222 | emailInput.readOnly = passwordInput.readOnly = loginBtn.disabled = false; 223 | loginBtn.innerHTML = 'Login'; 224 | } else { 225 | loginBtn.disabled = emailInput.readOnly = passwordInput.readOnly = true; 226 | const spinner = ` Loading...`; 227 | loginBtn.innerHTML = spinner; 228 | } 229 | } 230 | 231 | function disabledManualLoginScreen(flag) { 232 | const emailInput = document.getElementById('email'); 233 | const passwordInput = document.getElementById('password'); 234 | const serverInput = document.getElementById('server'); 235 | const portInput = document.getElementById('port'); 236 | const sslTlsInput = document.getElementById('ssl_tls'); 237 | const loginBtn = document.getElementById('login_btn'); 238 | const selectedAccountBtn = document.getElementById('selectedAccount'); 239 | 240 | if (flag === false) { 241 | if (selectedAccountBtn) { 242 | selectedAccountBtn.disabled = false; 243 | selectedAccountBtn.innerHTML = 'Login'; 244 | } else { 245 | emailInput.readOnly = passwordInput.readOnly = serverInput.readOnly = portInput.readOnly = sslTlsInput.disabled = loginBtn.disabled = false; 246 | loginBtn.innerHTML = 'Login'; 247 | } 248 | } else { 249 | if (selectedAccountBtn) { 250 | selectedAccountBtn.disabled = true; 251 | const spinner = ` Loading...`; 252 | selectedAccountBtn.innerHTML = spinner; 253 | } else { 254 | emailInput.readOnly = passwordInput.readOnly = serverInput.readOnly = portInput.readOnly = sslTlsInput.disabled = loginBtn.disabled = true; 255 | const spinner = ` Loading...`; 256 | loginBtn.innerHTML = spinner; 257 | } 258 | } 259 | } 260 | 261 | function disabledUploadEMLScreen(flag) { 262 | const filesInput = document.getElementById('formFileMultiple'); 263 | const folderInput = document.getElementById('notebook'); 264 | const tagsDiv = document.getElementById('div-tag'); 265 | const includeAttachmentsInput = document.getElementById('include_attachments'); 266 | const exportTypeInput = document.getElementById('export_type'); 267 | const attachmentsStyleInput = document.getElementById('attachments_style'); 268 | const loginBtn = document.getElementById('convert_btn'); 269 | 270 | if (flag === false) { 271 | filesInput.disabled = folderInput.disabled = includeAttachmentsInput.disabled = exportTypeInput.disabled = attachmentsStyleInput.disabled = loginBtn.disabled = false; 272 | tagsDiv.style.pointerEvents = 'auto'; 273 | loginBtn.innerHTML = 'Convert'; 274 | } else { 275 | filesInput.disabled = folderInput.disabled = includeAttachmentsInput.disabled = exportTypeInput.disabled = attachmentsStyleInput.disabled = true; 276 | tagsDiv.style.pointerEvents = 'none'; 277 | const spinner = ` Loading...`; 278 | loginBtn.disabled = true; 279 | loginBtn.innerHTML = spinner; 280 | } 281 | } 282 | 283 | webviewApi.onMessage(({message})=>{ 284 | if (message === 'enableLoginScreen') { 285 | disabledLoginScreen(false); 286 | } else if (message === 'enableManualLoginScreen') { 287 | disabledManualLoginScreen(false); 288 | } else if (message === 'enableUploadEMLScreen') { 289 | disabledUploadEMLScreen(false); 290 | } else if (message === 'monitoringError') { 291 | webviewApi.postMessage({ 292 | state: 'open', 293 | }); 294 | webviewApi.postMessage({ 295 | monitorMailBox: false, 296 | }); 297 | } 298 | }); 299 | 300 | function addBlockquote() { 301 | document.getElementById('quote').innerText = 'Make sure the email provider allows login using the original password; otherwise, use the app password.'; 302 | } 303 | 304 | function refresh() { 305 | webviewApi.postMessage({ 306 | refresh: false, 307 | }); 308 | } 309 | -------------------------------------------------------------------------------- /src/utils/stringOps.ts: -------------------------------------------------------------------------------- 1 | class StringOps { 2 | // To check whether the string line is RTL language or not. 3 | static isRTL(s: string): boolean { 4 | const rtlChars = '\u0591-\u07FF\u200F\u202B\u202E\uFB1D-\uFDFD\uFE70-\uFEFC'; 5 | const rtlDirCheck = new RegExp('^[^'+rtlChars+']*?['+rtlChars+']'); 6 | return rtlDirCheck.test(s); 7 | }; 8 | 9 | static wrapDir(str: string): string { 10 | return '\u202B' + str + '\u202C'; 11 | }; 12 | 13 | static escapeHTML(str: string): string { 14 | return str.replace(/&/g, '&') 15 | .replace(//g, ' >') 17 | .replace(/"/g, '"') 18 | .replace(/'/g, '''); 19 | }; 20 | 21 | // To remove irregular whitespace. 22 | // [Invisible Unicode characters](https://invisible-characters.com/#:~:text=Invisible%20Unicode%20characters%3F,%2B2800%20BRAILLE%20PATTERN%20BLANK). 23 | static removeIrregularSpaces(s: string): string { 24 | return s.replace(/\u0009/g, ' ') 25 | .replace(/\u0020/g, ' ') 26 | .replace(/\u00A0/g, ' ') 27 | .replace(/\u00AD/g, ' ') 28 | .replace(/\u034F/g, ' ') 29 | .replace(/\u061C/g, ' ') 30 | .replace(/\u115F/g, ' ') 31 | .replace(/\u1160/g, ' ') 32 | .replace(/\u17B4/g, ' ') 33 | .replace(/\u17B5/g, ' ') 34 | .replace(/\u180E/g, ' ') 35 | .replace(/\u2000/g, ' ') 36 | .replace(/\u2001/g, ' ') 37 | .replace(/\u2002/g, ' ') 38 | .replace(/\u2003/g, ' ') 39 | .replace(/\u2004/g, ' ') 40 | .replace(/\u2005/g, ' ') 41 | .replace(/\u2006/g, ' ') 42 | .replace(/\u2007/g, ' ') 43 | .replace(/\u2008/g, ' ') 44 | .replace(/\u2009/g, ' ') 45 | .replace(/\u200A/g, ' ') 46 | .replace(/\u200B/g, ' ') 47 | .replace(/\u200C/g, ' ') 48 | .replace(/\u200D/g, ' ') 49 | .replace(/\u200E/g, ' ') 50 | .replace(/\u200F/g, ' ') 51 | .replace(/\u202F/g, ' ') 52 | .replace(/\u205F/g, ' ') 53 | .replace(/\u2060/g, ' ') 54 | .replace(/\u2061/g, ' ') 55 | .replace(/\u2062/g, ' ') 56 | .replace(/\u2063/g, ' ') 57 | .replace(/\u2064/g, ' ') 58 | .replace(/\u206A/g, ' ') 59 | .replace(/\u206B/g, ' ') 60 | .replace(/\u206C/g, ' ') 61 | .replace(/\u206D/g, ' ') 62 | .replace(/\u206E/g, ' ') 63 | .replace(/\u206F/g, ' ') 64 | .replace(/\u3000/g, ' ') 65 | .replace(/\u2800/g, ' ') 66 | .replace(/\u3164/g, ' ') 67 | .replace(/\uFEFF/g, ' ') 68 | .replace(/\uFFA0/g, ' ') 69 | .replace(/\u1D159/g, ' ') 70 | .replace(/\u1D173/g, ' ') 71 | .replace(/\u1D174/g, ' ') 72 | .replace(/\u1D175/g, ' ') 73 | .replace(/\u1D176/g, ' ') 74 | .replace(/\u1D177/g, ' ') 75 | .replace(/\u1D177/g, ' ') 76 | .replace(/\u1D179/g, ' ') 77 | .replace(/\u1D17/g, ' '); 78 | }; 79 | } 80 | 81 | export default StringOps; 82 | -------------------------------------------------------------------------------- /test/emailConfigure.test.ts: -------------------------------------------------------------------------------- 1 | import {emailConfigure} from '../src/core/emailConfigure'; 2 | import {Login} from '../src/model/message.model'; 3 | import {ImapConfig} from '../src/model/imapConfig.model'; 4 | 5 | 6 | describe('Testing various types of writing the email', () => { 7 | it('Uppercase email', () => { 8 | const login: Login = { 9 | login: true, 10 | email: 'TEST@GMAIL.COM', 11 | password: '12345', 12 | }; 13 | 14 | const config = emailConfigure(login); 15 | 16 | const answer: ImapConfig = { 17 | user: 'test@gmail.com', 18 | password: '12345', 19 | type: 'gmail', 20 | host: 'imap.gmail.com', 21 | port: 993, 22 | tls: true, 23 | }; 24 | 25 | expect(config).toStrictEqual(answer); 26 | }); 27 | 28 | it('Email that starts with a space', () => { 29 | const login: Login = { 30 | login: true, 31 | email: ' test@gmail.com', 32 | password: '12345', 33 | }; 34 | 35 | const config = emailConfigure(login); 36 | 37 | const answer: ImapConfig = { 38 | user: 'test@gmail.com', 39 | password: '12345', 40 | type: 'gmail', 41 | host: 'imap.gmail.com', 42 | port: 993, 43 | tls: true, 44 | }; 45 | 46 | expect(config).toStrictEqual(answer); 47 | }); 48 | 49 | it('Email that ends with a space', () => { 50 | const login: Login = { 51 | login: true, 52 | email: 'test@outlook.com ', 53 | password: '12345', 54 | }; 55 | 56 | const config = emailConfigure(login); 57 | 58 | const answer: ImapConfig = { 59 | user: 'test@outlook.com', 60 | password: '12345', 61 | type: 'outlook', 62 | host: 'outlook.office365.com', 63 | port: 993, 64 | tls: true, 65 | }; 66 | 67 | expect(config).toStrictEqual(answer); 68 | }); 69 | 70 | it(`Presencing of a provider name from the provider's list within the username`, () => { 71 | const login: Login = { 72 | login: true, 73 | email: 'gmail@aol.com', 74 | password: '12345', 75 | }; 76 | 77 | const config = emailConfigure(login); 78 | 79 | const answer: ImapConfig = { 80 | user: 'gmail@aol.com', 81 | password: '12345', 82 | type: 'aol', 83 | host: 'imap.aol.com', 84 | port: 993, 85 | tls: true, 86 | }; 87 | 88 | expect(config).toStrictEqual(answer); 89 | }); 90 | 91 | it('If a provider is not on the email provider list, it will throw an error.', () => { 92 | const login: Login = { 93 | login: true, 94 | email: 'test@company.com', 95 | password: '12345', 96 | }; 97 | 98 | expect(()=>emailConfigure(login)).toThrow(Error(`Sorry, an email provider couldn't be found, Please use the manual connection.`)); 99 | }); 100 | }); 101 | -------------------------------------------------------------------------------- /test/emailSubjectParser.test.ts: -------------------------------------------------------------------------------- 1 | import EmailSubjectParser from '../src/core/emailSubjectParser'; 2 | import SubjectMetadata from '../src/model/subjectMetadata.model'; 3 | 4 | describe('Naive Case.', ()=>{ 5 | it(`Extract 'joplin' as a note and 'note' as a tag.`, ()=>{ 6 | const subject = 's @joplin #note'; 7 | const parser = new EmailSubjectParser(subject); 8 | const subjectMetadata = parser.parse(); 9 | 10 | const expectedSubjectMetadata: SubjectMetadata = { 11 | folders: ['joplin'], 12 | tags: ['note'], 13 | isTodo: 0, 14 | }; 15 | 16 | expect(subjectMetadata).toEqual(expectedSubjectMetadata); 17 | }); 18 | 19 | it('lowercase', ()=>{ 20 | const subject = '@joplin #joplin'; 21 | const parser = new EmailSubjectParser(subject); 22 | const subjectMetadata = parser.parse(); 23 | 24 | const expectedSubjectMetadata: SubjectMetadata = { 25 | folders: ['joplin'], 26 | tags: ['joplin'], 27 | isTodo: 0, 28 | }; 29 | 30 | expect(subjectMetadata).toEqual(expectedSubjectMetadata); 31 | }); 32 | 33 | it('uppercase', ()=>{ 34 | const subject = '@JOPLIN #JOPLIN'; 35 | const parser = new EmailSubjectParser(subject); 36 | const subjectMetadata = parser.parse(); 37 | 38 | const expectedSubjectMetadata: SubjectMetadata = { 39 | folders: ['JOPLIN'], 40 | tags: ['joplin'], 41 | isTodo: 0, 42 | }; 43 | 44 | expect(subjectMetadata).toEqual(expectedSubjectMetadata); 45 | }); 46 | }); 47 | 48 | describe('The subject without folders or tags.', ()=>{ 49 | it(`It will return two empty arrays of subjects and tags in the subject that don't contain mentions and tags.`, ()=>{ 50 | const subject = 'subject test'; 51 | const parser = new EmailSubjectParser(subject); 52 | const subjectMetadata = parser.parse(); 53 | 54 | const expectedSubjectMetadata: SubjectMetadata = { 55 | folders: ['email messages'], 56 | tags: [], 57 | isTodo: 0, 58 | }; 59 | 60 | expect(subjectMetadata).toEqual(expectedSubjectMetadata); 61 | }); 62 | 63 | it(`Empty subject.`, ()=>{ 64 | const subject = ''; 65 | const parser = new EmailSubjectParser(subject); 66 | const subjectMetadata = parser.parse(); 67 | 68 | const expectedSubjectMetadata: SubjectMetadata = { 69 | folders: ['email messages'], 70 | tags: [], 71 | isTodo: 0, 72 | }; 73 | 74 | expect(subjectMetadata).toEqual(expectedSubjectMetadata); 75 | }); 76 | 77 | it('Should ignore the empty mention or empty tag.', ()=>{ 78 | const subject = 'subject @ @ joplin @ @ @ @ @ # # # # # joplin # # joplin'; 79 | const parser = new EmailSubjectParser(subject); 80 | const subjectMetadata = parser.parse(); 81 | 82 | const expectedSubjectMetadata: SubjectMetadata = { 83 | folders: ['email messages'], 84 | tags: [], 85 | isTodo: 0, 86 | }; 87 | 88 | expect(subjectMetadata).toEqual(expectedSubjectMetadata); 89 | }); 90 | }); 91 | 92 | describe('@ symbol between text.', ()=>{ 93 | it('Should ignore the @ symbol between text.', ()=>{ 94 | const subject = 'subject email@gmail.com test@test @joplin @email_plugin #joplin'; 95 | const parser = new EmailSubjectParser(subject); 96 | const subjectMetadata = parser.parse(); 97 | 98 | const expectedSubjectMetadata: SubjectMetadata = { 99 | folders: ['joplin', 'email_plugin'], 100 | tags: ['joplin'], 101 | isTodo: 0, 102 | }; 103 | 104 | expect(subjectMetadata).toEqual(expectedSubjectMetadata); 105 | }); 106 | 107 | it('Should ignore the @ symbol between text.', ()=>{ 108 | const subject = 'subject email@gmail.com test@test@joplin@email_plugin #joplin'; 109 | const parser = new EmailSubjectParser(subject); 110 | const subjectMetadata = parser.parse(); 111 | 112 | const expectedSubjectMetadata: SubjectMetadata = { 113 | folders: ['email messages'], 114 | tags: ['joplin'], 115 | isTodo: 0, 116 | }; 117 | 118 | expect(subjectMetadata).toEqual(expectedSubjectMetadata); 119 | }); 120 | 121 | 122 | it('Should ignore the @ symbol inside an email.', ()=>{ 123 | const subject = 'subject email@gmail.com @joplin #joplin email2@gmail.com'; 124 | const parser = new EmailSubjectParser(subject); 125 | const subjectMetadata = parser.parse(); 126 | 127 | const expectedSubjectMetadata: SubjectMetadata = { 128 | folders: ['joplin'], 129 | tags: ['joplin'], 130 | isTodo: 0, 131 | }; 132 | 133 | expect(subjectMetadata).toEqual(expectedSubjectMetadata); 134 | }); 135 | }); 136 | 137 | 138 | describe('Special character.', ()=>{ 139 | it('Dealing with underscores within folders or emojis within tags', ()=>{ 140 | const subject = 'subject email@gmail.com test@test @joplin @email_plugin #joplin💖'; 141 | const parser = new EmailSubjectParser(subject); 142 | const subjectMetadata = parser.parse(); 143 | 144 | const expectedSubjectMetadata: SubjectMetadata = { 145 | folders: ['joplin', 'email_plugin'], 146 | tags: ['joplin💖'], 147 | isTodo: 0, 148 | }; 149 | 150 | expect(subjectMetadata).toEqual(expectedSubjectMetadata); 151 | }); 152 | 153 | 154 | it('Dealing with underscores within folders.', ()=>{ 155 | const subject = 'subject @50 @google.com @_gmail_proton*outlook'; 156 | const parser = new EmailSubjectParser(subject); 157 | const subjectMetadata = parser.parse(); 158 | 159 | const expectedSubjectMetadata: SubjectMetadata = { 160 | folders: ['50', 'google.com', '_gmail_proton*outlook'], 161 | tags: [], 162 | isTodo: 0, 163 | }; 164 | 165 | expect(subjectMetadata).toEqual(expectedSubjectMetadata); 166 | }); 167 | }); 168 | 169 | describe('Mention boundary.', ()=>{ 170 | it('Subject starts with mentioning a folder and ends with a tag.', ()=>{ 171 | const subject = '@joplin subject #tag'; 172 | const parser = new EmailSubjectParser(subject); 173 | const subjectMetadata = parser.parse(); 174 | 175 | const expectedSubjectMetadata: SubjectMetadata = { 176 | folders: ['joplin'], 177 | tags: ['tag'], 178 | isTodo: 0, 179 | }; 180 | 181 | expect(subjectMetadata).toEqual(expectedSubjectMetadata); 182 | }); 183 | 184 | it('Subject starts with mentioning a tag and ends with a folder.', ()=>{ 185 | const subject = 'subect# #tag @subject@ @joplin # # @go ﹫go'; 186 | const parser = new EmailSubjectParser(subject); 187 | const subjectMetadata = parser.parse(); 188 | 189 | const expectedSubjectMetadata: SubjectMetadata = { 190 | folders: ['joplin', 'go', 'go'], 191 | tags: ['tag'], 192 | isTodo: 0, 193 | }; 194 | 195 | expect(subjectMetadata).toEqual(expectedSubjectMetadata); 196 | }); 197 | }); 198 | 199 | describe('Irregular spaces.', ()=>{ 200 | it('should ignore irregular spaces between folders and tags.', ()=>{ 201 | const subject = 'why and but @note #note @good #tag  '; 202 | const parser = new EmailSubjectParser(subject); 203 | const subjectMetadata = parser.parse(); 204 | 205 | const expectedSubjectMetadata: SubjectMetadata = { 206 | folders: ['note', 'good'], 207 | tags: ['note', 'tag'], 208 | isTodo: 0, 209 | }; 210 | 211 | expect(subjectMetadata).toEqual(expectedSubjectMetadata); 212 | }); 213 | 214 | it('should ignore irregular spaces between folders and tags.', ()=>{ 215 | const subject = '     @note #note @good #tag  '; 216 | const parser = new EmailSubjectParser(subject); 217 | const subjectMetadata = parser.parse(); 218 | 219 | const expectedSubjectMetadata: SubjectMetadata = { 220 | folders: ['note', 'good'], 221 | tags: ['note', 'tag'], 222 | isTodo: 0, 223 | }; 224 | 225 | expect(subjectMetadata).toEqual(expectedSubjectMetadata); 226 | }); 227 | }); 228 | 229 | describe('Subject with duplicate tags.', ()=>{ 230 | it('should ignore duplicates tags.', ()=>{ 231 | const subject = 'email subject @joplin #joplin #gmail #joplin #tag #TAG'; 232 | const parser = new EmailSubjectParser(subject); 233 | const subjectMetadata = parser.parse(); 234 | 235 | const expectedSubjectMetadata: SubjectMetadata = { 236 | folders: ['joplin'], 237 | tags: ['joplin', 'gmail', 'tag'], 238 | isTodo: 0, 239 | }; 240 | 241 | expect(subjectMetadata).toEqual(expectedSubjectMetadata); 242 | }); 243 | }); 244 | 245 | 246 | describe('Subject starts with an exclamation mark (note marked as todo)', ()=>{ 247 | it('note marked as todo.', ()=>{ 248 | const subject = '! email subject @joplin #joplin #gmail #joplin #tag #TAG'; 249 | const parser = new EmailSubjectParser(subject); 250 | const subjectMetadata = parser.parse(); 251 | 252 | const expectedSubjectMetadata: SubjectMetadata = { 253 | folders: ['joplin'], 254 | tags: ['joplin', 'gmail', 'tag'], 255 | isTodo: 1, 256 | }; 257 | 258 | expect(subjectMetadata).toEqual(expectedSubjectMetadata); 259 | }); 260 | 261 | it('note marked as todo', ()=>{ 262 | const subject = '!'; 263 | const parser = new EmailSubjectParser(subject); 264 | const subjectMetadata = parser.parse(); 265 | 266 | const expectedSubjectMetadata: SubjectMetadata = { 267 | folders: ['email messages'], 268 | tags: [], 269 | isTodo: 1, 270 | }; 271 | 272 | expect(subjectMetadata).toEqual(expectedSubjectMetadata); 273 | }); 274 | }); 275 | -------------------------------------------------------------------------------- /test/emailparser.test.ts: -------------------------------------------------------------------------------- 1 | globalThis.Blob = require('cross-blob'); 2 | import {Email} from 'postal-mime'; 3 | import EmailParser from '../src/core/emailParser'; 4 | 5 | it(`throw an error if the EML file is empty.`, async ()=>{ 6 | const emailParser = new EmailParser(); 7 | expect( async ()=> await emailParser.parse(emptyEML)).rejects.toThrow(); 8 | }); 9 | 10 | 11 | it(`The EML file starts with blank lines.`, async ()=>{ 12 | const emailParser = new EmailParser(); 13 | const emailContent: Email = await emailParser.parse(EMLStartsWithBlankLines); 14 | 15 | const subject = emailContent.subject; 16 | const HTML = emailContent.html; 17 | 18 | // valid email file 19 | expect(subject).toBe('test'); 20 | expect(HTML).toBe('
Message
\n'); 21 | }); 22 | 23 | it(`The EML file ends with blank lines.`, async ()=>{ 24 | const emailParser = new EmailParser(); 25 | const emailContent: Email = await emailParser.parse(EMLEndsWithBlankLines); 26 | 27 | const subject = emailContent.subject; 28 | const HTML = emailContent.html; 29 | 30 | // valid email file 31 | expect(subject).toBe('test'); 32 | expect(HTML).toBe('
Message
\n'); 33 | }); 34 | 35 | 36 | it(`'No Subject', If an email without a subject.`, async ()=>{ 37 | const emailParser = new EmailParser(); 38 | const emailContent: Email = await emailParser.parse(emailWithoutSubject); 39 | 40 | const subject = emailContent.subject; 41 | const HTML = emailContent.html; 42 | 43 | expect(subject).toBe('No Subject'); 44 | expect(HTML).toBe('
Message
\n'); 45 | }); 46 | 47 | 48 | it(`email without body`, async ()=>{ 49 | const emailParser = new EmailParser(); 50 | const emailContent: Email = await emailParser.parse(emailWithoutBody); 51 | 52 | const subject = emailContent.subject; 53 | const HTML = emailContent.html; 54 | 55 | expect(subject).toBe('test'); 56 | expect(HTML).toBe('

This Email Has No Body

\n'); 57 | }); 58 | 59 | 60 | /* EML examples */ 61 | 62 | const emptyEML = ``; 63 | /* ------------------------------------------ */ 64 | const EMLStartsWithBlankLines = ` 65 | 66 | 67 | Subject: test 68 | From: bishoy.magdy.adeeb@gmail.com 69 | To: example@gmail.com 70 | Content-Type: text/html; charset="UTF-8" 71 | 72 |
Message
`; 73 | 74 | /* ------------------------------------------ */ 75 | 76 | const EMLEndsWithBlankLines = `Subject: test 77 | From: bishoy.magdy.adeeb@gmail.com 78 | To: example@gmail.com 79 | Content-Type: text/html; charset="UTF-8" 80 | 81 |
Message
82 | 83 | 84 | `; 85 | 86 | /* ------------------------------------------ */ 87 | 88 | const emailWithoutSubject = `Subject: 89 | From: bishoy.magdy.adeeb@gmail.com 90 | To: example@gmail.com 91 | Content-Type: text/html; charset="UTF-8" 92 | 93 |
Message
`; 94 | 95 | /* ------------------------------------------ */ 96 | 97 | const emailWithoutBody = `Subject: test 98 | From: bishoy.magdy.adeeb@gmail.com 99 | To: example@gmail.com`; 100 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "./dist/", 4 | "module": "commonjs", 5 | "target": "es2015", 6 | "jsx": "react", 7 | "allowJs": true, 8 | "baseUrl": "." 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | // ----------------------------------------------------------------------------- 2 | // This file is used to build the plugin file (.jpl) and plugin info (.json). It 3 | // is recommended not to edit this file as it would be overwritten when updating 4 | // the plugin framework. If you do make some changes, consider using an external 5 | // JS file and requiring it here to minimize the changes. That way when you 6 | // update, you can easily restore the functionality you've added. 7 | // ----------------------------------------------------------------------------- 8 | 9 | const path = require('path'); 10 | const crypto = require('crypto'); 11 | const fs = require('fs-extra'); 12 | const chalk = require('chalk'); 13 | const CopyPlugin = require('copy-webpack-plugin'); 14 | const WebpackOnBuildPlugin = require('on-build-webpack'); 15 | const tar = require('tar'); 16 | const glob = require('glob'); 17 | const execSync = require('child_process').execSync; 18 | 19 | const rootDir = path.resolve(__dirname); 20 | const userConfigFilename = './plugin.config.json'; 21 | const userConfigPath = path.resolve(rootDir, userConfigFilename); 22 | const distDir = path.resolve(rootDir, 'dist'); 23 | const srcDir = path.resolve(rootDir, 'src'); 24 | const publishDir = path.resolve(rootDir, 'publish'); 25 | 26 | const userConfig = Object.assign({}, { 27 | extraScripts: [], 28 | }, fs.pathExistsSync(userConfigPath) ? require(userConfigFilename) : {}); 29 | 30 | const manifestPath = `${srcDir}/manifest.json`; 31 | const packageJsonPath = `${rootDir}/package.json`; 32 | const manifest = readManifest(manifestPath); 33 | const pluginArchiveFilePath = path.resolve(publishDir, `${manifest.id}.jpl`); 34 | const pluginInfoFilePath = path.resolve(publishDir, `${manifest.id}.json`); 35 | 36 | function validatePackageJson() { 37 | const content = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); 38 | if (!content.name || content.name.indexOf('joplin-plugin-') !== 0) { 39 | console.warn(chalk.yellow(`WARNING: To publish the plugin, the package name should start with "joplin-plugin-" (found "${content.name}") in ${packageJsonPath}`)); 40 | } 41 | 42 | if (!content.keywords || content.keywords.indexOf('joplin-plugin') < 0) { 43 | console.warn(chalk.yellow(`WARNING: To publish the plugin, the package keywords should include "joplin-plugin" (found "${JSON.stringify(content.keywords)}") in ${packageJsonPath}`)); 44 | } 45 | 46 | if (content.scripts && content.scripts.postinstall) { 47 | console.warn(chalk.yellow(`WARNING: package.json contains a "postinstall" script. It is recommended to use a "prepare" script instead so that it is executed before publish. In ${packageJsonPath}`)); 48 | } 49 | } 50 | 51 | function fileSha256(filePath) { 52 | const content = fs.readFileSync(filePath); 53 | return crypto.createHash('sha256').update(content).digest('hex'); 54 | } 55 | 56 | function currentGitInfo() { 57 | try { 58 | let branch = execSync('git rev-parse --abbrev-ref HEAD', { stdio: 'pipe' }).toString().trim(); 59 | const commit = execSync('git rev-parse HEAD', { stdio: 'pipe' }).toString().trim(); 60 | if (branch === 'HEAD') branch = 'master'; 61 | return `${branch}:${commit}`; 62 | } catch (error) { 63 | const messages = error.message ? error.message.split('\n') : ['']; 64 | console.info(chalk.cyan('Could not get git commit (not a git repo?):', messages[0].trim())); 65 | console.info(chalk.cyan('Git information will not be stored in plugin info file')); 66 | return ''; 67 | } 68 | } 69 | 70 | function readManifest(manifestPath) { 71 | const content = fs.readFileSync(manifestPath, 'utf8'); 72 | const output = JSON.parse(content); 73 | if (!output.id) throw new Error(`Manifest plugin ID is not set in ${manifestPath}`); 74 | return output; 75 | } 76 | 77 | function createPluginArchive(sourceDir, destPath) { 78 | const distFiles = glob.sync(`${sourceDir}/**/*`, { nodir: true }) 79 | .map(f => f.substr(sourceDir.length + 1)); 80 | 81 | if (!distFiles.length) throw new Error('Plugin archive was not created because the "dist" directory is empty'); 82 | fs.removeSync(destPath); 83 | 84 | tar.create( 85 | { 86 | strict: true, 87 | portable: true, 88 | file: destPath, 89 | cwd: sourceDir, 90 | sync: true, 91 | }, 92 | distFiles 93 | ); 94 | 95 | console.info(chalk.cyan(`Plugin archive has been created in ${destPath}`)); 96 | } 97 | 98 | function createPluginInfo(manifestPath, destPath, jplFilePath) { 99 | const contentText = fs.readFileSync(manifestPath, 'utf8'); 100 | const content = JSON.parse(contentText); 101 | content._publish_hash = `sha256:${fileSha256(jplFilePath)}`; 102 | content._publish_commit = currentGitInfo(); 103 | fs.writeFileSync(destPath, JSON.stringify(content, null, '\t'), 'utf8'); 104 | } 105 | 106 | function onBuildCompleted() { 107 | try { 108 | fs.removeSync(path.resolve(publishDir, 'index.js')); 109 | createPluginArchive(distDir, pluginArchiveFilePath); 110 | createPluginInfo(manifestPath, pluginInfoFilePath, pluginArchiveFilePath); 111 | validatePackageJson(); 112 | } catch (error) { 113 | console.error(chalk.red(error.message)); 114 | } 115 | } 116 | 117 | const baseConfig = { 118 | mode: 'production', 119 | target: 'node', 120 | stats: 'errors-only', 121 | module: { 122 | rules: [ 123 | { 124 | test: /\.tsx?$/, 125 | use: 'ts-loader', 126 | exclude: /node_modules/, 127 | },{ 128 | include: /node_modules/, 129 | test: /\.mjs$/, 130 | type: 'javascript/auto' 131 | } 132 | ], 133 | }, 134 | }; 135 | 136 | const pluginConfig = Object.assign({}, baseConfig, { 137 | entry: './src/index.ts', 138 | resolve: { 139 | alias: { 140 | api: path.resolve(__dirname, 'api'), 141 | }, 142 | // JSON files can also be required from scripts so we include this. 143 | // https://github.com/joplin/plugin-bibtex/pull/2 144 | extensions: ['.js', '.tsx', '.ts', '.json'], 145 | }, 146 | output: { 147 | filename: 'index.js', 148 | path: distDir, 149 | }, 150 | plugins: [ 151 | new CopyPlugin({ 152 | patterns: [ 153 | { 154 | from: '**/*', 155 | context: path.resolve(__dirname, 'src'), 156 | to: path.resolve(__dirname, 'dist'), 157 | globOptions: { 158 | ignore: [ 159 | // All TypeScript files are compiled to JS and 160 | // already copied into /dist so we don't copy them. 161 | '**/*.ts', 162 | '**/*.tsx', 163 | ], 164 | }, 165 | }, 166 | ], 167 | }), 168 | ], 169 | }); 170 | 171 | const extraScriptConfig = Object.assign({}, baseConfig, { 172 | resolve: { 173 | alias: { 174 | api: path.resolve(__dirname, 'api'), 175 | }, 176 | extensions: ['.js', '.tsx', '.ts', '.json'], 177 | }, 178 | }); 179 | 180 | const createArchiveConfig = { 181 | stats: 'errors-only', 182 | entry: './dist/index.js', 183 | output: { 184 | filename: 'index.js', 185 | path: publishDir, 186 | }, 187 | plugins: [new WebpackOnBuildPlugin(onBuildCompleted)], 188 | }; 189 | 190 | function resolveExtraScriptPath(name) { 191 | const relativePath = `./src/${name}`; 192 | 193 | const fullPath = path.resolve(`${rootDir}/${relativePath}`); 194 | if (!fs.pathExistsSync(fullPath)) throw new Error(`Could not find extra script: "${name}" at "${fullPath}"`); 195 | 196 | const s = name.split('.'); 197 | s.pop(); 198 | const nameNoExt = s.join('.'); 199 | 200 | return { 201 | entry: relativePath, 202 | output: { 203 | filename: `${nameNoExt}.js`, 204 | path: distDir, 205 | library: 'default', 206 | libraryTarget: 'commonjs', 207 | libraryExport: 'default', 208 | }, 209 | }; 210 | } 211 | 212 | function buildExtraScriptConfigs(userConfig) { 213 | if (!userConfig.extraScripts.length) return []; 214 | 215 | const output = []; 216 | 217 | for (const scriptName of userConfig.extraScripts) { 218 | const scriptPaths = resolveExtraScriptPath(scriptName); 219 | output.push(Object.assign({}, extraScriptConfig, { 220 | entry: scriptPaths.entry, 221 | output: scriptPaths.output, 222 | })); 223 | } 224 | 225 | return output; 226 | } 227 | 228 | function main(processArgv) { 229 | const yargs = require('yargs/yargs'); 230 | const argv = yargs(processArgv).argv; 231 | 232 | const configName = argv['joplin-plugin-config']; 233 | if (!configName) throw new Error('A config file must be specified via the --joplin-plugin-config flag'); 234 | 235 | // Webpack configurations run in parallel, while we need them to run in 236 | // sequence, and to do that it seems the only way is to run webpack multiple 237 | // times, with different config each time. 238 | 239 | const configs = { 240 | // Builds the main src/index.ts and copy the extra content from /src to 241 | // /dist including scripts, CSS and any other asset. 242 | buildMain: [pluginConfig], 243 | 244 | // Builds the extra scripts as defined in plugin.config.json. When doing 245 | // so, some JavaScript files that were copied in the previous might be 246 | // overwritten here by the compiled version. This is by design. The 247 | // result is that JS files that don't need compilation, are simply 248 | // copied to /dist, while those that do need it are correctly compiled. 249 | buildExtraScripts: buildExtraScriptConfigs(userConfig), 250 | 251 | // Ths config is for creating the .jpl, which is done via the plugin, so 252 | // it doesn't actually need an entry and output, however webpack won't 253 | // run without this. So we give it an entry that we know is going to 254 | // exist and output in the publish dir. Then the plugin will delete this 255 | // temporary file before packaging the plugin. 256 | createArchive: [createArchiveConfig], 257 | }; 258 | 259 | // If we are running the first config step, we clean up and create the build 260 | // directories. 261 | if (configName === 'buildMain') { 262 | fs.removeSync(distDir); 263 | fs.removeSync(publishDir); 264 | fs.mkdirpSync(publishDir); 265 | } 266 | 267 | return configs[configName]; 268 | } 269 | 270 | let exportedConfigs = []; 271 | 272 | try { 273 | exportedConfigs = main(process.argv); 274 | } catch (error) { 275 | console.error(chalk.red(error.message)); 276 | process.exit(1); 277 | } 278 | 279 | if (!exportedConfigs.length) { 280 | // Nothing to do - for example where there are no external scripts to 281 | // compile. 282 | process.exit(0); 283 | } 284 | 285 | module.exports = exportedConfigs; 286 | --------------------------------------------------------------------------------