Advertisement
Guest User

SpookyX v22

a guest
Mar 27th, 2015
454
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // Displayable Name of your script
  3. // @name           SpookyX
  4.  
  5. // Brief description
  6. // @description    Enhances functionality of FoolFuuka boards. Devloped further for more comfortable ghost-posting on the moe archives.
  7.  
  8. // Your name, copyright  
  9. // @author          GNH
  10. // @copyright      2014, GNH
  11.  
  12. // Version Number
  13. // @version        22
  14.  
  15. // @include          https://*4plebs.org/*
  16. // @include          http://*4plebs.org/*
  17. // @include          https://archive.moe/*
  18. // @include          http://*loveisover.me/*
  19. // @include          https://*loveisover.me/*
  20. // @include          http://*imcute.yt/*
  21. // @include          https://*imcute.yt/*
  22. // @include          http://boards.foolz.us/*
  23. // @include          https://boards.foolz.us/*
  24. // @include          https://*nyafuu.org/*
  25. // @include          http://*nyafuu.org/*
  26. // @include          https://*fgts.jp/*
  27. // @include          http://*fgts.jp/*
  28. // @include          https://*not4plebs.org/*
  29. // @include          http://*not4plebs.org/*
  30.  
  31. // @grant       none
  32.  
  33. // ==/UserScript==
  34.  
  35. /* USER OPTIONS START */
  36. var imgSites = "puu.sh|i.imgur.com|data.archive.moe|i.4cdn.org|i0.kym-cdn.com|[\\S]*.deviantart.net|a.pomf.se"; // Sites to embed images from
  37. var imgNumMaster = 1; // Max number of images to embed
  38. var autoplayVids = false; // Make embedded videos play automatically (they start muted, expanding unmutes)
  39. var hideQROptions = true; // Make the reply options hidden by default in the quick reply
  40. var favicon = 2; // Choose which favicon is used to indicate there are unread posts. Preset numbers are 0-4, replace with link to custom image if you desire such as: "http://i.imgur.com/XGsrewo.png"
  41. var features = {
  42.     "postCounter":false,   // Add a post counter to the reply box
  43.     "inlineImages":true,   // Load full-size images in the thread, enable click to expand
  44.     "hidePosts":false,     // Allow user to hide posts manually
  45.     "newPosts":true,       // Reflect new posts in the tab name
  46.     "embedImages":true,    // Embed image links in thread
  47.     "inlineReplies":true,  // Click replies to expand them inline
  48.     "postQuote":true,      // Clicking the post number will insert highlighted text into the reply box
  49.     "filter":false,          // Hide undesirable posts from view
  50.     "labelYourPosts":true  // Add '(You)' to your posts and links that point to them
  51. };
  52. var filterCharThreshold = 100; // Filter posts with less than this number of characters
  53. var filteredStringsT0 = [    // List of Tier 0 strings to filter for. Capitalisation sensitive
  54.     //"[\\S]*(a{4,}|b{4,}|c{4,}|d{4,}|e{4,}|f{4,}|g{4,}|h{4,}|i{4,}|j{4,}|k{4,}|l{4,}|m{4,}|n{4,}|o{4,}|p{4,}|q{4,}|r{4,}|s{4,}|t{4,}|u{4,}|v{4,}|w{4,}|x{4,}|y{4,}|z{4,})[\\S]*",
  55.     "[\\S]*(e{4,}|E{4,}|i{4,}|I{4,}|o{4,}|O{4,}|u{4,}|U{4,})[\\S]*",
  56.     "E(G|g)(O|o)(-kun|kun)?"
  57. ];
  58. var filteredStringsT1 = [    // List of Tier 1 strings to filter for
  59.     "daki[\\S]*",
  60.     "ded",
  61.     "ayy lmao",
  62.     "incest",
  63.     "imoutos?",
  64.     "moonrunes",
  65.     "tale[\\S]*[^( of witches)]",
  66.     "ree+[\\S]*",
  67.     "boogeyman",
  68.     "normies"
  69. ];
  70. var filteredStringsT2 = [    // List of Tier 2 strings to filter for
  71.     "quest whe?n[?]*",
  72.     "test",
  73.     "tsukaima"
  74. ];
  75. var filteredTrips = [       // List of tripcodes to filter for
  76.     "!!/90sanF9F3Z"
  77. ];
  78. var filteredNames = [       // List of names to filter for
  79.     "久保島のミズゴロウ"
  80. ];
  81. /* USER OPTIONS END */
  82.  
  83. var newPostCount = 0;
  84. var DocumentTitle = document.title;
  85. var ignoreInline = ['v'];
  86. var rulesBox = $(".rules_box").html();
  87. if(autoplayVids){var autoplayVid = "autoplay";}else{var autoplayVid="";}
  88. var threadID;
  89. var queuedYouLabels = [];
  90.  
  91. function ThreadUpdate(features) {
  92.     if (features.postCounter){postCounter();}  
  93.     if (features.inlineImages){inlineImages();}
  94.     if (features.hidePosts){hidePosts();}
  95.     if (features.newPosts){newPosts();}
  96.     if (features.embedImages){embedImages();}
  97.     if (features.inlineReplies){inlineReplies();}
  98.     if (features.postQuote){postQuote();}
  99.     if (features.filter){filter();}
  100. }
  101.  
  102. switch(favicon) {
  103.     case 0: favicon = "http://i.imgur.com/7iTgtjy.png"; break;
  104.     case 1: favicon = "http://i.imgur.com/AWVjxfw.png"; break;
  105.     case 2: favicon = "http://i.imgur.com/S7uBSPZ.png"; break;
  106.     case 3: favicon = "http://i.imgur.com/Rt8dEaq.png"; break;
  107.     case 4: favicon = "http://i.imgur.com/3bRaVUl.png"; break;
  108.     default: break;
  109. }
  110.  
  111. $.fn.elemText = function() {
  112.     var text = '';
  113.     this.each(function() {
  114.         $(this).contents().each(function() {
  115.             if (this.nodeType == Node.TEXT_NODE)
  116.                 text += this.textContent;
  117.         });
  118.     });
  119.     return text;
  120. };
  121.  
  122. var escapeRegExp;
  123.  
  124. (function () {
  125.     // Referring to the table here:
  126.     // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  127.     // these characters should be escaped
  128.     // \ ^ $ * + ? . ( ) | { } [ ]
  129.     // These characters only have special meaning inside of brackets
  130.     // they do not need to be escaped, but they MAY be escaped
  131.     // without any adverse effects (to the best of my knowledge and casual testing)
  132.     // : ! , =
  133.     // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)
  134.  
  135.     var specials = [
  136.         // order matters for these
  137.         "-"
  138.         , "["
  139.         , "]"
  140.         // order doesn't matter for any of these
  141.         , "/"
  142.         , "{"
  143.         , "}"
  144.         , "("
  145.         , ")"
  146.         , "*"
  147.         , "+"
  148.         , "?"
  149.         , "."
  150.         , "\\"
  151.         , "^"
  152.         , "$"
  153.         , "|"
  154.     ]
  155.  
  156.     // I choose to escape every character with '\'
  157.     // even though only some strictly require it when inside of []
  158.     , regex = RegExp('[' + specials.join('\\') + ']', 'g')
  159.     ;
  160.     escapeRegExp = function (str) {
  161.         return str.replace(regex, "\\$&");
  162.     };
  163.  
  164.     // test escapeRegExp("/path/to/res?search=this.that")
  165. }());
  166.  
  167. shortcut = {
  168.     'all_shortcuts':{},//All the shortcuts are stored in this array
  169.     'add': function(shortcut_combination,callback,opt) {
  170.         //Provide a set of default options
  171.         var default_options = {
  172.             'type':'keydown',
  173.             'propagate':false,
  174.             'disable_in_input':false,
  175.             'target':document,
  176.             'keycode':false
  177.         };
  178.         if(!opt) opt = default_options;
  179.         else {
  180.             for(var dfo in default_options) {
  181.                 if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
  182.             }
  183.         }
  184.  
  185.         var ele = opt.target;
  186.         if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
  187.         var ths = this;
  188.         shortcut_combination = shortcut_combination.toLowerCase();
  189.  
  190.         //The function to be called at keypress
  191.         var func = function(e) {
  192.             e = e || window.event;
  193.  
  194.             if(opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields
  195.                 var element;
  196.                 if(e.target) element=e.target;
  197.                 else if(e.srcElement) element=e.srcElement;
  198.                 if(element.nodeType==3) element=element.parentNode;
  199.  
  200.                 if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
  201.             }
  202.  
  203.             //Find Which key is pressed
  204.             if (e.keyCode) code = e.keyCode;
  205.             else if (e.which) code = e.which;
  206.             var character = String.fromCharCode(code).toLowerCase();
  207.  
  208.             if(code == 188) character=","; //If the user presses , when the type is onkeydown
  209.             if(code == 190) character="."; //If the user presses , when the type is onkeydown
  210.  
  211.             var keys = shortcut_combination.split("+");
  212.             //Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
  213.             var kp = 0;
  214.  
  215.             //Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
  216.             var shift_nums = {
  217.                 "`":"~",
  218.                 "1":"!",
  219.                 "2":"@",
  220.                 "3":"#",
  221.                 "4":"$",
  222.                 "5":"%",
  223.                 "6":"^",
  224.                 "7":"&",
  225.                 "8":"*",
  226.                 "9":"(",
  227.                 "0":")",
  228.                 "-":"_",
  229.                 "=":"+",
  230.                 ";":":",
  231.                 "'":"\"",
  232.                 ",":"<",
  233.                 ".":">",
  234.                 "/":"?",
  235.                 "\\":"|"
  236.             };
  237.             //Special Keys - and their codes
  238.             var special_keys = {
  239.                 'esc':27,
  240.                 'escape':27,
  241.                 'tab':9,
  242.                 'space':32,
  243.                 'return':13,
  244.                 'enter':13,
  245.                 'backspace':8,
  246.  
  247.                 'scrolllock':145,
  248.                 'scroll_lock':145,
  249.                 'scroll':145,
  250.                 'capslock':20,
  251.                 'caps_lock':20,
  252.                 'caps':20,
  253.                 'numlock':144,
  254.                 'num_lock':144,
  255.                 'num':144,
  256.  
  257.                 'pause':19,
  258.                 'break':19,
  259.  
  260.                 'insert':45,
  261.                 'home':36,
  262.                 'delete':46,
  263.                 'end':35,
  264.  
  265.                 'pageup':33,
  266.                 'page_up':33,
  267.                 'pu':33,
  268.  
  269.                 'pagedown':34,
  270.                 'page_down':34,
  271.                 'pd':34,
  272.  
  273.                 'left':37,
  274.                 'up':38,
  275.                 'right':39,
  276.                 'down':40,
  277.  
  278.                 'f1':112,
  279.                 'f2':113,
  280.                 'f3':114,
  281.                 'f4':115,
  282.                 'f5':116,
  283.                 'f6':117,
  284.                 'f7':118,
  285.                 'f8':119,
  286.                 'f9':120,
  287.                 'f10':121,
  288.                 'f11':122,
  289.                 'f12':123
  290.             };
  291.  
  292.             var modifiers = {
  293.                 shift: { wanted:false, pressed:false},
  294.                 ctrl : { wanted:false, pressed:false},
  295.                 alt  : { wanted:false, pressed:false},
  296.                 meta : { wanted:false, pressed:false} //Meta is Mac specific
  297.             };
  298.  
  299.             if(e.ctrlKey) modifiers.ctrl.pressed = true;
  300.             if(e.shiftKey)  modifiers.shift.pressed = true;
  301.             if(e.altKey)  modifiers.alt.pressed = true;
  302.             if(e.metaKey)   modifiers.meta.pressed = true;
  303.  
  304.             for(var i=0; k=keys[i],i<keys.length; i++) {
  305.                 //Modifiers
  306.                 if(k == 'ctrl' || k == 'control') {
  307.                     kp++;
  308.                     modifiers.ctrl.wanted = true;
  309.  
  310.                 } else if(k == 'shift') {
  311.                     kp++;
  312.                     modifiers.shift.wanted = true;
  313.  
  314.                 } else if(k == 'alt') {
  315.                     kp++;
  316.                     modifiers.alt.wanted = true;
  317.                 } else if(k == 'meta') {
  318.                     kp++;
  319.                     modifiers.meta.wanted = true;
  320.                 } else if(k.length > 1) { //If it is a special key
  321.                     if(special_keys[k] == code) kp++;
  322.  
  323.                 } else if(opt['keycode']) {
  324.                     if(opt['keycode'] == code) kp++;
  325.  
  326.                 } else { //The special keys did not match
  327.                     if(character == k) kp++;
  328.                     else {
  329.                         if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
  330.                             character = shift_nums[character];
  331.                             if(character == k) kp++;
  332.                         }
  333.                     }
  334.                 }
  335.             }
  336.  
  337.             if(kp == keys.length &&
  338.                modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
  339.                modifiers.shift.pressed == modifiers.shift.wanted &&
  340.                modifiers.alt.pressed == modifiers.alt.wanted &&
  341.                modifiers.meta.pressed == modifiers.meta.wanted) {
  342.                 callback(e);
  343.  
  344.                 if(!opt['propagate']) { //Stop the event
  345.                     //e.cancelBubble is supported by IE - this will kill the bubbling process.
  346.                     e.cancelBubble = true;
  347.                     e.returnValue = false;
  348.  
  349.                     //e.stopPropagation works in Firefox.
  350.                     if (e.stopPropagation) {
  351.                         e.stopPropagation();
  352.                         e.preventDefault();
  353.                     }
  354.                     return false;
  355.                 }
  356.             }
  357.         }
  358.         this.all_shortcuts[shortcut_combination] = {
  359.             'callback':func,
  360.             'target':ele,
  361.             'event': opt['type']
  362.         };
  363.         //Attach the function with the event
  364.         if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
  365.         else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
  366.         else ele['on'+opt['type']] = func;
  367.     },
  368.  
  369.     //Remove the shortcut - just specify the shortcut and I will remove the binding
  370.     'remove':function(shortcut_combination) {
  371.         shortcut_combination = shortcut_combination.toLowerCase();
  372.         var binding = this.all_shortcuts[shortcut_combination];
  373.         delete(this.all_shortcuts[shortcut_combination])
  374.         if(!binding) return;
  375.         var type = binding['event'];
  376.         var ele = binding['target'];
  377.         var callback = binding['callback'];
  378.  
  379.         if(ele.detachEvent) ele.detachEvent('on'+type, callback);
  380.         else if(ele.removeEventListener) ele.removeEventListener(type, callback, false);
  381.         else ele['on'+type] = false;
  382.     }
  383. }
  384.  
  385. var getBoard = function() {
  386.     URL = document.URL;
  387.     return URL.split("/")[3];
  388. }
  389.  
  390. var inlineImages = function()
  391. {
  392.     // I Believe because I'm setting the src of the thumbnail to the full image right away,
  393.     // it also causes the images to be prefetched
  394.     $('.thread_image_box').each(function(index,currentImage) {
  395.         if ($(currentImage).data("inline") != "true"){
  396.             //$(currentImage).find('a').each(function() {
  397.             $(currentImage).find('>a').each(function() {
  398.                 fullImage = $(this).attr('href');
  399.                 //    if (!fullImage.match(/thumb(-[23])?/)){
  400.                 //        if (!fullImage.match(/search(-[23])?/)){
  401.                 //            if (!fullImage.match(/redirect?/)){
  402.                 //                if (!fullImage.match(/download/)){
  403.                 if (fullImage.match(/\.webm$/)){ // Handle post webms
  404.                     $(currentImage).html('<video width="125" style="float:left" name="media" loop muted '+autoplayVid+'><source src="'+fullImage+'" type="video/webm"></video>');
  405.                 }else if (!fullImage.match(/(\.pdf|\.swf)$/)){
  406.                     $(currentImage).find('img').each(function()  {
  407.                         $(this).attr('src',fullImage);
  408.                         $(this).removeAttr('width');
  409.                         $(this).removeAttr('height');
  410.                         if ($(this).data("handled") != "true"){
  411.                             if ($(this).hasClass("thread_image")){ // Handle OP images
  412.                                 $(this).data("handled","true");
  413.                                 $(this).addClass("smallImageOP");
  414.                                 $(this).click(function(e){
  415.                                     if (!e.originalEvent.ctrlKey && e.which == 1){
  416.                                         e.preventDefault();
  417.                                         $($(this)["0"]["previousSibling"]).toggle(); // Toggle the Spoiler text
  418.                                         $(this).toggleClass("smallImageOP");
  419.                                         $(this).toggleClass("bigImage");
  420.                                     }
  421.                                 });
  422.                             }else{ // Handle post images
  423.                                 $(this).addClass("smallImage");
  424.                                 $(this).click(function(e){
  425.                                     if (!e.originalEvent.ctrlKey && e.which == 1){
  426.                                         e.preventDefault();
  427.                                         $($(this)["0"]["previousSibling"]).toggle(); // Toggle the Spoiler text
  428.                                         $(this).toggleClass("smallImage");
  429.                                         $(this).toggleClass("bigImage");
  430.                                     }
  431.                                 });
  432.                             }
  433.                         }
  434.                     });
  435.                 }
  436.                 //              }
  437.                 //          }    
  438.                 $(currentImage).data("inline","true");
  439.                 //      }
  440.                 //  }
  441.             });
  442.         }
  443.     });
  444.  
  445.     $('video').each(function(index,currentVideo) {
  446.         if ($(currentVideo).data("inline") != "true"){
  447.             $(this).click(function(e){
  448.                 //e.preventDefault();
  449.                 if ($(this).hasClass("fullVideo")){
  450.                     this.muted=true;
  451.                     $(this).attr('width',"125");
  452.                     $(this).removeAttr('controls');
  453.                     $(this).removeClass("fullVideo");
  454.                 }else{
  455.                     $(this).removeAttr('width');
  456.                     $(this).attr('controls',"");
  457.                     $(this).addClass("fullVideo");
  458.                     this.muted=false;
  459.                 }
  460.             });
  461.             $(currentVideo).data("inline","true");
  462.         }
  463.     });
  464. }
  465.  
  466. var inlineReplies = function(){
  467.     $('article.post').each(function(index,currentPost) {
  468.         if ($(currentPost).data("inline") != "true"){
  469.             $(this).addClass("base");
  470.         }
  471.         $(currentPost).data("inline","true");
  472.     });
  473.     $('.post_backlink > .backlink').each(function(index,currentPost) {
  474.         if ($(currentPost).data("inline") != "true"){
  475.             $(this).on("click", function(e){
  476.                 if (!e.originalEvent.ctrlKey && e.which == 1){
  477.                     e.preventDefault();
  478.                     //e.stopPropagation();
  479.                     var postID = $(this).attr("data-post");
  480.                     var rootPostID = $(e["target"].closest('article.base')).attr('id');
  481.                     if ($(e["target"]).hasClass("inlined")){
  482.                         $(e["target"]).removeClass("inlined");
  483.                         $('.sub'+rootPostID).each(function(index,currentPost){
  484.                             $("#"+currentPost.id.substr(1)+".forwarded").removeClass("forwarded");
  485.                         });
  486.                         $('#i'+postID+'.sub'+rootPostID).remove();
  487.                     }else{
  488.                         $(e["target"]).addClass("inlined");
  489.                         $(e["target"]["parentNode"]["parentNode"]).after('<div class="inline sub'+rootPostID+'" id="i'+postID+'"></div>');
  490.                         $("#"+postID).addClass("forwarded").clone().removeClass("forwarded base post").attr("id","r"+postID).appendTo($("#i"+postID+'.sub'+rootPostID));
  491.                         $("#"+rootPostID+'.base .inline').each(function(index,currentPost){
  492.                             if (!$(this).hasClass('sub'+rootPostID)){
  493.                                 $(this).attr("class","inline sub"+rootPostID);
  494.                             }
  495.                         });
  496.                         $("#i"+postID+" .post_wrapper").addClass("post_wrapperInline");
  497.                     }
  498.                 }
  499.             });
  500.             $(currentPost).data("inline","true")
  501.         }
  502.     });
  503.     $('.text .backlink').each(function(index,currentPost) {
  504.         if ($(currentPost).data("inline") != "true"){
  505.             $(this).on("click", function(e){
  506.                 if (!e.originalEvent.ctrlKey && e.which == 1){
  507.                     e.preventDefault();
  508.                     //e.stopPropagation();
  509.                     var postID = $(this).attr("data-post");
  510.                     var rootPostID = $(e["target"].closest('article.base')).attr('id');
  511.                     if ($(e["target"]).hasClass("inlined")){
  512.                         $(e["target"]).removeClass("inlined");
  513.                         $('.sub'+rootPostID).each(function(index,currentPost){
  514.                             $("#"+currentPost.id.substr(1)+".forwarded").removeClass("forwarded");
  515.                         });
  516.                         $('#i'+postID+'.sub'+rootPostID).remove();
  517.                     }else{
  518.                         $(e["target"]).addClass("inlined");
  519.                         $(e["target"]["parentNode"]).after('<div class="inline sub'+rootPostID+'" id="i'+postID+'"></div>');
  520.                         $("#"+postID).addClass("forwarded").clone().removeClass("forwarded base post").attr("id","r"+postID).appendTo($("#i"+postID+'.sub'+rootPostID));
  521.                         $("#"+rootPostID+'.base .inline').each(function(index,currentPost){
  522.                             if (!$(this).hasClass('sub'+rootPostID)){
  523.                                 $(this).attr("class","inline sub"+rootPostID);
  524.                             }
  525.                         });
  526.                         $("#i"+postID+" .post_wrapper").addClass("post_wrapperInline");
  527.                     }
  528.                 }
  529.             });
  530.             $(currentPost).data("inline","true")
  531.         }
  532.     });
  533. };
  534.  
  535. function getSelectionText() {
  536.     var text = "";
  537.     if (window.getSelection) {
  538.         text = window.getSelection().toString();
  539.     } else if (document.selection && document.selection.type != "Control") {
  540.         text = document.selection.createRange().text;
  541.     }
  542.     return text;
  543. }
  544.  
  545. var postQuote = function(){
  546.     $('.post_data > [data-function=quote]').each(function(index,currentPost) {
  547.         if ($(currentPost).data("quotable") != "true"){
  548.             $(this).removeAttr("data-function"); // Disable native quote function
  549.             $(this).on("click", function(e){
  550.                 if (!e.originalEvent.ctrlKey && e.which == 1){
  551.                     e.preventDefault();
  552.                     var postnum = $(this)["0"].innerHTML;
  553.                     var input = document.getElementById('reply_chennodiscursus')
  554.  
  555.                     if (input.selectionStart != undefined)
  556.                     {
  557.                         var startPos = input.selectionStart;
  558.                         var endPos = input.selectionEnd;
  559.                         var startText = input.value.substring(0, startPos);
  560.                         var endText = input.value.substring(startPos);
  561.  
  562.                         var originalText = input.value;
  563.                         var selectedText = getSelectionText();
  564.                         if (selectedText == ""){
  565.                             var newText = startText +">>"+postnum+"\n"+ endText;
  566.                         }else{
  567.                             var newText = startText +">>"+postnum+"\n>"+ selectedText +"\n"+ endText;
  568.                         }
  569.                         document.getElementById('reply_chennodiscursus').value = originalText.replace(originalText,newText);
  570.                     }
  571.                 }
  572.             });
  573.             $(currentPost).data("quotable","true");
  574.         }
  575.     });
  576. };
  577.  
  578. var hidePosts = function()
  579. {
  580.     $('.pull-left').each(function(index, currentPost) {
  581.         if ($(currentPost).hasClass('stub')) {
  582.             $(currentPost).removeClass('stub')
  583.         }
  584.     });
  585. }
  586.  
  587. var filter = function(){
  588.     var sieveStrT0 = new RegExp("\\b("+filteredStringsT0.join("|")+")\\b"); // \b or (^|\s) works
  589.     var sieveStrT1 = new RegExp("\\b("+filteredStringsT1.join("|")+")\\b","i"); // \b or (^|\s) works
  590.     var sieveStrT2 = new RegExp("(^|\\s)("+filteredStringsT2.join("|")+")($|\\s)","i");
  591.     var sieveTrip = new RegExp("("+filteredTrips.join("|")+")");
  592.     var sieveName = new RegExp("("+filteredNames.join("|")+")");
  593.  
  594.     $('article.post').each(function(index,currentPost) {
  595.         if ($(currentPost).data("filtered") != "true"){
  596.             $(currentPost).data("filtered","true");
  597.             var postText = $(this).find('.text').elemText();
  598.             if (sieveTrip.test($(this).find('.post_tripcode').text()) || sieveName.test($(this).find('.post_author').text())){
  599.                 shitpostT2(currentPost, postText);
  600.             }else if(sieveStrT0.test(postText)){
  601.                 //console.log(postText.match(sieveStrT0));
  602.                 shitpostT0(currentPost, postText);
  603.             }else if (postText.length <= filterCharThreshold){
  604.                 if (sieveStrT1.test(postText)){
  605.                     //console.log(postText.match(sieveStrT1));
  606.                     shitpostT1(currentPost, postText);
  607.                 } else if (sieveStrT2.test(postText)){
  608.                     //console.log(postText.match(sieveStrT2));
  609.                     shitpostT2(currentPost, postText);
  610.                 }
  611.             }
  612.         }
  613.     });
  614. }
  615. function shitpostT0(post, postText){
  616.     $(post).addClass("shitpost");
  617. }
  618. function shitpostT1(post, postText){
  619.     $(post).addClass("shitpost");
  620. }
  621. function shitpostT2(post, postText){
  622.     $(post).removeClass('stub');
  623.     $(post).find('.pull-left').removeClass('stub');
  624.     var docID = $(post).find('.pull-left > button').attr("data-doc-id");
  625.     $('.doc_id_'+docID).hide();
  626.     $('.stub_doc_id_'+docID).show();
  627. }
  628.  
  629. var embedImages = function() {
  630.     $('.posts article').each(function(index, currentArticle){
  631.         if ($(currentArticle).data('imgEmbed') != 'true'){
  632.             var patt = new RegExp("http[s]?://("+imgSites+")/[^\"]*");
  633.             var imgNum = imgNumMaster - $(currentArticle).find('.thread_image_box').length;
  634.             $(currentArticle).find(".text > a, .text > .spoiler, .text > strong").each(function(index, currentLink){
  635.                 if (imgNum == 0) {
  636.                     return false;
  637.                 }
  638.                 var imglink = patt.exec($(this).html());
  639.                 if (imglink !== null){
  640.                     imgNum--;
  641.                     // var patt2 = new RegExp(escapeRegExp(imglink["0"]), 'g'); Can't see what this does, uncomment if things break again
  642.                     imglink["0"] = imglink["0"].replace(/.gifv/g, ".webm"); // Only tested to work with Imgur
  643.                     var filename = '<div class="post_file embedded_post_file"><a href="'+imglink["0"]+'" class="post_file_filename" rel="tooltip" title="'+imglink["0"]+'">'+imglink["0"].match(/[^\/]*/g)[imglink["0"].match(/[^\/]*/g).length -2]+'</a></div>';
  644.                     var filestats = ""; //'<br><span class="post_file_metadata"> 937KiB, '+imglink["0"].naturalWidth+'x'+imglink["0"].naturalHeight+'</span>';
  645.                     if ((/.webm/g).test(imglink["0"])){
  646.                         console.log(imglink["0"]);
  647.                         $(currentArticle).find(".post_wrapper").prepend('<div class="thread_image_box"></div>');
  648.                         $(currentArticle).find(".thread_image_box:first-child").html(filename+'<video width="125" style="float:left" name="media" loop muted '+autoplayVid+'><source src="'+imglink["0"]+'" type="video/webm"></video>'+filestats);
  649.                     }else if ($(this).hasClass("spoiler")){
  650.                         $(currentArticle).find(".post_wrapper").prepend('<div class="thread_image_box">'+filename+'<a href="'+imglink["0"]+'" target="_blank" rel="noreferrer" class="thread_image_link"><div class="spoilerText">Spoiler</div><img src="'+imglink["0"]+'" class="lazyload post_image spoilerImage smallImage"></a>'+filestats+'</div>');
  651.                     }else{
  652.                         $(currentArticle).find(".post_wrapper").prepend('<div class="thread_image_box">'+filename+'<a href="'+imglink["0"]+'" target="_blank" rel="noreferrer" class="thread_image_link"><img src="'+imglink["0"]+'" class="lazyload post_image smallImage"></a>'+filestats+'</div>');
  653.                     }
  654.                     $(this).remove();
  655.                 }
  656.             });
  657.             $(currentArticle).data('imgEmbed', 'true');
  658.         }
  659.     });
  660. }
  661.  
  662. var seenPosts = function(){$('article').each(function(index, currentArticle){$(currentArticle).data('seen','true')});}
  663.  
  664. var newPosts = function() {
  665.     $('article').each(function(index, currentArticle){
  666.         if ($(currentArticle).data('seen') != 'true')
  667.         {
  668.             $(currentArticle).data('seen', 'true')
  669.             newPostCount +=1
  670.         }
  671.     });
  672.  
  673.     if (windowFocus == true){
  674.         newPostCount = 0;
  675.         $('#favicon').attr("href","http://i.imgur.com/xuadeJ2.png");
  676.     }
  677.     if (newPostCount > 0){
  678.         $('#favicon').attr("href",favicon);
  679.     }
  680.     document.title = "(" + newPostCount + ") " + DocumentTitle;
  681. }
  682.  
  683. var postCounter = function() {$(".rules_box").html("<h6>Posts: " + $('.post_wrapper').length + "/400 <br> Images: " + $(".thread_image_box").length + "/250</h6>" + rulesBox)}
  684.  
  685. var bindShortcuts = function()
  686. {
  687.  
  688. }
  689.  
  690. var pokemon = ["bulbasaur","ivysaur","venusaur","charmander","charmeleon","charizard","squirtle","wartortle","blastoise","caterpie","metapod","butterfree","weedle","kakuna","beedrill","pidgey","pidgeotto","pidgeot","rattata","raticate","spearow","fearow","ekans","arbok","pikachu","raichu","sandshrew","sandslash","nidoran♀","nidorina","nidoqueen","nidoran♂","nidorino","nidoking","clefairy","clefable","vulpix","ninetales","jigglypuff","wigglytuff","zubat","golbat","oddish","gloom","vileplume","paras","parasect","venonat","venomoth","diglett","dugtrio","meowth","persian","psyduck","golduck","mankey","primeape","growlithe","arcanine","poliwag","poliwhirl","poliwrath","abra","kadabra","alakazam","machop","machoke","machamp","bellsprout","weepinbell","victreebel","tentacool","tentacruel","geodude","graveler","golem","ponyta","rapidash","slowpoke","slowbro","magnemite","magneton","farfetch'd","doduo","dodrio","seel","dewgong","grimer","muk","shellder","cloyster","gastly","haunter","gengar","onix","drowzee","hypno","krabby","kingler","voltorb","electrode","exeggcute","exeggutor","cubone","marowak","hitmonlee","hitmonchan","lickitung","koffing","weezing","rhyhorn","rhydon","chansey","tangela","kangaskhan","horsea","seadra","goldeen","seaking","staryu","starmie","mr. mime","scyther","jynx","electabuzz","magmar","pinsir","tauros","magikarp","gyarados","lapras","ditto","eevee","vaporeon","jolteon","flareon","porygon","omanyte","omastar","kabuto","kabutops","aerodactyl","snorlax","articuno","zapdos","moltres","dratini","dragonair","dragonite","mewtwo","mew","chikorita","bayleef","meganium","cyndaquil","quilava","typhlosion","totodile","croconaw","feraligatr","sentret","furret","hoothoot","noctowl","ledyba","ledian","spinarak","ariados","crobat","chinchou","lanturn","pichu","cleffa","igglybuff","togepi","togetic","natu","xatu","mareep","flaaffy","ampharos","bellossom","marill","azumarill","sudowoodo","politoed","hoppip","skiploom","jumpluff","aipom","sunkern","sunflora","yanma","wooper","quagsire","espeon","umbreon","murkrow","slowking","misdreavus","unown","wobbuffet","girafarig","pineco","forretress","dunsparce","gligar","steelix","snubbull","granbull","qwilfish","scizor","shuckle","heracross","sneasel","teddiursa","ursaring","slugma","magcargo","swinub","piloswine","corsola","remoraid","octillery","delibird","mantine","skarmory","houndour","houndoom","kingdra","phanpy","donphan","porygon2","stantler","smeargle","tyrogue","hitmontop","smoochum","elekid","magby","miltank","blissey","raikou","entei","suicune","larvitar","pupitar","tyranitar","lugia","ho-oh","celebi","treecko","grovyle","sceptile","torchic","combusken","blaziken","mudkip","marshtomp","swampert","poochyena","mightyena","zigzagoon","linoone","wurmple","silcoon","beautifly","cascoon","dustox","lotad","lombre","ludicolo","seedot","nuzleaf","shiftry","taillow","swellow","wingull","pelipper","ralts","kirlia","gardevoir","surskit","masquerain","shroomish","breloom","slakoth","vigoroth","slaking","nincada","ninjask","shedinja","whismur","loudred","exploud","makuhita","hariyama","azurill","nosepass","skitty","delcatty","sableye","mawile","aron","lairon","aggron","meditite","medicham","electrike","manectric","plusle","minun","volbeat","illumise","roselia","gulpin","swalot","carvanha","sharpedo","wailmer","wailord","numel","camerupt","torkoal","spoink","grumpig","spinda","trapinch","vibrava","flygon","cacnea","cacturne","swablu","altaria","zangoose","seviper","lunatone","solrock","barboach","whiscash","corphish","crawdaunt","baltoy","claydol","lileep","cradily","anorith","armaldo","feebas","milotic","castform","kecleon","shuppet","banette","duskull","dusclops","tropius","chimecho","absol","wynaut","snorunt","glalie","spheal","sealeo","walrein","clamperl","huntail","gorebyss","relicanth","luvdisc","bagon","shelgon","salamence","beldum","metang","metagross","regirock","regice","registeel","latias","latios","kyogre","groudon","rayquaza","jirachi","deoxys","turtwig","grotle","torterra","chimchar","monferno","infernape","piplup","prinplup","empoleon","starly","staravia","staraptor","bidoof","bibarel","kricketot","kricketune","shinx","luxio","luxray","budew","roserade","cranidos","rampardos","shieldon","bastiodon","burmy","wormadam","mothim","combee","vespiquen","pachirisu","buizel","floatzel","cherubi","cherrim","shellos","gastrodon","ambipom","drifloon","drifblim","buneary","lopunny","mismagius","honchkrow","glameow","purugly","chingling","stunky","skuntank","bronzor","bronzong","bonsly","mime jr.","happiny","chatot","spiritomb","gible","gabite","garchomp","munchlax","riolu","lucario","hippopotas","hippowdon","skorupi","drapion","croagunk","toxicroak","carnivine","finneon","lumineon","mantyke","snover","abomasnow","weavile","magnezone","lickilicky","rhyperior","tangrowth","electivire","magmortar","togekiss","yanmega","leafeon","glaceon","gliscor","mamoswine","porygon-z","gallade","probopass","dusknoir","froslass","rotom","uxie","mesprit","azelf","dialga","palkia","heatran","regigigas","giratina","cresselia","phione","manaphy","darkrai","shaymin","arceus","victini","snivy","servine","serperior","tepig","pignite","emboar","oshawott","dewott","samurott","patrat","watchog","lillipup","herdier","stoutland","purrloin","liepard","pansage","simisage","pansear","simisear","panpour","simipour","munna","musharna","pidove","tranquill","unfezant","blitzle","zebstrika","roggenrola","boldore","gigalith","woobat","swoobat","drilbur","excadrill","audino","timburr","gurdurr","conkeldurr","tympole","palpitoad","seismitoad","throh","sawk","sewaddle","swadloon","leavanny","venipede","whirlipede","scolipede","cottonee","whimsicott","petilil","lilligant","basculin","sandile","krokorok","krookodile","darumaka","darmanitan","maractus","dwebble","crustle","scraggy","scrafty","sigilyph","yamask","cofagrigus","tirtouga","carracosta","archen","archeops","trubbish","garbodor","zorua","zoroark","minccino","cinccino","gothita","gothorita","gothitelle","solosis","duosion","reuniclus","ducklett","swanna","vanillite","vanillish","vanilluxe","deerling","sawsbuck","emolga","karrablast","escavalier","foongus","amoonguss","frillish","jellicent","alomomola","joltik","galvantula","ferroseed","ferrothorn","klink","klang","klinklang","tynamo","eelektrik","eelektross","elgyem","beheeyem","litwick","lampent","chandelure","axew","fraxure","haxorus","cubchoo","beartic","cryogonal","shelmet","accelgor","stunfisk","mienfoo","mienshao","druddigon","golett","golurk","pawniard","bisharp","bouffalant","rufflet","braviary","vullaby","mandibuzz","heatmor","durant","deino","zweilous","hydreigon","larvesta","volcarona","cobalion","terrakion","virizion","tornadus","thundurus","reshiram","zekrom","landorus","kyurem","keldeo","meloetta","genesect","chespin","quilladin","chesnaught","fennekin","braixen","delphox","froakie","frogadier","greninja","bunnelby","diggersby","fletchling","fletchinder","talonflame","scatterbug","spewpa","vivillon","litleo","pyroar","flabébé","floette","florges","skiddo","gogoat","pancham","pangoro","furfrou","espurr","meowstic","honedge","doublade","aegislash","spritzee","aromatisse","swirlix","slurpuff","inkay","malamar","binacle","barbaracle","skrelp","dragalge","clauncher","clawitzer","helioptile","heliolisk","tyrunt","tyrantrum","amaura","aurorus","sylveon","hawlucha","dedenne","carbink","goomy","sliggoo","goodra","klefki","phantump","trevenant","pumpkaboo","gourgeist","bergmite","avalugg","noibat","noivern","xerneas","yveltal","zygarde","diancie","hoopa","volcanion"];
  691. function notifyMe(title, image, body){
  692.     if (!Notification){
  693.         alert('Please us a modern version of Chrome, Firefox, Opera or Firefox.');
  694.         return;
  695.     }
  696.  
  697.     if (Notification.permission !== "granted")
  698.         Notification.requestPermission();
  699.     var icon = image;
  700.     if(!Math.floor(Math.random()*8192)){
  701.         var ND = Math.floor(Math.random()*720);
  702.         icon = "http://img.pokemondb.net/sprites/black-white/shiny/"+pokemon[ND]+".png";
  703.     }
  704.  
  705.     var notification = new Notification(title, {
  706.         icon: icon,
  707.         body: body
  708.     });
  709.  
  710.     notification.onshow = function (){
  711.         setTimeout(notification.close.bind(notification), 5000);
  712.     }
  713.     notification.onclick = function (){
  714.         window.focus();
  715.     }
  716. }
  717.  
  718. if (features.labelYourPosts){
  719.     var yourPosts = localStorage.yourPosts;
  720.     if (yourPosts == undefined){
  721.         yourPosts = {};
  722.         console.log("Created post archive for the first time");
  723.     } else {
  724.         yourPosts = JSON.parse(localStorage.yourPosts);
  725.     }
  726.     window.addEventListener("beforeunload", function (e) {
  727.         if (localStorage.yourPosts == undefined){
  728.             localStorage.yourPosts = JSON.stringify(yourPosts);
  729.         } else {
  730.             localStorage.yourPosts = JSON.stringify($.extend(true, yourPosts, JSON.parse(localStorage.yourPosts)));
  731.         }
  732.         //var confirmationMessage = "\o/";
  733.  
  734.         //(e || window.event).returnValue = confirmationMessage; //Gecko + IE
  735.         //return confirmationMessage;                            //Webkit, Safari, Chrome
  736.     });
  737. }
  738.  
  739. function labelYourPosts(firstcall){
  740.     $.each(queuedYouLabels, function(i, v){ // Parse all names on pageload and with each post submission
  741.         $('#'+v+' .post_author').after('<span> (You)</span>');
  742.     });
  743.     queuedYouLabels = [];
  744.  
  745.     if (firstcall){ // Parse all backlinks present on pageload
  746.         $.each(yourPosts[threadID], function(i,v){
  747.             $('.backlink[data-post='+v+']').each(function(){
  748.                 if ($(this).data('linkedYou') != 'true'){
  749.                     this.textContent += ' (You)';
  750.                     $(this).data('linkedYou','true');
  751.                 }
  752.             });
  753.         });
  754.     }
  755. }
  756.  
  757. function labelNewPosts(response){
  758.     var newPosts = Object.keys(response[threadID]["posts"]);
  759.     $.each(newPosts, function(i,v){ // For each post returned by update
  760.         var notificationTriggered = false;
  761.         $('#'+v+' .greentext > a').each(function(i, link){ // For each post content backlink
  762.             var linkID = $(link).attr('data-post');
  763.             if ($.inArray(linkID, yourPosts[threadID])+1){ // If the link points to your post
  764.                 if (!notificationTriggered){
  765.                     notifyMe($('#'+v+' .post_poster_data').text().trim()+" replied to you","http://i.imgur.com/HTcKk4Y.png",$('#'+v+' .text').text().trim());
  766.                     notificationTriggered = true;
  767.                 }
  768.                 link.textContent += ' (You)'; // Designate the link as such
  769.             }
  770.             if ($.inArray(v, yourPosts[threadID])+1){ // If the post is your own
  771.                 var backlink = $('#'+linkID+' .post_backlink [data-post='+v+']');
  772.                 if (backlink.data('linkedYou') != 'true'){
  773.                     backlink[0].textContent += ' (You)'; // Find your post's new reply backlink and designate it too
  774.                     backlink.data('linkedYou','true');
  775.                 }
  776.             }
  777.         });
  778.     });
  779. }
  780.  
  781. var lastSubmittedContent;
  782.  
  783. function postSubmitEvent(){
  784.     if ($('#reply [type=submit]').length){
  785.         window.MutationObserver = window.MutationObserver
  786.         || window.WebKitMutationObserver
  787.         || window.MozMutationObserver;
  788.         var target =  $('#reply [type=submit]')["0"],
  789.             observer = new MutationObserver(function(mutation) {
  790.                 //console.log("Post Submit Event Triggered");
  791.                 lastSubmittedContent = $('#reply_chennodiscursus')[0].value;
  792.             }),
  793.             config = {
  794.                 attributes: true
  795.             };
  796.         observer.observe(target, config);
  797.     }
  798. }
  799.  
  800. $(document).ready(function(){
  801.     $('head').after('<script src="https://cdn.rawgit.com/madapaja/jquery.selection/master/src/jquery.selection.js"></script>'); // Pull in selection plugin (http://madapaja.github.io/jquery.selection/)
  802.     $('head').after('<style type="text/css" id="FoolX-css">.bigImage{opacity: 1!important; max-width:100%;}.smallImage{max-width:125px; max-height:125px}.smallImageOP{max-width:250px; max-height:250px}.spoilerImage{opacity: 0.1}.spoilerText{position: relative; height: 0px; font-size: 19px; top: 47px;}.forwarded{display:none}.inline{border:1px solid; display: table; margin: 2px 0;}.inlined{opacity:0.5}.post_wrapper{border-right: 1px solid #cccccc;}.post_wrapperInline{border-right:0!important; border-bottom:0!important;}.quickReply{position: fixed; top: 0; right: 0; margin: 3px !important;}.shitpost{opacity: 0.3}.embedded_post_file{margin: 0!important; width: 125px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}</style>');
  803.     $('head').append('<link id="favicon" rel="shortcut icon" type="image/png" href="http://i.imgur.com/xuadeJ2.png">');
  804.     windowFocus = true
  805.     $(window).focus(function(){windowFocus = true; ThreadUpdate(features)})
  806.     $(window).blur(function(){windowFocus = false})
  807.     if (hideQROptions){
  808.         $('#reply').toggleClass("showQROptions"); // Make options hidden in QR by default
  809.     }
  810.     if (features.labelYourPosts){
  811.         threadID = $('#main > article[data-thread-num]').attr('id');
  812.         if (yourPosts[threadID] == undefined){
  813.             yourPosts[threadID] = [];
  814.         } else {
  815.             queuedYouLabels = yourPosts[threadID].slice(0);
  816.             //console.log(queuedYouLabels);
  817.         }
  818.         //console.log(yourPosts);
  819.         postSubmitEvent();
  820.  
  821.         $(document).ajaxComplete(function(event, request, settings) {
  822.             //console.log(event);
  823.             //console.log(request);
  824.             //console.log(settings);
  825.             if (request.responseText != ""){
  826.                 response = JSON.parse(request.responseText);
  827.             }else{
  828.                 response = {"error":"No responseText"};
  829.             }
  830.             //console.log(response);
  831.             if (response.error != undefined){
  832.                 console.log(response.error);
  833.             }else{
  834.                 if (settings.type == "POST"){
  835.                     if (response.error == undefined ){
  836.                         for (var post in response[threadID]["posts"]) {
  837.                             //console.log(lastSubmittedContent);                    
  838.                             if(response[threadID]["posts"][post]["comment"].replace(/[\r\n]/g,'') == lastSubmittedContent.replace(/[\r\n]/g,'')){
  839.                                 yourPosts[threadID].push(post);
  840.                                 queuedYouLabels.push(post);
  841.                                 //console.log(yourPosts);
  842.                                 //console.log(queuedYouLabels);
  843.                                 labelYourPosts();
  844.                                 break;
  845.                             }
  846.                         }
  847.                         labelNewPosts(response);
  848.                     }else{
  849.                         console.log(response.error);
  850.                     }
  851.                 }else{
  852.                     if (response[threadID] != undefined){
  853.                         labelNewPosts(response);
  854.                     }else{
  855.                         console.log("Not in a thread");
  856.                     }
  857.                 }
  858.             }
  859.         });
  860.         labelYourPosts(true); // First call, add (You) to page content
  861.     }
  862. });
  863.  
  864. var executeShortcut = function(shortcut) {
  865.     //console.log(shortcut);
  866.     var input = document.getElementById('reply_chennodiscursus');
  867.  
  868.     if (input.selectionStart != undefined){
  869.         $('#reply_chennodiscursus').selection('insert', {
  870.             text: "["+shortcut+"]",
  871.             mode: 'before'
  872.         });
  873.         $('#reply_chennodiscursus').selection('insert', {
  874.             text: "[/"+shortcut+"]",
  875.             mode: 'after'
  876.         });
  877.     }
  878. };
  879.  
  880. function quickReply(){
  881.     $('#reply').toggleClass("quickReply");
  882.     $('#reply fieldset > div:nth-child(1)').css("width","");
  883.     if ($('#reply').hasClass("showQROptions")){
  884.         $('#reply fieldset > div:nth-child(2)').toggle();
  885.     }
  886. }
  887.  
  888. function quickReplyOptions(){
  889.     $('#reply').toggleClass("showQROptions");
  890.     $('#reply.quickReply fieldset > div:nth-child(2)').toggle();
  891. }
  892.  
  893. $(function(){
  894.     shortcut.add("ctrl+s", function(){ executeShortcut("spoiler")});
  895.     shortcut.add("ctrl+i", function(){ executeShortcut("i")});
  896.     shortcut.add("ctrl+b", function(){ executeShortcut("b")});
  897.     shortcut.add("ctrl+u", function(){ executeShortcut("u")});
  898.     shortcut.add("q", function(){quickReply()}, {"disable_in_input":true});
  899.     shortcut.add("ctrl+q", function(){quickReplyOptions()}, {"disable_in_input":false});
  900.  
  901.     seenPosts();
  902.     ThreadUpdate(features);
  903.     getBoard();
  904.     bindShortcuts();
  905.     window.setInterval( function(){ ThreadUpdate(features); }, 500 );
  906. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement