-
Notifications
You must be signed in to change notification settings - Fork 1
/
Powder_Toy_enhancements.user.js
2810 lines (2648 loc) · 110 KB
/
Powder_Toy_enhancements.user.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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name Powder Toy enhancements
// @namespace http://powdertoythings.co.uk/tptenhance
// @description Fix and improve some things (mainly moderation tools) on powdertoy.co.uk
// @include http*://powdertoy.co.uk/*
// @version 2.46
// @author jacksonmj
// @license GPL-3.0-or-later; http://www.gnu.org/copyleft/gpl.html
// @grant none
// @downloadURL https://openuserjs.org/install/jacksonmj/Powder_Toy_enhancements.user.js
// ==/UserScript==
/* jshint forin:true, freeze:true, latedef:true, multistr:true, shadow:inner, undef:true, unused:true */
/* global tptenhance, d3, moment */
/* jshint jquery:true, browser:true */
/* global alert, confirm */
/* global currentSaveID:false */ // defined by powdertoy.co.uk in Browse/View.html
/* global ProcessMessages, LoadForumBlocks, WYSIWYG */ // powdertoy.co.uk functions which are overridden by this script
// contentEval, from http://userscripts.org/scripts/source/100842.user.js :
function contentEval(source) {
if (document.body.id==="tinymce")
return;
if ('function' == typeof source) {
source = '(' + source + ')();';
}
var script = document.createElement('script');
script.setAttribute("type", "application/javascript");
script.textContent = source;
document.body.appendChild(script);
document.body.removeChild(script);
}
function addScript(url) {
if (document.body.id==="tinymce")
return;
var script = document.createElement('script');
script.setAttribute("type", "application/javascript");
script.setAttribute("src", url);
document.body.appendChild(script);
}
addScript("//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js");
contentEval(function(){
var tptenhance_init = function(){
if (typeof $ == "undefined" || typeof moment == "undefined") // check jQuery and other libraries have loaded
{
setTimeout(tptenhance_init, 20);
return;
}
window.tptenhance = {
// used by several functions to replace clicked "Delete" links to show that a request is in progress / finished
deletingHtml:'<div class="pull-right label label-info"><i class="icon-refresh icon-white"></i> <strong>Deleting...</strong></div>',
deletedHtml:'<div class="pull-right label label-success"><i class="icon-ok icon-white"></i> <strong>Deleted</strong></div>',
doneLabelHtml:'<div class="label label-success"><i class="icon-ok icon-white"></i> <strong>Done</strong></div>',
// a random page to use for redirects, which will hopefully load faster than the default redirect (e.g. to a user moderation page) in ajax requests
dummyUrl:"/Themes/Next/Javascript/Browse.View.js",
// Return session key (the thing used as CSRF protection) - cached in tptenhance.sessionKey
getSessionKey:function()
{
if (tptenhance.sessionKey!=="")
return tptenhance.sessionKey;
$('.main-menu').find('a').each(function(){
var url = this.href;
var matches = url.match(/Logout.html\?Key=[A-Za-z0-9]+/);
if (matches)
{
// Logout link found, extract key
tptenhance.sessionKey = matches[0].split("=")[1];
}
});
return tptenhance.sessionKey;
},
sessionKey:"",
// Get the username to which the page refers
// E.g. for moderation page, username of person being moderated.
getPageUsername:function()
{
if (window.location.pathname.toString().indexOf("/User/Moderation.html")!==-1 ||
window.location.toString().indexOf("/User.html")!=-1 ||
window.location.toString().indexOf("/User/Saves.html")!=-1)
return $('.SubmenuTitle').text();
if (window.location.pathname.toString().indexOf("/Browse.html")!==-1)
{
var matches = window.location.search.toString().match(/[?&]Search_Query=[^&]*user(?::|%3A)(((?!(%20))[^ +&])+)/);
if (matches)
return matches[1];
}
return null;
},
// Get the username of the currently logged in user
getAuthedUser:function()
{
var el = $(".main-menu .pull-right .dropdown:nth-child(2) a.dropdown-toggle");
if (el.length)
return el.contents().get(0).nodeValue.trim();
return null;
},
// Returns bool indicating whether the user is logged in as a moderator
isMod:function()
{
if (typeof tptenhance.isModCache!="undefined")
return tptenhance.isModCache;
tptenhance.isModCache = false;
$(".main-menu .dropdown a.dropdown-toggle").each(function(){
if ($(this).text().indexOf("Admin")!==-1)
tptenhance.isModCache = true;
});
return tptenhance.isModCache;
},
LoadForumBlocks:function(){
tptenhance.oldLoadForumBlocks();
$(".Actions > a").each(function(){
if (this.href.indexOf("/UnhidePost.html")!=-1)
{
$(this).click(function(e){
e.preventDefault();
$(this).addClass("disabled btn-primary");
$.get(this.href);
var newElement = $(this).parents('.Comment').children('.Message');
var postID = newElement.attr('id').split("-")[1];
$.get("/Discussions/Thread/Post.json?Post="+postID, function(){
location.reload(true);
// TODO: reload like http://powdertoy.co.uk/Applications/Application.Discussions/Javascript/Thread.js $(".Pagination a") click does
});
});
}
});
},
comments:
{
deleteUrl:function(commentId, saveId)
{
return "/Browse/View.html?ID="+encodeURIComponent(saveId)+"&DeleteComment="+encodeURIComponent(commentId);
},
// Get the ID of the comment inside elem (only works for moderators, since only they get a "Delete" link)
getId:function(elem)
{
var deleteLink = $(elem).find(".Actions a");
if (deleteLink.length)
return +(deleteLink.attr("href").match(/DeleteComment=[0-9]+/)[0].split("=")[1]);
else
return null;
},
add:function(saveId, commentText)
{
$.post(tptenhance.saves.viewUrl(saveId), {'Comment': commentText}, function(data){tptenhance.comments.addHandleResponse(data, saveId)});
},
addHandleResponse:function(data, saveId)
{
if (saveId == currentSaveID && typeof tptenhance.comments.commentView!=="undefined" && tptenhance.comments.commentView.getSelectedPage()===1)
{
tptenhance.comments.commentView.mergeComments(data);
}
}
},
tags:
{
// lists of callbacks triggered when tags are removed/disabled/enabled
// callback fn arguments: tag text, save id
tagRemovedCallbacks:$.Callbacks(),
// callback fn arguments: tag text
tagDisabledCallbacks:$.Callbacks(),
tagEnabledCallbacks:$.Callbacks(),
disableUrl:function(tag)
{
return "/Browse/Tags.html?Delete="+encodeURIComponent(tag)+"&Key="+encodeURIComponent(tptenhance.getSessionKey());
},
enableUrl:function(tag)
{
return "/Browse/Tags.html?UnDelete="+encodeURIComponent(tag)+"&Key="+encodeURIComponent(tptenhance.getSessionKey());
},
removeUrl:function(tag, saveId)
{
return "/Browse/EditTag.json?Op=delete&ID="+encodeURIComponent(saveId)+"&Tag="+encodeURIComponent(tag)+"&Key="+encodeURIComponent(tptenhance.getSessionKey());
},
searchUrl:function(search)
{
return "/Browse/Tags.html?Search_Query="+encodeURIComponent(search);
},
// Tag info HTML, showing moderators which user placed a particular tag
// Optional argument saveId: only show who placed the tag on a single save, instead of showing all instances of the tag
infoUrl:function(tagText, saveId)
{
var url = "/Browse/Tag.xhtml?Tag="+encodeURIComponent(tagText);
if (typeof saveId!="undefined")
url += "&SaveID="+encodeURIComponent(saveId);
return url;
},
// Event handlers to use an ajax request for enable/disable button clicks for tags displayed in a div.Tag (on /Browse/Tags.html and user moderation pages)
disableButtonClick:function(e){
e.preventDefault();
var tag = $(this).parents('.Tag').find(".TagText").text();
if (tptenhance.popoverSelectedTag==tag)
tptenhance.removePopover();
var tagElem = $(this).parents('.Tag');
var url = this.href.replace(/Redirect=[^&]*/, 'Redirect='+encodeURIComponent(tptenhance.dummyUrl));
$(this).parent().append(' <span class="LoadingIcon"><i class="icon-refresh"></i></span>');
$(this).css('display','none');
$.get(url, function()
{
tptenhance.tags.showDisabled(tagElem);
tptenhance.tags.tagDisabledCallbacks.fire(tagElem.find(".TagText").text());
});
},
enableButtonClick:function(e){
e.preventDefault();
var tagElem = $(this).parents('.Tag');
var url = this.href.replace(/Redirect=[^&]*/, 'Redirect='+encodeURIComponent(tptenhance.dummyUrl));
$(this).parent().append(' <span class="LoadingIcon"><i class="icon-refresh"></i></span>');
$(this).css('display','none');
$.get(url, function()
{
tptenhance.tags.showEnabled(tagElem);
tptenhance.tags.tagEnabledCallbacks.fire(tagElem.find(".TagText").text());
});
},
attachHandlers:function(baseElem){
// Attach event handlers which will make tag disabling/enabling happen in an ajax request. Also add a clearer tooltip for Disable buttons.
// Does not attach event handlers for tag info popups
baseElem.find('.UnDelButton').off('click').on('click', tptenhance.tags.enableButtonClick);
baseElem.find('.DelButton').off('click').on('click', tptenhance.tags.disableButtonClick).attr('title', 'Disable');
},
// Change a tag to appear as disabled or enabled (used by event handlers above)
showDisabled:function(tagElem){
if (tagElem.hasClass('Restricted'))
return;
tagElem.addClass('Restricted');
tagElem.find('.icon-refresh').remove();
var btn = tagElem.find('.DelButton');
btn.removeClass('DelButton').addClass('UnDelButton').css('display','inline');
btn.attr('href', btn.attr('href').replace('/Browse/Tags.html?Delete=','/Browse/Tags.html?UnDelete='));
btn.attr('title', 'Disable');
tptenhance.tags.attachHandlers(tagElem);
},
showEnabled:function(tagElem){
if (!tagElem.hasClass('Restricted'))
return;
tagElem.removeClass('Restricted');
tagElem.find('.icon-refresh').remove();
var btn = tagElem.find('.UnDelButton');
btn.removeClass('UnDelButton').addClass('DelButton').css('display','inline');
btn.attr('href', btn.attr('href').replace('/Browse/Tags.html?UnDelete=','/Browse/Tags.html?Delete='));
btn.attr('title', 'Approve');
tptenhance.tags.attachHandlers(tagElem);
},
// callbacks for updating status of built-in tag elements (provided by powdertoy.co.uk instead of added by this script) when this script removes/disables/enables a tag
default_onTagRemoved:function(affectedTagText, affectedSaveId){
if (typeof currentSaveID=="undefined" || affectedSaveId!=currentSaveID)
return;
$(".SaveTags span.Tag.label").each(function(){
if ($(this).text()===affectedTagText)
$(this).addClass("label-warning");
});
},
default_onTagDisabled:function(affectedTagText){
$("div.Tag").each(function(){
var tagtextelems = $(this).find(".TagText");
if (tagtextelems.length && tagtextelems.text()===affectedTagText)
tptenhance.tags.showDisabled($(this));
});
$(".SaveTags span.Tag.label").each(function(){
if ($(this).text()===affectedTagText)
$(this).addClass("label-danger label-important");
});
},
default_onTagEnabled:function(affectedTagText){
$("div.Tag").each(function(){
var tagtextelems = $(this).find(".TagText");
if (tagtextelems.length && tagtextelems.text()===affectedTagText)
tptenhance.tags.showEnabled($(this));
});
$(".SaveTags span.Tag.label").each(function(){
if ($(this).text()===affectedTagText)
$(this).removeClass("label-danger label-important");
});
},
isTagElemDisabled:function(tagElem){
tagElem = $(tagElem);
if (tagElem.is("span.TagText"))
tagElem = tagElem.parents(".Tag");
if (tagElem.is(".label.Tag"))
return tagElem.hasClass("label-danger") || tagElem.hasClass("label-important");
else
return tagElem.hasClass("Restricted");
},
isTagElemRemoved:function(tagElem){
tagElem = $(tagElem);
if (tagElem.is("span.TagText"))
tagElem = tagElem.parents(".Tag");
if (tagElem.is(".label.Tag"))
return tagElem.hasClass("label-warning");
return false;
},
createDisableLink:function(tagText){
return $('<a class="Tag-LinkDisable" title="Disable tag">Disable</a>')
.attr('href', tptenhance.tags.disableUrl(tagText)+"&Redirect="+encodeURIComponent(location.pathname+location.search));
},
createEnableLink:function(tagText){
return $('<a class="Tag-LinkEnable" title="Enable tag">Enable</a>')
.attr('href', tptenhance.tags.enableUrl(tagText)+"&Redirect="+encodeURIComponent(location.pathname+location.search));
}
},
makeSaveLinks:function(messages, convertAllNumbers)
{
// Turn numbers which might be save IDs into links
// 'messages' should be the jQuery elements to process, contents should be plain text
var regex;
if (typeof convertAllNumbers!="undefined" && convertAllNumbers)
regex = /(?:~|\b(?:(?:id|save|saveid)[^\d\w]?)[\s]*)?[0-9]+\b/gi;
else
regex = /(?:~|\b(?:(?:id|save|saveid)[^\d\w]?)[\s]*)[0-9]+\b/gi;
messages.each(function(){
var msg = $(this);
var text = msg.text();
msg.empty();
var result, prevLastIndex = 0;
regex.lastIndex = 0;
while ((result=regex.exec(text)))
{
// Append the text before the match
msg.append($('<span></span>').text(text.slice(prevLastIndex, result.index)));
// Turn the match into a link
var link = $('<a></a>');
var saveId = result[0].match(/[0-9]+/)[0];
link.attr('href', tptenhance.saves.viewUrl(saveId));
link.addClass('AutoSaveLink');
link.attr('data-saveid', saveId);
link.text(result[0]);
msg.append(link);
// store the position of the end of the match
prevLastIndex = regex.lastIndex;
}
// Append last plain text part
msg.append($('<span></span>').text(text.slice(prevLastIndex)));
});
},
forums:{
threadUrl:function(id)
{
return "/Discussions/Thread/View.html?Thread="+encodeURIComponent(id);
}
},
groups:{
currentGroupId:function()
{
// ID of the group currently being viewed
return +($(".Pageheader a:eq(1)").attr("href").match(/[0-9]+/)[0]);
}
},
reports:{
viewReportUrl:function(id)
{
return "/Reports/View.html?ID="+encodeURIComponent(id);
},
markAsReadUrl:function(id)
{
return "/Reports.html?Read="+encodeURIComponent(id);
},
unpublishUrl:function(id)
{
return "/Reports.html?Unpublish="+encodeURIComponent(id);
},
/* current
* <span class="badge badge-info">16</span>
<li style="background-color:rgb(240, 240, 240);border-top-color: rgb(250, 250, 250);"> <a href="/Browse/View.html?ID=355967" target="_blank"> <img src="/GetScreenshot.util?ID=355967&Size=small"/> </a> <span style="float: right; margin: 5px;"> <a href="/Reports.html?Unpublish=355967" class="ButtonLink">Unpublish</a> <a href="/Reports.html?Read=355967" class="ButtonLink">Mark as Read</a> </span> <div class="MainInfo" style="width: 355px; display: block; padding: 2px;"> <span class="ReportsCount">1</span> <span class="SaveName"> <a href="/Reports/View.html?ID=355967" target="_blank"> Light Splitter 2 </a> </span> by <span class="SaveAuthor">WinstonsDomain</span> </div> <div class="Clear"></div></li></ul>
*/
parseReportsHtml:function(html)
{
var reports = [];
$(html).find("li").each(function(){reports.push(tptenhance.reports.parseReportsHtmlSingle($(this)));});
/*reports.push({SaveId:17758,UnreadReportCount:2,SaveName:"8x6 line text display",Username:"jacksonmj"});
reports.push({SaveId:2198,UnreadReportCount:1,SaveName:"Destroyable city 5 (wth metro)",Username:"dima-gord"});*/
return reports;
},
parseReportsHtmlSingle:function(html)
{
html = $(html);
return {
SaveId: +html.find("img").attr("src").match(/[0-9]+/)[0],
UnreadReportCount: +html.find(".ReportsCount").text(),
SaveName: html.find(".SaveName a").text().trim(),
Username: html.find(".SaveAuthor").text().trim()
};
},
parseViewReport:function(html)
{
var reportMsgs = [];
$(html).find(".Post .Comment").each(function(){
var reasonHtml = $(this);
reportMsgs.push({
UserAvatar:reasonHtml.find(".Meta .Author img").attr("src"),
UserName:reasonHtml.find(".Meta .Author a:last-child").text().trim(),
ReportDate:reasonHtml.find(".Meta .Date").text().trim(),
Message:reasonHtml.find(".Message").text().trim()
});
});
return reportMsgs;
},
changeButtons:function()
{
$(".ButtonLink").addClass("btn btn-mini").each(function(){
var btn = $(this);
var url = btn.attr('href');
btn.attr('title', btn.text());
if (url.indexOf('Unpublish=')!=-1)
{
btn.addClass("btn-warning").html('<i class="icon-lock icon-white"></i> Unpublish');
}
if (url.indexOf('Read=')!=-1)
{
btn.addClass("btn-success").html('<i class="icon-ok icon-white"></i> Mark as read');
}
});
}
},
saves:{
dataUrl:function(id, historyVersion)
{
if (typeof historyVersion=="undefined" || !historyVersion)
return window.location.protocol+"//static.powdertoy.co.uk/"+encodeURIComponent(id)+".cps";
else
return window.location.protocol+"//static.powdertoy.co.uk/"+encodeURIComponent(id)+"_"+encodeURIComponent(historyVersion)+".cps";
},
smallerImgUrl:function(id, historyVersion) // 153px × 96px
{
// TODO: historyVersion?
if (typeof historyVersion=="undefined" || !historyVersion)
return "/GetScreenshot.util?ID="+encodeURIComponent(id)+"&Size=small";
else
return tptenhance.saves.smallImgUrl(id, historyVersion);
},
smallImgUrl:function(id, historyVersion) // 204px × 128px
{
if (typeof historyVersion=="undefined" || !historyVersion)
return window.location.protocol+"//static.powdertoy.co.uk/"+encodeURIComponent(id)+"_small.png";
else
return window.location.protocol+"//static.powdertoy.co.uk/"+encodeURIComponent(id)+"_"+encodeURIComponent(historyVersion)+"_small.png";
},
fullImgUrl:function(id, historyVersion) // 612px × 384px
{
if (typeof historyVersion=="undefined" || !historyVersion)
return window.location.protocol+"//static.powdertoy.co.uk/"+encodeURIComponent(id)+".png";
else
return window.location.protocol+"//static.powdertoy.co.uk/"+encodeURIComponent(id)+"_"+encodeURIComponent(historyVersion)+".png";
},
viewUrl:function(id, historyVersion)
{
if (typeof historyVersion=="undefined" || !historyVersion)
return "/Browse/View.html?ID="+encodeURIComponent(id);
else
return "/Browse/View.html?ID="+encodeURIComponent(id)+"&Date="+encodeURIComponent(historyVersion);
},
infoJsonUrl:function(id, historyVersion)
{
if (typeof historyVersion=="undefined" || !historyVersion)
return "/Browse/View.json?ID="+encodeURIComponent(id);
else
return "/Browse/View.json?ID="+encodeURIComponent(id)+"&Date="+encodeURIComponent(historyVersion);
},
infoJsonUrlPTT:function(id)
{
return window.location.protocol+"//powdertoythings.co.uk/Powder/Saves/View.json?ID="+encodeURIComponent(id);
},
infoDetailedJsonUrlPTT:function(id)
{
return window.location.protocol+"//powdertoythings.co.uk/Powder/Saves/ViewDetailed.json?ID="+encodeURIComponent(id);
},
historyJsonUrl:function(id)
{
return "/Browse.json?Search_Query=history%3A"+encodeURIComponent(id)+"&Start=0&Count=100";
},
voteMapUrl:function(id)
{
return "/IPTools.html?Save="+encodeURIComponent(id);
},
voteDataJsonUrl:function(id)
{
return "/IPTools/SaveVoteData.json?ID="+encodeURIComponent(id);
},
searchUrl:function(query)
{
return "/Browse.html?Search_Query="+encodeURIComponent(query);
},
userSearchUrl:function(user)
{
return tptenhance.saves.searchUrl("user:"+user);
},
getCurrentHistoryVersion:function()
{
var matches = window.location.toString().match(/Date=([0-9]+)/);
if (matches && matches.length)
return +matches[1];
else
return null;
},
promoState:{
Featured:2,
Promoted:1,
Normal:0,
Demoted:-1,
Disabled:-2
},
handleModActionsResponse:function(data, saveId)
{
if (saveId==currentSaveID)
{
$(".ModActions").replaceWith($(data).find(".ModActions"));
}
},
setPromoState:function(saveId, promoState)
{
if (!tptenhance.isMod())
return;
var url = tptenhance.saves.viewUrl(saveId) + '&Key=' + tptenhance.getSessionKey();
$.post(url, {'PromoState':promoState}, function(data){
tptenhance.saves.handleModActionsResponse(data, saveId);
});
},
unpublish:function(saveId)
{
var url = tptenhance.saves.viewUrl(saveId) + '&Key=' + tptenhance.getSessionKey();
$.post(url, {'ActionUnpublish':1}, function(data){
tptenhance.saves.handleModActionsResponse(data, saveId);
});
},
publish:function(saveId)
{
var url = tptenhance.saves.viewUrl(saveId) + '&Key=' + tptenhance.getSessionKey();
$.post(url, {'ActionPublish':1}, function(data){
tptenhance.saves.handleModActionsResponse(data, saveId);
});
},
tabs:{},
showVotes:function()
{
// some of this function is copied from the JS on the website
var m = [40, 40, 20, 20],
w = 612 - m[1] - m[3],
h = 300 - m[0] - m[2];
// Scales. Note the inverted domain for the y-scale: bigger is up!
var x = d3.time.scale().range([0, w]),
y = d3.scale.linear().range([h, 0]),
xAxis = d3.svg.axis().scale(x).orient("bottom").tickSize(-h, 0).tickPadding(6),
yAxis = d3.svg.axis().scale(y).orient("right").tickSize(-w).tickPadding(6);
// An area generator.
var area = d3.svg.area()
.interpolate("step-after")
.x(function(d) { return x(d.date); })
.y0(function(d) { return y((d.value<0)?d.value:0); })
.y1(function(d) { return y((d.value>0)?d.value:0); });
// A line generator.
var line = d3.svg.line()
.interpolate("step-after")
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.value); });
var svg = d3.select("#VoteGraph").append("svg:svg")
.attr("width", w + m[1] + m[3])
.attr("height", h + m[0] + m[2])
.append("svg:g")
.attr("transform", "translate(" + m[3] + "," + m[0] + ")");
var gradient = svg.append("svg:defs").append("svg:linearGradient")
.attr("id", "gradient")
.attr("x2", "0%")
.attr("y2", "100%");
gradient.append("svg:stop")
.attr("offset", "0%")
.attr("stop-color", "#9ecae1")
.attr("stop-opacity", 0.5);
gradient.append("svg:stop")
.attr("offset", "100%")
.attr("stop-color", "#6baed6")
.attr("stop-opacity", 1);
svg.append("svg:clipPath")
.attr("id", "clip")
.append("svg:rect")
.attr("x", x(0))
.attr("y", y(1))
.attr("width", x(1) - x(0))
.attr("height", y(0) - y(1));
svg.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(" + w + ",0)");
svg.append("svg:path")
.attr("class", "area")
.attr("clip-path", "url(#clip)")
.style("fill", "url(#gradient)");
svg.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," + h + ")");
svg.append("svg:path")
.attr("class", "line")
.attr("clip-path", "url(#clip)");
var voteLines = svg.append("svg:g");
var dupVLine;
var rect = svg.append("svg:rect")
.attr("class", "pane")
.attr("width", w)
.attr("height", h);
//.call(d3.behavior.zoom().on("zoom", zoom));
d3.json(tptenhance.saves.voteDataJsonUrl(currentSaveID), function(data) {
// Parse dates and numbers.
data.votes.forEach(function(d) {
d.date = new Date(d.date*1000);//parse(d.date);
d.value = +d.value;
});
data.dupVotes.forEach(function(d) {
d.Date = new Date(d.Date*1000);//parse(d.date);
});
if (data.dupVotes.length)
{
var dupVotesDiv = $('<div></div>').addClass("DupVotes");
$('<h4>Suspicious votes (<a>see map</a>)</h4>').appendTo(dupVotesDiv).find('a').attr('href',tptenhance.saves.voteMapUrl(currentSaveID));
var dupVotesTbl = $('<table cellspacing="0" cellpadding="0"><thead><tr><th>Date</th><th>Username</th><th>IP address</th><th> </th></tr></thead><tbody></tbody></table>').appendTo(dupVotesDiv);
var dupVotesTblBody = dupVotesTbl.find('tbody');
var dupVotes = data.dupVotes.sort(function(a,b){return (+b.Date)-(+a.Date);});
var ipcolours = {};
var iplist = [];
dupVotes.forEach(function(d) {
if (typeof ipcolours[d.SourceAddress] == "undefined")
{
ipcolours[d.SourceAddress] = "";
iplist.push(d.SourceAddress);
}
});
if (iplist.length>1)
{
var hueStep = 340/iplist.length;
for (var i=0; i<iplist.length; i++)
{
ipcolours[iplist[i]] = 'hsl('+(hueStep*i)+',50%,80%)';
}
}
dupVotes.forEach(function(d) {
var tableRow = $('<tr></tr>');
var cell;
cell = $('<td><a></a></td>').addClass('Date').appendTo(tableRow);
cell.text(moment(d.Date).format("DD MMM YYYY HH:mm:ss"));
cell = $('<td><a></a></td>').addClass('Username').appendTo(tableRow);
cell.children().first().attr('href', tptenhance.users.moderationUrlById(d.UserID)).text(d.Username);
// This is a bootstrap tooltip, not the jquery tooltip plugin
var hoverTimeout = false;
var hovered = false;
cell.on("mouseleave", function(){
hovered = false;
if (hoverTimeout!==false)
{
clearTimeout(hoverTimeout);
hoverTimeout = false;
}
});
cell.on("mouseenter", function(){
hovered = true;
var that = $(this);
if (hoverTimeout===false)
{
hoverTimeout = setTimeout(function(){
hoverTimeout = false;
that.off("mouseenter");
tptenhance.users.getModerationInfoById(d.UserID, function(data){
var txt = "";
if (data.Banned && data.Bans[0].Duration===0) txt += "Perm banned";
else
{
if (data.Banned)
{
txt += "Temp banned";
if (data.Bans.length>1)
{
txt += ", "+(data.Bans.length-1)+" previous ban";
if (data.Bans.length>2) txt += "s";
}
}
else
{
txt += "Not currently banned";
if (data.Bans.length>0)
{
txt += ", "+data.Bans.length+" previous ban";
if (data.Bans.length>1) txt += "s";
}
}
}
txt += "<br>";
if (!data.Comments.length && !data.Tags.length)
txt += "No tags or comments";
else
{
txt += data.Tags.length+" tags, ";
if (data.CommentPageCount>1)
txt += data.CommentPageCount+" pages of comments";
else
txt += data.Comments.length+" comments";
}
// TODO: saves?
that.tooltip({title:txt, placement:"left"});
if (hovered) that.tooltip("show");
});
}, 500);
}
});
cell = $('<td><a></a></td>').addClass('IPAddress').appendTo(tableRow);
cell.children().first().attr('href', tptenhance.ipMapUrl(d.SourceAddress)).text(d.SourceAddress);
if (typeof ipcolours[d.SourceAddress] != "undefined" && ipcolours[d.SourceAddress] !== "")
cell.css('background-color', ipcolours[d.SourceAddress]);
cell = $('<td></td>').addClass('VoteType');
if (d.Vote==1) cell.html('<i class="VoteUpIcon icon-chevron-up icon-white"></i>');
else if (d.Vote==-1) cell.html('<i class="VoteDownIcon icon-chevron-down icon-white"></i>');
else cell.html(' ');
cell.appendTo(tableRow);
if (iplist.length>1)
{
tableRow.on("dblclick", function(){
if ($(this).hasClass("highlight"))
{
$(this).parents("tbody").find("tr").removeClass("highlight");
return;
}
var target = $(this).find(".IPAddress a").text();
$(this).parents("tbody").find("tr").each(function(){
if ($(this).find(".IPAddress a").text() == target)
$(this).addClass("highlight");
else
$(this).removeClass("highlight");
});
});
}
dupVotesTblBody.append(tableRow);
});
$("#VoteGraph").append(dupVotesDiv);
}
x.domain([d3.min(data.votes, function(d) { return d.date; }), d3.max(data.votes, function(d) { return d.date; })]);
var ydomain = d3.extent(data.votes, function(d) { return d.value; });
if (ydomain[0]>0) ydomain[0] = 0;
y.domain(ydomain);
rect.call(d3.behavior.zoom().x(x).on("zoom", zoom));
// Bind the data to our path elements.
svg.select("path.area").data([data.votes]);
svg.select("path.line").data([data.votes]);
function voteMouseover(d) {
//d.classed("active", true);
svg.selectAll(".dupVLine").classed("active", function(p) { return p.SourceAddress === d.SourceAddress; });
}
function voteMouseout() {
svg.selectAll(".active").classed("active", false);
//info.text(defaultInfo);
}
dupVLine = voteLines.selectAll("line.link")
.data(data.dupVotes);
var lineG = dupVLine.enter().insert("svg:g")
.attr("class", function(d) { return "dupVLine"+d.Vote+" dupVLine"; })
.on("mouseover", voteMouseover)
.on("mouseout", voteMouseout);
lineG.append("line")
.attr("x1", 0).attr("x2", 0).attr("y1", h).attr("y2", -5);
lineG.append("text")
.attr("text-anchor", "middle")
.attr('font-size', 11)
.attr("dy", ".1em")
.text(function(d) { return d.Username; });
lineG.append("text")
.attr("text-anchor", "middle")
.attr('font-size', 11)
.attr("dy", ".1em")
.attr("transform", "translate(0, 14)")
.text(function(d) { return d.SourceAddress; });
//.x1(function(d) { return x(d.Date); })
//.y1(function(d) { return y(100); });
//.style("stroke-width", function(d) { return Math.sqrt(d.value); });
dupVLine.exit().remove();
/*link.enter().insert("svg:line", ".node")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value); });
link.exit().remove();*/
draw();
});
function draw() {
svg.select("g.x.axis").call(xAxis);
svg.select("g.y.axis").call(yAxis);
svg.select("path.area").attr("d", area);
svg.select("path.line").attr("d", line);
/*dupVLine.attr("x1", function(d) { return x(d.Date); })
.attr("y1", function(d) { return h; })
.attr("x2", function(d) { return x(d.Date); })
.attr("y2", function(d) { return -5; });*/
dupVLine.attr("transform", function(d) { return "translate("+x(d.Date)+", 0)"; });
//svg.select("dupVotes.line").attr();
}
// Using a timeout here to defer drawing seems to improve zooming in Firefox on slow computers
// Possibly multiple calls to zoom are issued simultaneously depending on the amount of
// scroll wheel movement, and unnecessary redraws occur. The setTimeout defers drawing,
// hopefully until after all zoom calls occur.
var zoomDrawTimeout = false;
function zoomDraw() {
zoomDrawTimeout = false;
draw();
}
function zoom() {
//d3.event.transform(x); // TODO d3.behavior.zoom should support extents
if (zoomDrawTimeout===false) zoomDrawTimeout = setTimeout(zoomDraw, 1);
}
}
},
users:{
moderationUrlById:function(id)
{
return "/User/Moderation.html?ID="+encodeURIComponent(id);
},
profileUrlById:function(id)
{
return "/User.html?ID="+encodeURIComponent(id);
},
savesUrlById:function(id)
{
return "/User/Saves.html?ID="+encodeURIComponent(id);
},
moderationUrlByName:function(n)
{
return "/User/Moderation.html?Name="+encodeURIComponent(n);
},
profileUrlByName:function(n)
{
return "/User.html?Name="+encodeURIComponent(n);
},
savesUrlByName:function(n)
{
return "/User/Saves.html?Name="+encodeURIComponent(n);
},
parseModerationPage:function(html)
{
html = $(html).find(".Page");
var data = {};
data.Banned = (html.find(".UnBanUser").length>0);
data.KnownAddresses = [];
html.find(".KnownAddresses a").each(function(){data.KnownAddresses.push($(this).text());});
data.Comments = [];
html.find(".MessageList .Post").each(function(){
var comment = $(this);
data.Comments.push({
SaveID: +comment.find(".SaveInfo a").text(),
date: comment.find(".Date").text(),
CommentID: +tptenhance.comments.getId(comment),
Message: comment.find(".Message").html()
});
});
data.CommentPageCount = +(html.find(".pagination li:nth-last-child(2) a").first().text());
data.Bans = [];
html.find(".BanHistory li").each(function(){
var ban = $(this);
var h6 = ban.find("h6").text().split(", ");
var otherText = ban.clone();
otherText.children().remove();
otherText = otherText.text().split("\"");
var duration = otherText.shift().replace("\s+$","").toLowerCase();
if (duration.indexOf("permanently")!=-1)
duration = 0;
else if (duration.indexOf("hour")!=-1)
duration = 60*60*(+duration.split(" ")[0]);
else if (duration.indexOf("day")!=-1)
duration = 60*60*24*(+duration.split(" ")[0]);
else if (duration.indexOf("week")!=-1)
duration = 60*60*24*7*(+duration.split(" ")[0]);
else if (duration.indexOf("month")!=-1)
duration = 60*60*24*7*4*(+duration.split(" ")[0]); // 4 weeks seems right, e.g. a ban reported on IRC as 67200 hours shows as 100 months
otherText.pop();
data.Bans.push({
date: h6[0],
By: h6[1],
Reason: otherText.join("\""),
Duration: duration
});
});
data.Tags = [];
html.find(".TagText").each(function(){ data.Tags.push($(this).text()); });
data.SaveDeletions = +$(html.find(".Record .Information")[1]).text().match(/[0-9]+/)[0];
return data;
},
getModerationInfoById:function(id,callback)
{
$.get(tptenhance.users.moderationUrlById(id), function(data){
callback(tptenhance.users.parseModerationPage(data));
}, "html");
}
},
ipMapUrl:function(ip)
{
return "/IPTools.html?IP="+encodeURIComponent(ip);
}
};
tptenhance.tags.tagRemovedCallbacks.add(tptenhance.tags.default_onTagRemoved);
tptenhance.tags.tagDisabledCallbacks.add(tptenhance.tags.default_onTagDisabled);
tptenhance.tags.tagEnabledCallbacks.add(tptenhance.tags.default_onTagEnabled);
tptenhance.tags.TagInfoPopup = function(){
this.targetElem = false;
this.popupElem = false;
this.selectedTagText = "";
this.tagDisabled = false;
this.getInfoXHR = false;
this.updatePosition = this.updatePosition.bind(this);
this.handleRemoveLinkClick = this.handleRemoveLinkClick.bind(this);
this.handleDisableLinkClick = this.handleDisableLinkClick.bind(this);
this.handleEnableLinkClick = this.handleEnableLinkClick.bind(this);
this.onTagRemoved = this.onTagRemoved.bind(this);
this.onTagDisabled = this.onTagDisabled.bind(this);
this.onTagEnabled = this.onTagEnabled.bind(this);
};
tptenhance.tags.TagInfoPopup.prototype.isOpen = function(){
return (!!this.targetElem);// return true if the popup is visible
};
tptenhance.tags.TagInfoPopup.prototype.normaliseTargetElem = function(elem){
elem = $(elem);
if (elem.hasClass("TagText"))
elem = elem.parents(".Tag");
return elem;
};
tptenhance.tags.TagInfoPopup.prototype.handleRemoveLinkClick = function(e){
var tagInfo = $(e.target).parents('div.TagInfo');
var saveId;
var matches = $(tagInfo).find("a.Tag-LinkRemove").attr("href").match(/ID=([0-9]+)/);
if (matches)
saveId = +matches[1];
else if (typeof currentSaveID!="undefined")
saveId = currentSaveID;
var url = e.target.href;
var placeholder = $(tptenhance.deletingHtml).addClass("Tag-LinkRemove");
$(e.target).replaceWith(placeholder);
var that = this;
var tagText = this.selectedTagText;
$.get(url, function(){
placeholder.replaceWith($(tptenhance.deletedHtml).addClass("Tag-LinkRemoved"));
if (that.targetElem.is("span.Tag.label"))
that.targetElem.addClass("label-warning");
tptenhance.tags.tagRemovedCallbacks.fire(tagText, saveId);
});