-
Notifications
You must be signed in to change notification settings - Fork 0
/
popup.js
executable file
·361 lines (295 loc) · 9.18 KB
/
popup.js
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
$(function () {
$('#info').popover()
})
// Updates quizlet elements based off if user has logged in before
chrome.storage.sync.get({authToken: null}, function(items) {
var connect = document.getElementById("quizlet")
var flashcard = document.getElementById("toggleQuizlet")
if (items.authToken != null) {
connect.style.display = "none"
flashcard.style.display = "block"
} else {
connect.style.display = "block"
flashcard.style.display = "none"
}
});
// Checks if array has duplicates
function hasDuplicates(array) {
return (new Set(array)).size !== array.length;
}
// Takes full URL and returns hostname only
function extractHostname(url) {
var hostname;
//find & remove protocol (http, ftp, etc.) and get hostname
if (url.indexOf("://") > -1) {
hostname = url.split('/')[2];
}
else {
hostname = url.split('/')[0];
}
//find & remove port number
hostname = hostname.split(':')[0];
//find & remove "?"
hostname = hostname.split('?')[0];
return hostname;
}
var language;
var difficulty;
var currTab;
// Get selectors by ID
var TOGGLE = document.getElementById("toggle");
var e = document.getElementById("languageSelect");
var DIFF = document.getElementById("difficulty");
// Create event listeners when settings are changed, calls corresponding function
if(DIFF){
DIFF.addEventListener('change', selectDiff, false);
}
if(e){
e.addEventListener('change', selectLanguage, false);
}
if(TOGGLE){
TOGGLE.addEventListener('click', toggled, false);
}
// Get tabID for future use in refreshing
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
currTab = tabs[0];
});
// Retrieve settings from chrome storage
chrome.storage.sync.get({language: 'hy', difficulty: 60, whitelist: []}, function(items) {
// Flag to check if current hostname is on whitelist
onList = items.whitelist.indexOf( extractHostname(currTab.url) ) != -1
language = items.language
difficulty = items.difficulty
e.value = language;
DIFF.value = difficulty;
if( !onList ) {
TOGGLE.active = false;
TOGGLE.innerHTML = "Off for this domain";
TOGGLE.style.backgroundColor = "#455560";
} else {
TOGGLE.active = true;
TOGGLE.innerHTML = "On for this domain";
TOGGLE.style.backgroundColor = "#0A54D3";
}
});
function toggled() {
// Translation is on, need to turn off
console.log(onList);
if (onList == true) {
// Change UI to react
TOGGLE.active = false;
TOGGLE.innerHTML = "Off for this domain";
TOGGLE.style.backgroundColor = "#455560";
// Remove domain to whitelist
chrome.storage.sync.get({whitelist: []}, function(items) {
// Get index of hostname to remove later
var index = items.whitelist.indexOf(extractHostname(currTab.url))
// Remove hostname from whitelist
if (index > -1) {
items.whitelist.splice(index, 1);
}
// Save changes
chrome.storage.sync.set({'whitelist': items.whitelist});
});
// Refresh tab
// Translation is off, need to turn on
} else {
// Change UI to reflect change
TOGGLE.active = true;
TOGGLE.innerHTML = "On for this domain";
TOGGLE.style.backgroundColor = "#0A54D3";
// Add domain to whitelist
chrome.storage.sync.get({whitelist: []}, function(items) {
// Append current hostname to whitelist
items.whitelist.push(extractHostname(currTab.url))
console.log(extractHostname(currTab.url));
chrome.storage.sync.set({'whitelist': items.whitelist}, function() {
chrome.tabs.executeScript(currTab.id, {file: "inject.js"});
});
});
}
// Close popup when done
chrome.tabs.update(currTab.id, {url: currTab.url});
window.close()
}
// Change language
function selectLanguage(){
language = e.options[e.selectedIndex].value;
chrome.storage.sync.set({'language': language});
chrome.tabs.executeScript(currTab.id, {file: "inject.js"});
}
// Change difficulty
function selectDiff(){
difficulty = DIFF.value;
chrome.storage.sync.set({'difficulty': difficulty});
chrome.tabs.executeScript(currTab.id, {file: "inject.js"});
}
/// methods for event-handling
function quizletAuthorize() {
var url = "https://quizlet.com/authorize";
chrome.identity.launchWebAuthFlow (
{
"url": url + "?response_type=code&client_id=" + clientID +
"&scope=read%20write_set&state=gimmeit",
"interactive": true,
}, function(redirect_url) {
if(typeof redirect_url !== "undefined") {
var code = redirect_url.substring(
redirect_url.search("code=") + 5,
redirect_url.length
);
getAccessToken(code, redirect_url);
}
}
);
}
// handles user authorization for the Quizlet API
$("#quizlet").click(function() {
quizletAuthorize();
});
$('#changeAccount').click(function (){
quizletAuthorize();
});
$('#toggleQuizlet').click(function() {
$('#quizletIcon').toggleClass("fa fa-plus fa fa-minus");
updateCard();
});
// updates card set when
$("#setSelect").change(function() {
saveSet($("#setSelect option:selected").val());
loadCards();
});
// change card when you press right arrow
$(document).keydown(function(e) {
switch(e.which) {
case 39: // right
break;
}
e.preventDefault(); // prevent the default action
updateCard();
});
/// methods for core functionality minus events
loadSets();
// retrieves access token based on code from user authorization
function getAccessToken(code, redirect_url) {
var secondURL = "https://api.quizlet.com/oauth/token?grant_type=authorization_code&code=" + code + "&redirect_uri=redirect_url";
$.ajax({
xhrFields: {
withCredentials: true
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(clientID + ":" + secret));
},
method: "POST",
url: "https://api.quizlet.com/oauth/token",
data: {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": redirect_url
}
})
.done(function(res) {
saveToken(res.access_token);
saveUser(res.user_id);
loadSets();
})
.fail(function(err) {
console.log(err.error_description);
});
}
// loads the select field with user's available sets
function loadSets() {
chrome.storage.sync.get(['username', 'authToken'], function(items) {
var username = items.username;
var token = items.authToken;
var url = "https://api.quizlet.com/2.0/users/" + username + "/sets";
$.ajax({
xhrFields: {
withCredentials: true
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
},
method: "GET",
url: url,
dataType: "json"
})
.done(function(res) {
$('#setSelect option').remove();
res.forEach(function(set) {
$("#setSelect").append("<option value='" + set.id + "'>" + set.title + "</option>");
});
loadCards();
previousSet();
})
.fail(function(err) {
console.log(err.error_description);
});
});
}
// saves the card set for the current selected set
function loadCards() {
var currentSet = $("#setSelect option:selected").val();
chrome.storage.sync.get('authToken', function(items) {
var token = items.authToken;
var url = "https://api.quizlet.com/2.0/sets/" + currentSet + "/terms";
$.ajax({
xhrFields: {
withCredentials: true
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
},
method: "GET",
url: url,
dataType: "json"
})
.done(function(res) {
var cards = [];
res.forEach(function(term) {
cards.push([term.term, term.definition]);
});
chrome.storage.sync.set({'currentCards': cards}, function() {
// Notify that we saved.
updateCard();
});
})
.fail(function(err) {
console.log(err.error_description);
});
});
}
// changes the UI of the flashcard
function updateCard() {
chrome.storage.sync.get('currentCards', function(items) {
var randomIndex = Math.floor(Math.random() * items.currentCards.length);
$("#term").text(items.currentCards[randomIndex][0]);
$("#termTranslation").text(items.currentCards[randomIndex][1]);
});
}
function previousSet() {
chrome.storage.sync.get('set', function(items) {
var currentSet = items.set;
//console.log("previous set", currentSet);
$('#setSelect').val(currentSet);
});
}
/// methods for persisting Quizlet options
// saves access token for API calls
function saveToken(token) {
chrome.storage.sync.set({'authToken': token}, function() {
// Notify that we saved.
});
}
// saves user ID of user
function saveUser(username) {
chrome.storage.sync.set({'username': username}, function() {
// Notify that we saved.
});
}
//saves the set
function saveSet(set) {
chrome.storage.sync.set({'set': set}, function() {
// Notify that we saved.
});
}