/
main.js
411 lines (394 loc) · 13.1 KB
/
main.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/* jshint esnext: true */
/* global require: false */
// Import the APIs we need.
let pageMod = require("sdk/page-mod");
let Request = require("sdk/request").Request;
let self = require("sdk/self");
let tabs = require("sdk/tabs");
//let ss = require("simple-storage"); // Temporarily disabled
let timer = require("sdk/timers");
let priv = require("sdk/private-browsing");
let windows = require("sdk/windows").browserWindows;
// require chrome allows us to use XPCOM objects...
const {Cc,Ci,Cu,components} = require("chrome");
let historyService = Cc["@mozilla.org/browser/history;1"].getService(Ci.mozIAsyncHistory);
// Temporary workaround for ss being broken (https://github.com/honestbleeps/Reddit-Enhancement-Suite/issues/797)
let localStorage = {};
let file = require("sdk/io/file")
let ss = (function() {
var timeout = null;
var filename = (function() {
let storeFile = Cc["@mozilla.org/file/directory_service;1"].
getService(Ci.nsIProperties).
get("ProfD", Ci.nsIFile);
storeFile.append("jetpack");
storeFile.append(self.id);
storeFile.append("simple-storage");
file.mkpath(storeFile.path);
storeFile.append("store.json");
return storeFile.path;
})();
var really_save = function() {
let stream = file.open(filename, "w");
try {
stream.writeAsync(JSON.stringify(localStorage), function writeAsync(err) {
if (err)
console.error("Error writing simple storage file: " + filename);
}.bind(this));
}
catch (err) {
// writeAsync closes the stream after it's done, so only close on error.
stream.close();
}
};
this.save = function() {
if (timeout !== null) {
timer.clearTimeout(timeout);
}
timeout = timer.setTimeout(really_save, 3000);
};
let str = "";
try {
str = file.read(filename);
} catch (e) {
console.warn("Error loading simple storage file: " + e);
}
localStorage = str ? JSON.parse(str) : {};
return this;
})();
// End temporary workaround
// Cookie manager for new API login
let cookieManager = Cc["@mozilla.org/cookiemanager;1"].getService().QueryInterface(Ci.nsICookieManager2);
components.utils.import("resource://gre/modules/NetUtil.jsm");
// Preferences
let prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
// this function takes in a string (and optional charset, paseURI) and creates an nsURI object, which is required by historyService.addURI...
function makeURI(aURL, aOriginCharset, aBaseURI) {
let ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
return ioService.newURI(aURL, aOriginCharset, aBaseURI);
}
let workers = [];
function detachWorker(worker, workerArray) {
let index = workerArray.indexOf(worker);
if (index !== -1) {
workerArray.splice(index, 1);
}
}
localStorage.getItem = function(key) {
return localStorage[key];
};
localStorage.setItem = function(key, value) {
localStorage[key] = value;
ss.save();
};
localStorage.removeItem = function(key) {
delete localStorage[key];
ss.save();
};
let XHRCache = {
forceCache: false,
capacity: 250,
entries: {},
count: 0,
check: function(key) {
if (key in this.entries) {
// console.log("hit");
this.entries[key].hits++;
return this.entries[key].data;
} else {
// console.log("miss");
return null;
}
},
add: function(key, value) {
if (key in this.entries) {
return;
} else {
// console.log("add");
this.entries[key] = {data: value, timestamp: Date.now(), hits: 1};
this.count++;
}
if (this.count > this.capacity) {
this.prune();
}
},
prune: function() {
let now = Date.now();
let bottom = [];
for (let key in this.entries) {
// if (this.entries[key].hits === 1) {
// delete this.entries[key];
// this.count--;
// continue;
// }
//Weight by hits/age which is similar to reddit's hit/controversial sort orders
bottom.push({
key: key,
weight: this.entries[key].hits/(now - this.entries[key].timestamp)
});
}
bottom.sort(function(a,b){return a.weight-b.weight;});
let count = this.count - Math.floor(this.capacity / 2);
for (let i = 0; i < count; i++) {
delete this.entries[bottom[i].key];
this.count--;
}
// console.log("prune");
},
clear: function() {
this.entries = {};
this.count = 0;
}
};
tabs.on('activate', function(tab) {
// find this worker...
for (let i in workers) {
if ((typeof workers[i].tab !== 'undefined') && (tab.title === workers[i].tab.title)) {
workers[i].postMessage({ name: "getLocalStorage", message: localStorage });
}
}
});
pageMod.PageMod({
include: ["*.reddit.com"],
contentScriptWhen: 'start',
contentScriptFile: [
self.data.url('jquery-1.10.2.min.js'),
self.data.url('guiders-1.2.8.js'),
self.data.url('jquery.dragsort-0.6.js'),
self.data.url('jquery-fieldselection.min.js'),
self.data.url('tinycon.js'),
self.data.url('jquery.tokeninput.js'),
self.data.url('HTMLPasteurizer.js'),
self.data.url('snuownd.js'),
self.data.url('utils.js'),
self.data.url('browsersupport.js'),
self.data.url('console.js'),
self.data.url('alert.js'),
self.data.url('storage.js'),
self.data.url('template.js'),
self.data.url('konami.js'),
self.data.url('mediacrush.js'),
self.data.url('gfycat.js'),
self.data.url('hogan-2.0.0.js'),
self.data.url('reddit_enhancement_suite.user.js'),
self.data.url('modules/betteReddit.js'),
self.data.url('modules/userTagger.js'),
self.data.url('modules/keyboardNav.js'),
self.data.url('modules/commandLine.js'),
self.data.url('modules/about.js'),
self.data.url('modules/hover.js'),
self.data.url('modules/subredditTagger.js'),
self.data.url('modules/uppersAndDowners.js'),
self.data.url('modules/singleClick.js'),
self.data.url('modules/commentPreview.js'),
self.data.url('modules/commentTools.js'),
self.data.url('modules/sortCommentsTemporarily.js'),
self.data.url('modules/usernameHider.js'),
self.data.url('modules/showImages.js'),
self.data.url('modules/showKarma.js'),
self.data.url('modules/hideChildComments.js'),
self.data.url('modules/showParent.js'),
self.data.url('modules/neverEndingReddit.js'),
self.data.url('modules/saveComments.js'),
self.data.url('modules/userHighlight.js'),
self.data.url('modules/styleTweaks.js'),
self.data.url('modules/accountSwitcher.js'),
self.data.url('modules/filteReddit.js'),
self.data.url('modules/newCommentCount.js'),
self.data.url('modules/spamButton.js'),
self.data.url('modules/commentNavigator.js'),
self.data.url('modules/subredditManager.js'),
self.data.url('modules/RESTips.js'),
self.data.url('modules/settingsNavigation.js'),
self.data.url('modules/dashboard.js'),
self.data.url('modules/notifications.js'),
self.data.url('modules/subredditInfo.js'),
self.data.url('modules/commentHidePersistor.js'),
self.data.url('modules/bitcointip.js'),
self.data.url('modules/troubleshooter.js'),
self.data.url('init.js')
],
contentStyleFile: [
self.data.url('nightmode.css'),
self.data.url('commentBoxes.css'),
self.data.url('res.css'),
self.data.url('players.css'),
self.data.url('guiders.css'),
self.data.url('tokenize.css'),
self.data.url("batch.css")
],
onAttach: function(worker) {
// when a tab is activated, repopulate localStorage so that changes propagate across tabs...
workers.push(worker);
worker.on('detach', function () {
detachWorker(this, workers);
});
worker.on('message', function(data) {
let request = data,
inBackground = prefs.getBoolPref('browser.tabs.loadInBackground') || true,
isPrivate, thisLinkURL;
switch (request.requestType) {
case 'readResource':
let fileData = self.data.load(request.filename);
worker.postMessage({ name: 'readResource', data: fileData, transaction: request.transaction });
break;
case 'deleteCookie':
cookieManager.remove('.reddit.com', request.cname, '/', false);
break;
case 'GM_xmlhttpRequest':
let responseObj = {
XHRID: request.XHRID,
name: request.requestType
};
if (request.aggressiveCache || XHRCache.forceCache) {
let cachedResult = XHRCache.check(request.url);
if (cachedResult) {
responseObj.response = cachedResult;
worker.postMessage(responseObj);
return;
}
}
if (request.method === 'POST') {
Request({
url: request.url,
onComplete: function(response) {
responseObj.response = {
responseText: response.text,
status: response.status
};
//Only cache on HTTP OK and non empty body
if ((request.aggressiveCache || XHRCache.forceCache) && (response.status === 200 && response.text)) {
XHRCache.add(request.url, responseObj.response);
}
worker.postMessage(responseObj);
},
headers: request.headers,
content: request.data
}).post();
} else {
Request({
url: request.url,
onComplete: function(response) {
responseObj.response = {
responseText: response.text,
status: response.status
};
if ((request.aggressiveCache || XHRCache.forceCache) && (response.status === 200 && response.text)) {
XHRCache.add(request.url, responseObj.response);
}
worker.postMessage(responseObj);
},
headers: request.headers,
content: request.data
}).get();
}
break;
case 'singleClick':
inBackground = ((request.button === 1) || (request.ctrl === 1));
isPrivate = priv.isPrivate(windows.activeWindow);
// handle requests from singleClick module
if (request.openOrder === 'commentsfirst') {
// only open a second tab if the link is different...
if (request.linkURL !== request.commentsURL) {
tabs.open({url: request.commentsURL, inBackground: inBackground, isPrivate: isPrivate });
}
tabs.open({url: request.linkURL, inBackground: inBackground, isPrivate: isPrivate });
} else {
tabs.open({url: request.linkURL, inBackground: inBackground, isPrivate: isPrivate });
// only open a second tab if the link is different...
if (request.linkURL !== request.commentsURL) {
tabs.open({url: request.commentsURL, inBackground: inBackground, isPrivate: isPrivate });
}
}
worker.postMessage({status: "success"});
break;
case 'keyboardNav':
isPrivate = priv.isPrivate(windows.activeWindow);
// handle requests from keyboardNav module
thisLinkURL = request.linkURL;
if (thisLinkURL.toLowerCase().substring(0, 4) !== 'http') {
thisLinkURL = (thisLinkURL.substring(0, 1) === '/') ? 'http://www.reddit.com' + thisLinkURL : location.href + thisLinkURL;
}
// Get the selected tab so we can get the index of it. This allows us to open our new tab as the "next" tab.
tabs.open({url: thisLinkURL, inBackground: inBackground, isPrivate: isPrivate });
worker.postMessage({status: "success"});
break;
case 'openLinkInNewTab':
inBackground = (request.focus !== true);
isPrivate = priv.isPrivate(windows.activeWindow);
thisLinkURL = request.linkURL;
if (thisLinkURL.toLowerCase().substring(0, 4) !== 'http') {
thisLinkURL = (thisLinkURL.substring(0, 1) === '/') ? 'http://www.reddit.com' + thisLinkURL : location.href + thisLinkURL;
}
// Get the selected tab so we can get the index of it. This allows us to open our new tab as the "next" tab.
tabs.open({url: thisLinkURL, inBackground: inBackground, isPrivate: isPrivate });
worker.postMessage({status: "success"});
break;
case 'loadTweet':
Request({
url: request.url,
onComplete: function(response) {
let resp = JSON.parse(response.text);
let responseObj = {
name: 'loadTweet',
response: resp
};
worker.postMessage(responseObj);
},
headers: request.headers,
content: request.data
}).get();
break;
case 'getLocalStorage':
worker.postMessage({ name: 'getLocalStorage', message: localStorage });
break;
case 'saveLocalStorage':
for (let key in request.data) {
localStorage.setItem(key,request.data[key]);
}
localStorage.setItem('importedFromForeground', true);
worker.postMessage({ name: 'saveLocalStorage', message: localStorage });
break;
case 'localStorage':
switch (request.operation) {
case 'getItem':
worker.postMessage({status: true, value: localStorage.getItem(request.itemName)});
break;
case 'removeItem':
localStorage.removeItem(request.itemName);
// worker.postMessage({status: true, value: null});
break;
case 'setItem':
localStorage.setItem(request.itemName, request.itemValue);
break;
}
break;
case 'XHRCache':
switch (request.operation) {
case 'clear':
XHRCache.clear();
break;
}
break;
case 'addURLToHistory':
isPrivate = priv.isPrivate(windows.activeWindow);
if (isPrivate) {
// do not add to history if in private browsing mode!
return false;
}
let uri = makeURI(request.url);
historyService.updatePlaces({
uri: uri,
visits: [{
transitionType: Ci.nsINavHistoryService.TRANSITION_LINK,
visitDate: Date.now() * 1000
}]
});
break;
default:
worker.postMessage({status: "unrecognized request type"});
break;
}
});
}
});