This repository has been archived by the owner on May 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
thread-unsubscribe-store.es6
227 lines (215 loc) · 7.74 KB
/
thread-unsubscribe-store.es6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import {
Actions,
TaskFactory,
FocusedPerspectiveStore,
NylasAPI,
NylasAPIRequest,
} from 'nylas-exports';
import NylasStore from 'nylas-store';
import {MailParser} from 'mailparser';
import {remote} from 'electron';
import open from 'open';
import _ from 'underscore';
import {logIfDebug, shortenURL, shortenEmail, interpretEmail, userConfirm} from './util/helpers';
import {electronCantOpen} from './util/blacklist';
import EmailParser from './util/email-parser';
import ThreadConditionType from './enum/threadConditionType';
import path from 'path';
export default class ThreadUnsubscribeStore extends NylasStore {
constructor(thread) {
super();
this.settings = NylasEnv.config.get("n1-unsubscribe");
if (!thread) {
NylasEnv.reportError(new Error("Invalid thread object"));
this.threadState = {
id: null,
condition: ThreadConditionType.ERRORED,
}
} else {
this.thread = thread;
this.threadState = {
id: this.thread.id,
condition: ThreadConditionType.LOADING,
}
this.messages = this.thread.__messages;
this._loadLinks();
}
}
_triggerUpdate() {
this.trigger(this.threadState);
}
unsubscribe() {
if (this.parser && this.parser.canUnsubscribe()) {
const unsubscribeHandler = (error, unsubscribed) => {
if (error) {
this.threadState.condition = ThreadConditionType.ERRORED;
NylasEnv.reportError(error, this);
} else if (unsubscribed) {
this._moveThread();
this.threadState.condition = ThreadConditionType.UNSUBSCRIBED;
}
this._triggerUpdate();
};
if (this.parser.emails.length > 0) {
this._unsubscribeViaMail(this.parser.emails[0], unsubscribeHandler);
} else {
this._unsubscribeViaBrowser(this.parser.urls[0], unsubscribeHandler);
}
}
}
_loadLinks() {
this._loadMessagesViaAPI((error, email) => {
if (error) {
this.threadState.condition = ThreadConditionType.ERRORED;
NylasEnv.reportError(error, this);
} else if (email) {
const confirmText = "Are you sure that you want to unsubscribe?";
this.isForwarded = this.thread.subject.match(/^Fwd: /i);
this.confirmText = this.isForwarded ? `The email was forwarded. ${confirmText}` : confirmText;
this.parser = new EmailParser(email.headers, email.html, email.text);
this.threadState.condition = this.parser.canUnsubscribe() ? ThreadConditionType.READY : ThreadConditionType.DISABLED;
// Output troubleshooting info
logIfDebug(`Found ${(this.parser.canUnsubscribe() ? "" : "no ")}links for: "${this.thread.subject}"`);
logIfDebug(this.parser);
} else {
this.threadState.condition = ThreadConditionType.DISABLED;
}
this._triggerUpdate();
});
}
_runNylasQuery(options, success, error) {
const IS_NYLAS_MAIL = path.parse(NylasEnv.getConfigDirPath()).base == ".nylas-mail"
if (IS_NYLAS_MAIL) {
// Nylas Mail
const loadEmail = new NylasAPIRequest({
api: NylasAPI,
options: options,
});
loadEmail.run()
.then(success)
.catch(error);
} else {
// Nylas N1
options.success = success;
options.error = error;
NylasAPI.makeRequest(options);
}
}
_loadMessagesViaAPI(callback) {
if (this.messages && this.messages.length > 0) {
if (this.messages[0].draft || (this.messages[0].categories &&
_.some(this.messages[0].categories, _.matcher({displayName: "Sent Mail"})))) {
// Can't unsubscribe from draft or sent emails
callback(null, null);
} else {
// Fetch the email contents to parse for unsubscribe links
// NOTE: This will only make a request for the first email message in the thread,
// instead of all messages based on the assumption that the first email will have
// an unsubscribe link iff you can unsubscribe from that thread.
const messagePath = `/messages/${this.messages[0].id}`;
const options = {
accountId: this.thread.accountId,
path: messagePath,
headers: {Accept: "message/rfc822"},
json: false,
};
const success = (rawEmail) => {
const mailparser = new MailParser();
mailparser.on('end', (parsedEmail) => {
callback(null, parsedEmail);
});
mailparser.write(rawEmail);
mailparser.end();
};
const error = (error) => {
callback(error);
};
this._runNylasQuery(options, success, error);
}
} else {
callback(new Error('No messages found to parse for unsubscribe links.'));
}
}
_unsubscribeViaBrowser(url, callback) {
if ((!this.isForwarded && !this.settings.confirmForBrowser) ||
userConfirm(this.confirmText, `A browser will be opened at: ${shortenURL(url)}`)) {
logIfDebug(`Opening a browser window to:\n${url}`);
if (this.settings.defaultBrowser === "native" || electronCantOpen(url)) {
open(url);
callback(null, /* unsubscribed=*/true);
} else {
const browserWindow = new remote.BrowserWindow({
'web-preferences': { 'web-security': false, 'nodeIntegration': false },
'width': 1000,
'height': 800,
'center': true,
"alwaysOnTop": true,
});
browserWindow.on('closed', () => {
callback(null, /* unsubscribed=*/true);
});
browserWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription) => {
// Unable to load this URL in a browser window. Redirect to a native browser.
logIfDebug(`Failed to open URL in browser window: ${errorCode} ${errorDescription}`);
browserWindow.destroy();
open(url);
});
browserWindow.loadURL(url);
browserWindow.show();
}
} else {
callback(null, /* unsubscribed=*/false);
}
}
_unsubscribeViaMail(emailAddress, callback) {
if (emailAddress) {
if ((!this.isForwarded && !this.settings.confirmForEmail) ||
userConfirm(this.confirmText, `An email will be sent to:\n${shortenEmail(emailAddress)}`)) {
logIfDebug(`Sending an email to: ${emailAddress}`);
const success = () => {};
const error = (error) => {
NylasEnv.reportError(error, this);
};
const options = {
accountId: this.thread.accountId,
path: '/send',
method: 'POST',
body: interpretEmail(emailAddress),
};
this._runNylasQuery(options, success, error);
// Send the callback now so that emails are moved immediately
// instead of waiting for the email to be sent.
callback(null, /* unsubscribed= */true);
} else {
callback(null, /* unsubscribed= */false);
}
} else {
callback(new Error(`Invalid email address (${emailAddress})`), /* unsubscribed= */false);
}
}
_moveThread() {
switch (this.settings.handleThreads) {
case "trash":
if (FocusedPerspectiveStore.current().canTrashThreads([this.thread])) {
const tasks = TaskFactory.tasksForMovingToTrash({
threads: [this.thread],
fromPerspective: FocusedPerspectiveStore.current(),
});
Actions.queueTasks(tasks);
}
break;
case "archive":
if (FocusedPerspectiveStore.current().canArchiveThreads([this.thread])) {
const tasks = TaskFactory.tasksForArchiving({
threads: [this.thread],
fromPerspective: FocusedPerspectiveStore.current(),
});
Actions.queueTasks(tasks);
}
break;
default:
// "none" case -- do not move email
}
Actions.popSheet();
}
}