-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
314 lines (269 loc) · 9.61 KB
/
Copy pathbackground.js
File metadata and controls
314 lines (269 loc) · 9.61 KB
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
// First Part Handles the User Authentication Part.
const REDIRECT_URL = "https://localhost:6547/";
const CLIENT_ID = "Put your clientId here";
const SCOPES = ["openid", "email", "profile"];
const AUTH_URL =
`https://accounts.google.com/o/oauth2/auth\
?client_id=${CLIENT_ID}\
&response_type=token\
&redirect_uri=${REDIRECT_URL}\
&scope=${encodeURIComponent(SCOPES.join(' '))}`;
const VALIDATION_BASE_URL = "https://www.googleapis.com/oauth2/v3/tokeninfo";
/*
Used when user is logging in for the first time.
*/
async function register(accountId, email, registerDetail) {
chrome.identity.getAuthToken({ account: { id: accountId }, interactive: true }, function (token) {
if (token) {
chrome.storage.sync.set({ [email]: token });
chrome.storage.sync.set({ "Accounts": registerDetail });
chrome.tabs.query({ active: true, currentWindow: true }, function (tab) {
chrome.tabs.sendMessage(tab[0].id, { reload: true });
})
}
})
}
/*
When new access_token is required
*/
async function getToken(accountId, email) {
chrome.identity.getAuthToken({ account: { id: accountId }, interactive: false }, function (token) {
if (token) {
chrome.storage.sync.set({ [email]: token });
} else {
chrome.storage.sync.remove(email);
removeAccount(accountId);
}
});
}
/*
Logouts a logged in user.
Pass Account as {id: accountId}
*/
async function logout(Account, logoutOnce) {
try {
chrome.identity.getAuthToken({ account: Account, interactive: false }, (token) => {
var url = 'https://accounts.google.com/o/oauth2/revoke?token=' + token;
fetch(url);
chrome.identity.removeCachedAuthToken({ token: token });
});
if (logoutOnce) removeAccount(Account.id, true);
} catch (error) {
throw error;
}
}
async function removeAccount(id, refresh = false) {
chrome.storage.sync.get("Accounts", (accounts) => {
const newAccounts = {};
const account = Object.entries(accounts.Accounts);
for (var i in account) account[i][1] !== id && (newAccounts[account[i][0]] = account[i][1]);
chrome.storage.sync.set({ "Accounts": newAccounts }, () => {
if (refresh) {
chrome.tabs.query({ active: true, currentWindow: true }, function (tab) {
chrome.tabs.sendMessage(tab[0].id, { reload: true });
})
}
})
})
}
function extractAccessToken(redirectUri) {
let m = redirectUri.match(/[#?](.*)/);
if (!m || m.length < 1)
return null;
let params = new URLSearchParams(m[1].split("#")[0]);
return params.get("access_token");
}
/**
Validate the token contained in redirectURL.
This follows essentially the process here:
https://developers.google.com/identity/protocols/OAuth2UserAgent#tokeninfo-validation
- make a GET request to the validation URL, including the access token
- if the response is 200, and contains an "aud" property, and that property
matches the clientID, then the response is valid
- otherwise it is not valid
Note that the Google page talks about an "audience" property, but in fact
it seems to be "aud".
*/
function validate(redirectURL) {
const accessToken = extractAccessToken(redirectURL);
if (!accessToken) {
throw "Authorization failure";
}
const validationURL = `${VALIDATION_BASE_URL}?access_token=${accessToken}`;
const validationRequest = new Request(validationURL, {
method: "GET"
});
function checkResponse(response) {
if (response.status != 200) {
throw "Token validation error";
}
response.json().then((json) => {
if (json.aud && (json.aud === CLIENT_ID)) {
const email = json.email, accountId = json.sub;
chrome.storage.sync.get("Accounts", (account) => {
const accounts = account.Accounts
if (!accounts || !accounts[email]) {
register(accountId, email, { ...accounts, [email]: accountId }, true);
}
});
}
else {
throw "Token validation error";
}
});
}
fetch(validationRequest).then(checkResponse);
}
/*
Gives the tab which is currently active
*/
async function getCurrentTab() {
let queryOptions = { active: true, currentWindow: true };
let [tab] = await chrome.tabs.query(queryOptions);
return tab;
}
/*
User Chooses which google account they want to use for registering
*/
async function authenticate(tabId, mainTab) {
chrome.tabs.onUpdated.addListener(function listenUpdates(id, changeInfo, tab) {
if (id == tabId) {
if (changeInfo.url) {
var ok = 1, url = changeInfo.url;
for (let i = 0; i < REDIRECT_URL.length && ok; ++i) ok &= (REDIRECT_URL[i] == url[i]);
if (ok) {
validate(url);
chrome.tabs.onUpdated.removeListener(listenUpdates);
chrome.tabs.remove(id);
chrome.tabs.highlight({ "tabs": mainTab });
}
}
}
});
}
/*
Register a user, so that they can use this chrome extension.
*/
async function userRegister() {
const mainTab = await getCurrentTab();
const tab = await chrome.tabs.create({ url: AUTH_URL });
authenticate(tab.id, mainTab.index);
}
/*
Returns a new access_token that can be used when the current token expires.
*/
async function refreshToken(email) {
chrome.storage.sync.get("Accounts", (accounts) => {
const account = accounts.Accounts;
const accountId = account[email];
if (accountId) getToken(accountId, email);
else throw "User Not found!!";
})
}
/*
Signs Out all signed in users at once
*/
async function signOutAllUsers() {
chrome.storage.sync.get("Accounts", (accounts) => {
const account = Object.entries(accounts.Accounts);
for (var i in account) {
logout({ id: account[i][1] }, false);
}
chrome.storage.sync.set({ "Accounts": {} }, () => {
chrome.tabs.query({ active: true, currentWindow: true }, function (tab) {
chrome.tabs.sendMessage(tab[0].id, { reload: true });
})
})
});
}
// Second Part - Handles user requests
async function MessageHandler(message, sender, callback) {
switch (message.payload) {
case 'SetAlarm':
setAlarm(message.email, message.messageId, message.byUser);
break;
case 'RemoveAlarm':
removeAlarm(message.email, message.messageId, message.byUser);
break;
case 'RefreshToken':
refreshToken(message.email);
break;
case 'Register':
userRegister();
break;
case 'Logout':
logout({ id: message.accountId }, true)
break;
case 'SignoutAll':
signOutAllUsers()
break;
case 'changeWaitTime':
changeDay(message.time);
break;
}
}
chrome.runtime.onMessage.addListener(MessageHandler);
// Third Part - Create Alarm and Delete Email after alarm is triggered
/* States:
undefined - new_email, unread and unregistered. OR Alarm was removed as user read the message
1 - User set the Alarm
2 - User removed the Alarm
3 - Alarm was set as message was unread.
*/
function changeDay(minutes) {
chrome.storage.sync.set({ "delay": minutes });
chrome.tabs.query({ active: true, currentWindow: true }, function (tab) {
chrome.tabs.sendMessage(tab[0].id, { reload: true });
})
}
function setAlarm(gmail, messageId, byUser) {
const alarmName = gmail + " " + messageId, messageName = gmail + messageId;
chrome.storage.sync.get("delay", (json) => {
const delay = parseInt(json.delay) || 43200;
chrome.alarms.create(alarmName, { 'delayInMinutes': delay });
});
chrome.storage.sync.set({ [messageName]: byUser ? 1 : 3 });
}
function removeAlarm(gmail, messageId, byUser) {
const alarmName = gmail + " " + messageId, messageName = gmail + messageId;
chrome.alarms.clear(alarmName);
if (byUser) chrome.storage.sync.set({ [messageName]: 2 });
else chrome.storage.sync.remove(messageName);
}
chrome.alarms.onAlarm.addListener(deleteEmail);
async function deleteEmail(alarm) {
const name = alarm.name;
const [gmail, messageId] = name.split(' ');
chrome.storage.sync.get(gmail, (json) => {
const token = json[gmail];
let init = {
method: 'POST',
async: true,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
},
'contentType': 'json'
};
fetch(`https://gmail.googleapis.com/gmail/v1/users/${gmail}/threads/${messageId}/trash`, init)
.then(res => {
if (res.status == 401) {
refreshToken(gmail);
Dhoka(gmail, messageId);
}
if (res.status == 200) {
chrome.storage.sync.remove(gmail + messageId);
}
})
});
}
function Dhoka(gmail, messageId) {
function handleChange(changes, areaName) {
if (changes[gmail]) {
chrome.storage.onChanged.removeListener(handleChange);
if (changes[gmail]["newValue"]) deleteEmail({ name: gmail + ' ' + messageId });
else chrome.storage.sync.remove(gmail + messageId);
}
}
chrome.storage.onChanged.addListener(handleChange);
}