forked from OverlordQ/Reddit-Pro-Tools
-
Notifications
You must be signed in to change notification settings - Fork 2
/
users.js
682 lines (543 loc) · 23 KB
/
users.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
"use strict";
// get a list of users on the page
function getAuthors() {
let authors = [];
let userElems = document.evaluate(
'//a[' + userElemEval + ']',
document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
let i = 0;
while (userElems.snapshotItem(i)) {
let author = userElems.snapshotItem(i).textContent.replace(/^u\//, '');
// if not already in our list of authors
if (author &&
author != '' &&
authors.indexOf(author) < 0 &&
author != '[deleted]' &&
author != 'AutoModerator' &&
author != 'PoliticsModeratorBot' &&
author != 'LegalAdviceModerator' &&
author != 'court-reporter' &&
author != 'Invite to chat') {
authors.push(author);
}
i++;
}
return authors;
}
function SubStats() {
let empty = function() {
this.average = null;
this.total = 0
this.length = 0;
};
this.link = new empty();
this.comment = new empty();
}
function User(username, init = true) {
printLog('User():', username);
this.name = username;
this.about = {
updated: null
};
this.comments = null;
this.working = false;
this.hasTag = false;
this.tags = {};
this.stats = {
links: {
updated: null,
average: null,
total: 0
},
comments: {
updated: null,
average: null,
total: 0
},
subreddits: {}
};
this.getComments = function() {
// wait for the user to load from the db
if (this.stats.comments.updated == null) {
// console.log('getComments() waiting on user from db:', this.name);
setTimeout(() => {
this.getComments();
}, 100);
return;
}
printLog('\tgetComments:', this.name);
// console.log(this.comments);
if (!this.comments || !this.comments[0] || !this.comments[0].name) {
this.comments = [];
this.getCommentsJson('after');
} else if (!this.stats.comments.updated || (datenow() - this.stats.comments.updated) > cacheTime) {
this.getCommentsJson('before', this.comments[0]);
} else {
this.evalComments();
}
}
this.getCommentsJson = async function(type = 'after', id = null) {
let domain = window.location.hostname;
let url = 'https://' + domain + '/user/' + this.name + '/comments.json?sort=new&limit=100';
if (id) {
url += '&' + type + '=' + id;
}
let results = await chrome.runtime.sendMessage({
contentScriptQuery: "queryComment",
url: url,
type: type,
user: this
});
console.log('\t\t\tqueryComment(' + this.name + ')');
let json = results.json
json.data.before = (json.data.children[0]) ? json.data.children[0].data.name : null;
this.saveComments(results.type, results.json);
if (json.data[results.type]) {
this.getCommentsJson(results.type, json.data[type]);
} else {
this.evalComments();
}
return true;
}
this.saveComments = function(type, json) {
console.log('\t\t\tsaveComments(' + type + ')');
let saved = [];
json.data.children.forEach((comment) => {
let save = {
// parent_id: comment.data.parent_id,
// permalink: comment.data.permalink,
// body: comment.data.body,
// ups: comment.data.ups,
name: comment.data.name,
created: comment.data.created_utc,
subreddit: comment.data.subreddit,
controversiality: comment.data.controversiality,
score: comment.data.score,
};
saved.push(save);
});
if (type == 'after') {
if (this.comments === null) {
this.comments = [];
}
this.comments = this.comments.concat(saved);
} else {
this.comments = saved.concat(this.comments);
}
}
this.evalComments = function() {
printLog('\t\tevalComments():', this.name);
// keep up to 1000 comments, discard old ones over 1000
if (this.comments.length >= 1000) {
this.comments.splice(1000, this.comments.length - 1);
}
this.stats.comments.total = 0;
this.comments.forEach((comment) => {
if (comment !== null) {
this.stats.comments.total += comment.score;
}
});
let scoreAvg = Math.round(this.stats.comments.total / this.comments.length * 100) / 100;
this.stats.comments.average = scoreAvg;
this.stats.subreddits = {};
this.comments.forEach((comment) => {
if (comment !== null) {
if (!this.stats.subreddits[comment.subreddit]) {
this.stats.subreddits[comment.subreddit] = new SubStats;
}
let sub = this.stats.subreddits[comment.subreddit];
sub.comment.total += comment.score;
sub.comment.length++;
sub.comment.average = Math.round(sub.comment.total / sub.comment.length * 100) / 100;
}
});
this.stats.comments.updated = datenow();
this.evalTags();
}
this.evalTags = function() {
printLog('\t\t\tevalTags():', this.name);
// wait for the user info to be updated
if (this.about.created == null) {
// console.log('evalTags() waiting on user about:', this.name);
setTimeout(() => {
this.evalTags();
}, 100);
return;
}
let statsTableLength = 10;
for (let type in settings.tags) {
this.tags[type] = {}
for (let tag in settings.tags[type]) {
if (!settings.tags[type][tag].enabled) {
continue;
}
if (type == 'accountage') {
let age = Math.round((datenow() - this.about.created) / day);
if ((settings.tags[type][tag].gtlt == 'greater' && age > settings.tags[type][tag].age) ||
(settings.tags[type][tag].gtlt != 'greater' && age < settings.tags[type][tag].age)) {
this.tags[type][tag] = true;
this.hasTag = true;
}
} else if (type == 'subreddits') {
settings.tags[type][tag].list.forEach((sub) => {
if (!sub || !this.stats.subreddits[sub]) {
return;
}
if (settings.tags[type][tag].avgtotal == 'average' && this.stats.subreddits[sub].comment.length < 10) {
return;
}
let comparator = (settings.tags[type][tag].avgtotal == 'total') ? this.stats.subreddits[sub].comment.total : this.stats.subreddits[sub].comment.average;
if ((settings.tags[type][tag].gtlt == 'greater' && comparator > settings.tags[type][tag].karma) ||
(settings.tags[type][tag].gtlt != 'greater' && comparator < settings.tags[type][tag].karma)) {
let subs = this.subSort(type, tag, settings.tags[type][tag].list);
subs.splice(statsTableLength);
this.tags[type][tag] = subs;
this.hasTag = true;
return;
}
});
} else if (type == 'subkarma') {
let url = window.location.href.split('/');
let urlSubs = (url[3] == 'r') ? url[4].split('+') : [];
let subs = [];
urlSubs.forEach((sub) => {
if (!sub || !this.stats.subreddits[sub]) {
return;
}
if (settings.tags[type][tag].avgtotal == 'average' && this.stats.subreddits[sub].comment.length < 10) {
return;
}
let comparator = (settings.tags[type][tag].avgtotal == 'total') ? this.stats.subreddits[sub].comment.total : this.stats.subreddits[sub].comment.average;
if ((settings.tags[type][tag].gtlt == 'greater' && comparator > settings.tags[type][tag].karma) ||
(settings.tags[type][tag].gtlt != 'greater' && comparator < settings.tags[type][tag].karma)) {
subs.push(sub);
}
});
if (subs.length) {
subs = this.subSort(type, tag, subs);
subs.splice(statsTableLength);
this.tags[type][tag] = subs;
this.hasTag = true;
}
} else if (type == 'karma') {
let comparator = (settings.tags[type][tag].avgtotal == 'total') ? this.stats.comments.total : this.stats.comments.average;
if ((settings.tags[type][tag].gtlt == 'greater' && comparator > settings.tags[type][tag].karma) ||
(settings.tags[type][tag].gtlt != 'greater' && comparator < settings.tags[type][tag].karma)) {
let subs = this.subSort(type, tag, Object.keys(this.stats.subreddits));
subs.splice(statsTableLength);
this.tags[type][tag] = subs;
this.hasTag = true;
}
}
}
}
this.saveDb();
}
this.subSort = function(type, tag, subs) {
let sortBy = [];
// for (let sub in subs) {
subs.forEach((sub) => {
if (!(sub in this.stats.subreddits)) {
return;
}
sortBy[sub] = (settings.tags[type][tag].avgtotal == 'total') ? this.stats.subreddits[sub].comment.total : this.stats.subreddits[sub].comment.average;
});
subs = Object.keys(sortBy).sort(function(a, b) {
return sortBy[b] - sortBy[a];
});
if (settings.tags[type][tag].gtlt != 'greater') {
subs = subs.reverse();
}
return subs;
}
this.addTags = function() {
// wait on tags to be generated
if (!Object.keys(this.tags).length) {
setTimeout(() => {
this.addTags();
}, 100);
return;
}
if (!this.hasTag) {
return;
}
printLog('\t\t\t\taddTags():', this.name);
let userElems = this.getUserElemements();
// console.log(userElems);
userElems.forEach((userElem) => {
let wrapper = this.tagWrapper();
for (let type in this.tags) {
for (let tag in this.tags[type]) {
let tagSpan = this.tagSpan(type, tag);
wrapper.appendChild(tagSpan);
}
}
setTimeout(function() {
userElem.before(wrapper);
}, Math.random() * 500);
});
this.working = false;
}
this.getUserElemements = function() {
let userLinks = [];
let userElems = document.evaluate(
'//a[' + userElemEval + ' and (text()="u/' + this.name + '" or text()="' + this.name + '")]',
document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
let i = 0;
while (userElems.snapshotItem(i)) {
let userElem = userElems.snapshotItem(i);
// if it doesn't already have a tag...
if (!userElem.previousSibling ||
!userElem.previousSibling.tagName ||
(userElem.previousSibling.tagName != 'SPAN' || !userElem.previousSibling.className.split(' ').includes('rptTagWrapper'))) {
userLinks.push(userElem);
}
i++;
}
return userLinks.reverse();
}
this.tagWrapper = function() {
let span = document.createElement('span');
span.className = 'rptTagWrapper rptUser-' + this.name;
return span;
}
this.tagSpan = function(type, tag) {
let span = document.createElement('span');
span.textContent = tag;
// span.className = 'rptTag rptUser-' + this.name;
span.className = 'rptTag';
span.style.backgroundColor = '#' + settings.tags[type][tag].color;
span.style.color = '#' + settings.tags[type][tag].tcolor;
let displayTag = span.cloneNode(true);
span.addEventListener('mouseenter', (e) => {
let hoverDiv = document.createElement('div');
hoverDiv.className = 'rptTagInfo';
let zIndex = 1000000;
if (span.parentElement.className.split(' ').includes('fieldPair-text')) {
zIndex = window.getComputedStyle(span.parentElement.parentElement.parentElement.parentElement.parentElement).getPropertyValue('z-index') + 10;
}
hoverDiv.style.zIndex = zIndex;
hoverDiv.addEventListener('mouseleave', (e) => {
hoverDiv.parentNode.removeChild(hoverDiv);
});
let header = document.createElement('div');
header.className = 'rptTagInfoHeader textCenter';
let rpt = document.createElement('div');
rpt.style.color = '#ff0000';
rpt.style.fontSize = '130%';
rpt.style.marginBottom = '5px';
rpt.textContent = 'Reddit Pro Tools';
rpt.className = 'textCenter bold';
let userLink = document.createElement('a');
userLink.href = '/u/' + this.name;
userLink.textContent = '/u/' + this.name;
let colon = document.createElement('span');
colon.textContent = ': ';
header.appendChild(userLink);
header.appendChild(colon);
header.appendChild(displayTag);
let tagDesc = document.createElement('div');
tagDesc.className = 'rptTagInfoDesc textCenter bold';
let body = document.createElement('div');
body.className = 'rptTagInfoBody textCenter';
if (type == 'accountage') {
let year = 365.25;
let age = Math.round((datenow() - this.about.created) / day);
let years = Math.floor(age / year);
let months = Math.floor(age % year / year * 12);
let days = Math.floor(age - years * year - months * year / 12);
let ageText = (years) ? years + ' years,' : '';
ageText += (months) ? ' ' + months + ' months,' : ''
ageText += (days) ? ' ' + days + ' days' : '< 1 day';
tagDesc.textContent = 'Account age ' + settings.tags[type][tag].gtlt + ' than ' + numPretty(settings.tags[type][tag].age) + ' days';
body.textContent = 'Account age: ' + ageText;
} else if (type == 'subreddits') {
let subLimit = 4;
let subsText = '';
for (let i in settings.tags[type][tag].list) {
if (i > subLimit - 1) {
continue;
}
if (i != 0) {
subsText += ', ';
}
subsText += settings.tags[type][tag].list[i];
}
if (settings.tags[type][tag].list.length > subLimit) {
subsText += ', ...';
}
tagDesc.textContent = 'Comment karma ' + settings.tags[type][tag].gtlt + ' than ' + numPretty(settings.tags[type][tag].karma) + ' in:';
let subsDiv = document.createElement('div');
subsDiv.style.fontWeight = 'normal';
subsDiv.textContent = '(' + subsText + ')';
tagDesc.append(subsDiv);
body.append(this.statsTable(this.tags[type][tag]));
} else if (type == 'subkarma') {
tagDesc.textContent = 'Comment karma ' + settings.tags[type][tag].gtlt + ' than ' + numPretty(settings.tags[type][tag].karma) + ' in current subreddit';
body.append(this.statsTable(this.tags[type][tag]));
} else if (type == 'karma') {
tagDesc.textContent = 'Total comment karma ' + settings.tags[type][tag].gtlt + ' than ' + numPretty(settings.tags[type][tag].karma);
body.append(this.statsTable(this.tags[type][tag]));
} else if (type == 'rptStats') {
if (tag == 'RPT+') {
tagDesc.textContent = 'Subreddits by positive comment karma';
let subs = this.subSort(type, tag, Object.keys(this.stats.subreddits));
subs.splice(10);
body.append(this.statsTable(subs));
} else if (tag == 'RPT-') {
tagDesc.textContent = 'Subreddits by negative comment karma';
let subs = this.subSort(type, tag, Object.keys(this.stats.subreddits));
subs.splice(10);
body.append(this.statsTable(subs));
}
}
hoverDiv.appendChild(rpt);
hoverDiv.appendChild(header);
hoverDiv.appendChild(tagDesc);
hoverDiv.appendChild(body);
document.body.appendChild(hoverDiv);
this.positionRptTagInfo(hoverDiv, e.pageX, e.pageY);
});
return span;
}
this.positionRptTagInfo = function(div, pageX, pageY) {
div.style.left = (pageX - 50) + 'px';
div.style.top = (pageY - 20) + 'px';
let pos = $(div)[0].getBoundingClientRect();
if (0 > pos.left) {
div.css('left', '0px');
}
if (0 > pos.top) {
div.style.top = document.documentElement.scrollTop + 'px';
}
if (pos.right > window.innerWidth) {
div.style.left = (document.documentElement.scrollLeft + window.innerWidth - pos.width - 20) + 'px';
}
if (pos.bottom > window.innerHeight) {
div.style.top = (document.documentElement.scrollTop + window.innerHeight - pos.height) + 'px';
}
}
this.statsTable = function(subs) {
let table = document.createElement('table');
table.style.width = '100%';
let tr = document.createElement('tr');
let td = document.createElement('td');
td.style.paddingLeft = '5px';
td.style.paddingRight = '5px';
let thSubreddit = td.cloneNode();
thSubreddit.className = 'rptBorder';
thSubreddit.style.borderWidth = '0px 1px 1px 0px';
thSubreddit.textContent = 'Subreddit';
let thTotal = td.cloneNode();
thTotal.className = 'rptBorder';
thTotal.style.borderWidth = '0px 1px 1px 0px';
thTotal.textContent = 'Total Karma';
let thAverage = td.cloneNode();
thAverage.className = 'rptBorder';
thAverage.style.borderWidth = '0px 1px 1px 0px';
thAverage.textContent = 'Average Karma';
let thComments = td.cloneNode();
thComments.className = 'rptBorder';
thComments.style.borderWidth = '0px 0px 1px 0px';
thComments.textContent = 'Comments';
let th = tr.cloneNode();
th.appendChild(thSubreddit);
th.appendChild(thTotal);
th.appendChild(thAverage);
th.appendChild(thComments);
table.appendChild(th);
subs.forEach((sub) => {
let trStats = tr.cloneNode();
let tdSubreddit = td.cloneNode();
tdSubreddit.textContent = sub;
let tdTotal = td.cloneNode();
tdTotal.textContent = numPretty(this.stats.subreddits[sub].comment.total);
let tdAverage = td.cloneNode();
tdAverage.textContent = numPretty(this.stats.subreddits[sub].comment.average);
let tdComments = td.cloneNode();
tdComments.textContent = numPretty(this.stats.subreddits[sub].comment.length);
trStats.appendChild(tdSubreddit);
trStats.appendChild(tdTotal);
trStats.appendChild(tdAverage);
trStats.appendChild(tdComments);
table.appendChild(trStats);
});
return table;
}
this.getAbout = async function() {
// wait for the db to load the user
if (this.about.updated == null) {
// console.log('waiting on user from db:', this.name);
setTimeout(() => {
this.getAbout();
}, 100);
return;
}
console.log('\taboutGet():\t\t', this.name);
// if we didn't have about data saved or if the about data is outdated...
if (this.about.link_karma == undefined || datenow() - this.about.updated > cacheTime) {
let domain = window.location.hostname;
let url = 'https://' + domain + '/user/' + this.name + '/about.json';
let results = await chrome.runtime.sendMessage({
contentScriptQuery: "queryAbout",
user: this
});
this.saveAbout(results.json);
}
};
this.saveAbout = function(json) {
console.log('\t\taboutSave():\t\t', this.name);
this.about.link_karma = json.data.link_karma;
this.about.comment_karma = json.data.comment_karma;
this.about.created = json.data.created;
this.about.updated = datenow();
};
this.getDb = function() {
console.log('\tgetDb():', this.name);
let transaction = db.transaction([table]);
// transaction errors
transaction.onerror = function(e) {
console.log('user.dbGet transaction error:');
console.log(e);
};
let os = transaction.objectStore(table);
let req = os.get(this.name);
// request errors
req.onerror = function(e) {
console.log('user.dbGet error: ' + table + '!');
};
req.onsuccess = () => {
if (req.result && req.result.about.updated !== null) {
this.about = req.result.about;
this.stats = req.result.stats;
this.comments = req.result.comments;
} else {
this.about.updated = 0;
this.stats.comments.updated = 0;
}
};
}
this.saveDb = function() {
// console.log('\tsaveDb():', this.name);
var os = db.transaction([table], "readwrite").objectStore(table);
var save = {
name: this.name,
about: this.about,
comments: this.comments,
stats: this.stats
};
var req = os.put(save);
req.onerror = function(event) {
console.log('user.dbSave error: ' + table + ' - ' + this.name + '!');
};
}
this.getDb();
this.getAbout();
this.getComments();
}
function round(num) {
return Math.round(num * 100) / 100;
}
function datenow() {
return Math.round(Date.now() / 1000);
}