-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathinject.js
370 lines (308 loc) · 10.9 KB
/
inject.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
362
363
364
365
366
367
368
369
370
(function () {
var storage = chrome.storage.local,
notyRef,
port,
id = chrome.runtime.id,
x_error,
x_error_code,
$body = $('body'),
debug = false,
saveToPocket = '<div class="action_item"><span><a class="saveToPocket">Save to Pocket</a></span></div>',
notify = function (msg, type) {
if (notyRef) {
notyRef.close();
}
notyRef = noty({
text: msg,
type: type
});
},
appendLink = function (actionBar, link) {
// Better validation of node here.
if (!actionBar) {
console.debug("Cannot find action bar");
return;
}
if (actionBar.find('a.saveToPocket').length !== 0 ||
actionBar.find('a.savedToPocket').length !== 0) {
console.debug("Action bar has save to pocket button");
return false;
}
var el = $(saveToPocket),
saveToPocketLink = el.find('a').eq(0);
saveToPocketLink.attr('href', link);
actionBar.append(el);
},
reconnectExtension = function () {
console.debug("port reset");
port = false;
if (notyRef) {
notyRef.close();
}
// Won't connect no matter what.
//setTimeout(connectToExtension, 5000);
},
connectToExtension = function () {
port = chrome.runtime.connect(id);
port.onDisconnect.addListener(reconnectExtension);
},
initNoty = function () {
$.noty.defaults = {
layout: 'topRight',
theme: 'relax',
type: 'alert',
text: 'Sample Notification',
dismissQueue: false,
template: '<div class="noty_message"><span class="noty_text"></span><div class="noty_close"></div></div>',
animation: {
open: {
height: 'toggle'
},
close: {
height: 'toggle'
},
easing: 'swing',
speed: 250
},
timeout: false,
force: false,
modal: false,
maxVisible: 1,
killer: true,
closeWith: ['click'],
callback: {
onShow: function () {
},
afterShow: function () {
},
onClose: function () {
},
afterClose: function () {
}
},
buttons: false
};
},
//todo: consumer key needs to be in one place, refactor later
data = {
consumer_key: "34861-28c2d90660db385a7d94bd26",
redirect_uri: "chrome-extension://" + chrome.runtime.id
+ "/html/options.html?getAccessToken=1",
access_token: false,
username: false,
request_token: false
},
urls = {
"add": "https://getpocket.com/v3/add",
"remove": "https://getpocket.com/v3/send"
},
init = function () {
storage.get(null, function (o) {
data.access_token = o.access_token || false;
data.username = o.username || false;
data.request_token = o.request_token || false;
});
connectToExtension();
},
saveItem = function (url, target) {
storage.get('access_token', function (o) {
$.ajax({
url: urls.add,
type: 'POST',
dataType: 'json',
data: {
"access_token": o.access_token,
"consumer_key": data.consumer_key,
"url": url
},
headers: {
"X-Accept": "application/json"
}
})
.done(function (data, textStatus, req) {
//notify("Item saved successfully", "success");
target
.removeClass('saveToPocket')
.addClass('savedToPocket')
.text('Remove from Pocket')
.data('id', data.item.item_id);
})
.fail(function (req) {
handleError(req);
if (!x_error_code && !x_error) {
x_error = "";
x_error_code = "Something went wrong";
}
var baseUri = 'chrome-extension://' + chrome.runtime.id
+ '/html/options.html';
var text = x_error_code + ": " + x_error
+ "<br> Click <a target='_blank' href="
+ baseUri + ">here</a> to troubleshoot";
notify(text, "error");
target.text('Save to Pocket');
console.error("An error has occured while saving the answer");
});
});
},
removeItem = function (target) {
storage.get('access_token', function (o) {
$.ajax({
url: urls.remove,
type: 'POST',
dataType: 'json',
processData: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
"access_token": o.access_token,
"consumer_key": data.consumer_key,
"actions": [{
"action": "delete",
"item_id": target.data('id')
}]
}),
headers: {
"X-Accept": "application/json"
}
})
.done(function (data, textStatus, req) {
//notify("Item saved successfully", "success");
target
.removeClass('savedToPocket')
.addClass('saveToPocket')
.text('Save to Pocket')
.removeData('id');
})
.fail(function (req) {
handleError(req);
if (!x_error_code && !x_error) {
x_error = "";
x_error_code = "Something went wrong";
}
var baseUri = 'chrome-extension://' + chrome.runtime.id
+ '/html/options.html';
var text = x_error_code + ": " + x_error
+ "<br> Click <a target='_blank' href="
+ baseUri + ">here</a> to troubleshoot";
notify(text, "error");
target.text('Remove from Pocket');
console.error("An error has occured while saving the answer");
});
});
},
handleError = function (req) {
var headers = req.getAllResponseHeaders().split('\n');
headers.forEach(function (item) {
if (item.indexOf('X-Error-Code') >= 0) {
x_error_code = item.split(":")[1];
console.error('error message :' + x_error_code);
storage.set({
'x_error_code': x_error_code
});
} else if (item.indexOf('X-Error') >= 0) {
x_error = item.split(":")[1];
console.error('error message :' + x_error);
storage.set({
'x_error': x_error
});
}
});
},
insertSaveToPocketForItem = function (element) {
// Given an element, try to find either of the following elements
// Answer, Question, Blog Item
var results = element.find(
"a.answer_permalink, a.question_link, a.timestamp");
// Check in the order of answer, question and then blog item
if (results.length !== 0) {
var url;
var permalink_results = element.find("a.answer_permalink");
var question_link_results = element.find("a.question_link");
var timestamp_results = element.find("a.timestamp");
if (permalink_results.length > 0) {
url = permalink_results.attr('href');
} else if (question_link_results.length > 0) {
url = question_link_results.attr('href');
} else if (timestamp_results.length > 0) {
url = timestamp_results.attr('href');
}
if (url) {
appendLink(element.find("div.ActionBar div.action_bar_inner"), url);
}
} else {
console.debug("Cannot find link for item", element);
}
},
getItemsToAppendLinkTo = function (element) {
// In case a new node is inserted, try to find the following elements
// inside the inserted node
var items = element.find("div.feed_item, div.pagedlist_item");
if (items.length === 0) {
// check if element itself is a pagedlist or feed item
// this happens in case of questions page
var classes = element.attr("class");
var classList = classes && classes.split(/\s+/) || [];
if (classList.indexOf("feed_item") >= 0 || classList.indexOf(
"pagedlist_item") >= 0) {
return element;
} else {
return undefined;
}
}
return items;
},
bindNodeInsertedHandler = function () {
var documentSelector = $(document);
documentSelector.bind('DOMNodeInserted', function (e) {
var element = $(e.target);
var items = getItemsToAppendLinkTo(element);
console.debug("Processing new item", element);
items && items.each(function (i, node) {
insertSaveToPocketForItem($(node));
});
});
},
readyStateCheckInterval = setInterval(function () {
if (document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
init();
initNoty();
console.debug("A hello from Quora Save to Pocket Extension");
bindNodeInsertedHandler();
// Required for processing items that arrive when the page
// is initially loaded
$("div.feed_item, div.pagedlist_item").each(function (i, node) {
console.debug("inserting link for first set of items");
insertSaveToPocketForItem($(node));
});
$body.on('click', 'a.saveToPocket', function (ev) {
// If extension is disconnected, do not perform any task.
if (!port) {
return;
}
ev.preventDefault();
var url = ev.target.href,
link = $(ev.target);
if (url) {
link.text('Saving...');
//notify("Saving Item...", "info");
saveItem(url, link);
}
});
$body.on('click', 'a.savedToPocket', function (ev) {
// If extension is disconnected, do not perform any task.
if (!port) {
return;
}
ev.preventDefault();
var link = $(ev.target);
link.text('Removing...');
removeItem(link);
});
}
}, 10);
if (!debug) {
console.debug = function () {
};
}
})
();