Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

week 6 & 7& 8 #5

Merged
merged 3 commits into from
Aug 23, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"@typescript-eslint/parser": "^5.30.7",
"chalk": "^4.1.0",
"copy-webpack-plugin": "^6.1.0",
"cross-blob": "^2.0.0",
"eslint": "^8.20.0",
"eslint-config-google": "^0.14.0",
"fs-extra": "^9.0.1",
Expand All @@ -35,6 +36,7 @@
"dependencies": {
"imap": "^0.8.19",
"net": "^1.0.2",
"postal-mime": "^1.0.13",
"tls": "^0.0.1"
}
}
1 change: 1 addition & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export const SECTION_NAME = 'Email_Plugin';
export const EXPORT_TYPE = 'Export_Type';
export const ATTACHMENTS = 'Attachments';
export const PLUGIN_ICON = 'fa fa-envelope';
export const CONVERTED_MESSAGES = 'Converted_Messages';
36 changes: 36 additions & 0 deletions src/core/emailParser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const postalMime = require('postal-mime/dist/node').postalMime.default;
import {EmailContent} from '../model/emailContent.model';


export default class EmailParser extends postalMime {
emailContent: EmailContent;
constructor() {
super();
}

// Email in RFC 822 format.
async parse(message: string): Promise<EmailContent> {
// A message is invalid if it starts with a space.
message = message.trim();

try {
this.emailContent = await super.parse(message);
this.emailContent.subject = this.subject;
this.emailContent.html = this.html;
this.emailContent.attachments = this.emailContent.attachments;

return (this.emailContent);
} catch (err) {
throw err;
}
}

get subject() {
return this.emailContent.subject || 'No Subject';
}

get html() {
return this.emailContent.html || '<div><h1>This Email Has No Body</h1></div>\n';
}
}

107 changes: 105 additions & 2 deletions src/core/imap.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
import * as Imap from 'imap';
import {ImapConfig} from '../model/imapConfig.model';
import {Query} from '../model/Query.model';
import joplin from 'api';
import {CONVERTED_MESSAGES} from '../constants';
import {PostNote} from './postNote';
import EmailParser from './emailParser';
import {EmailContent} from '../model/emailContent.model';

export class IMAP {
private imap = null;
private monitorId = null;
private query: Query = null;
private delayTime = 1000 * 5;

// To check if there is a query not completed yet.
private pending = false;

constructor(config: ImapConfig) {
this.imap = new Imap({
...config,
Expand Down Expand Up @@ -51,7 +59,7 @@ export class IMAP {
});
}

search(criteria) {
search(criteria): Promise<number[]> {
return new Promise((resolve, reject) => {
this.imap.search(criteria, (err, messages) => {
if (err) {
Expand Down Expand Up @@ -83,6 +91,81 @@ export class IMAP {
});
}

fetchAll(messages: number[], structure: object) {
return new Promise<string[]>((resolve, reject) => {
const fetch = this.imap.fetch(messages, structure);
const convertedMessages: string[] = [];

// For each message
fetch.on('message', (message, seqno) => {
let data = '';

message.on('body', (stream) => {
stream.on('data', function(chunk) {
// push data
data += chunk;
});
});

message.once('end', async () => {
convertedMessages.push(data);
});
});

// All messages have been fetched of type RFC 822.
fetch.on('end', () => {
resolve(convertedMessages);
});

this.imap.once('error', function(err: Error) {
reject(err);
});
});
}

newMessages(messages: number[]): Promise<number[]> {
return new Promise(async (resolve, reject)=>{
if (messages.length === 0) {
return resolve([]);
}

try {
const value = await joplin.settings.value(CONVERTED_MESSAGES);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This setting will grow over time, could become a performance bottleneck at some point.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I came up with a better solution: get the converted message and store it in a variable, then query that variable to see if there is a new message, and when there is, the values are updated. This means that the converted message in Joplin is not only updated until there is a new message(If you have another solution please tell me).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure what you mean by variable here? You need to persists this information between restarts somehow.

It seems to me that the easiest way to store this information is to use the email account itself - you either delete messages you've converted, mark them read, or move to another folder.
Or you could only store the date of the last seen email and only process newer. This way you store it on the client but at least it's just one number per mailbox.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

indeed, the thought came to my mind to store this information by using the email account itself, but there is no standard way to mark the message. To be more clear, some email providers allow you to mark messages while others don't.

But I found a solution One of the flags that are standard for all email providers is the 'SEEN' flag. Every message is flagged as 'UNSEEN' if the message is new or the user marks it as 'UNSEEN'.

So I will add an additional condition in the search, which is to search for the messages that are "from" a specific email and marked as "UNSEEN" and then mark the messages as "SEEN" after fetching them.

I think this solution is better than deleting. and the user can mark as an "unread" message any number of messages in their email provider.

Sorry for the delay in suggesting this solution. It took me a lot of time to test this solution across different email providers.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

example:

git2.mp4

const email = this.imap._config.user;

// Each email has a list of messages ids, which have been converted to notes before.
if (!(email in value)) {
value[email] = {
['from']: [],
};
await joplin.settings.setValue(CONVERTED_MESSAGES, value);
}

const converted = value[email]['from'];
const newMessages = messages.filter((x) => !converted.includes(x));

return resolve(newMessages);
} catch (err) {
return reject(err);
}
});
}

updateConvertedMessages(newMessages: number[]): Promise<void> {
return new Promise(async (resolve, reject)=>{
try {
const value = await joplin.settings.value(CONVERTED_MESSAGES);
const email = this.imap._config.user;

value[email]['from'].push(...newMessages);
await joplin.settings.setValue(CONVERTED_MESSAGES, value);
resolve();
} catch (err) {
return reject(err);
}
});
}

monitor() {
let mailBox = null;
let criteria = null;
Expand All @@ -100,11 +183,31 @@ export class IMAP {

const messages = await this.search(criteria);

console.log(messages);
const newMessages = await this.newMessages(messages);

console.log(newMessages);

if (newMessages.length && !this.pending) {
this.pending = true;
const data = await this.fetchAll(newMessages, {bodies: ''});

for (let i = 0; i < data.length; i++) {
const email = new EmailParser();
const emailContent: EmailContent = await email.parse(data[i]);

// for test
const note = new PostNote();
await note.post(emailContent, ['joplin'], []);
}
/* to save the id of converted messages */
await this.updateConvertedMessages(newMessages);
this.pending = false;
}
} catch (err) {
// Revoke the query
this.query = null;
alert(err);
throw err;
}
}
}, this.delayTime);
Expand Down
52 changes: 52 additions & 0 deletions src/core/postAttachments.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import {tmpdir} from 'os';
import {sep} from 'path';
import joplin from 'api';
import {Attachment} from '../model/attachment.model';
import {AttachmentProperties} from '../model/attachmentProperties.mode';
const fs = joplin.require('fs-extra');

export class Attachments {
tempFolder: string = `${tmpdir}${sep}joplin-email-plugin${sep}`;
attachments: Attachment[];

constructor(attachments: Attachment[]) {
this.attachments = attachments.filter((e: Attachment)=>e.filename !== '');
}


async postAttachments(): Promise<AttachmentProperties[]> {
const attachmentsProp: AttachmentProperties[] = [];
const tempFolder = this.tempFolder;

try {
// for each attachment will create an actual file of the attachment and posting to Joplin.
for (let i = 0; i < this.attachments.length; i++) {
const {contentId, filename} = this.attachments[i];
const path = `${tempFolder}${this.attachments[i].filename}`;

// to create a file
fs.writeFileSync(path, Buffer.from(this.attachments[i].content));

// To post a file to Joplin
const resource = await joplin.data.post(
['resources'],
null,
{title: filename}, // Resource metadata
[
{
path: path, // Actual file
},
],
);

attachmentsProp.push({contentId: contentId, id: resource.id});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

might be worth cleaning up the temp file afterwards

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried deleting folders in this place, but it will slow down when there are a lot of messages that you want to convert because it will create and delete and so on. What I did is every time the plugin starts, it deletes the old attachments and starts creating a new temporary folder.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could potentially be a security risk, say, if you run the plugin in Joplin portable from a USB drive, your emails will be left on the computer.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can't the delete job be a self-running/isolated background job?
The "old" temp folder could be renamed, a new one created, old, now renamed, deleted in the background

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could potentially be a security risk, say, if you run the plugin in Joplin portable from a USB drive, your emails will be left on the computer.

Okay, I refacted the function to this mechanism.

  • Create a temp folder
    • Post all emails including attachments to Joplin.
  • Remove a temp folder

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can't the delete job be a self-running/isolated background job?
The "old" temp folder could be renamed, a new one created, old, now renamed, deleted in the background

It's a sync function, which means I can't go to the next line after finishing this function(delete a temp folder).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could in theory use a web worker (or whatever the equivalent of threads in the JS world is called) but this looks like an overkill.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could in theory use a web worker (or whatever the equivalent of threads in the JS world is called) but this looks like an overkill.

This looks very good since we can add all the notes and attachments posting functions in the other JS thread.
I will read more about web worker. and I will definitely add it if I notice its presence will be important.

}

return attachmentsProp;
} catch (err) {
throw err;
}
}
}


Loading