Joeviocoe / Facebook Fix

// ==UserScript==
// @name         Facebook Fix
// @namespace
// @version      2.7.3
// @description  Fix Ads, Links and Display of Facebook.
// @include      http://www.facebook.com/*
// @include      https://www.facebook.com/*
// @grant        GM_addStyle
// @require      https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
// @updateURL    https://openuserjs.org/install/Joeviocoe/Facebook_Fix.user.js
// @downloadURL  https://openuserjs.org/install/Joeviocoe/Facebook_Fix.user.js
// @icon         https://www.google.com/s2/favicons?domain=www.facebook.com
// @copyright    2018+, Joeviocoe
// @license      MIT
// @noframes
// ==/UserScript==
// Copyright (c) 2018, Joeviocoe
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
// * Neither the name of Joeviocoe nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
/*jslint browser: true*/
/*global $, jQuery, alert*/

function Remove_Ads() {
    $('#rightCol').children('*').remove();
    //$('div[data-ownerid*="hyperfeed_story"]').remove();
    $('div:contains("Products shown:")').parents('div.mtm').remove();
    $('#stories_pagelet_below_composer').remove();

    var classes = [];
    if ( $('style:contains("Sponsored")').length > 0 ) {
        var sponsored = (' ' + $('style:contains("Sponsored")').get(0).innerHTML).split(' .');
        for ( var i = 1; i < sponsored.length; i++ ) { classes.push('.' + sponsored[i].split(':')[0]); }
    }
    if ( $('link[href*="font-size:0"]').length > 0 ) {
        classes.push('.' + $('link[href*="font-size:0"]').get(0).href.split("{font-size:0")[0].split(".").pop());
    }
    var Ads = [];
    if ( classes.length > 0 ) { Ads.push( $(classes.join(", ")) ); }
    Ads.push( $('a:contains("Sponsored")') );
    Ads.push( $('div[title="Page Stories You May Like"]') );
    Ads.push( $('div[data-ft*="quick_promotion"]') );
    Ads.push( $('div' ).filter(function(index) {return $(this).text().match(/^Related$|^Suggested Shows|^Suggested for You/);}) );
    Ads.push( $('span').filter(function(index) {return $(this).text().match(/^More From Related Pages$|^ Facebook $|^Connect With Facebook$|^People You May Know$/);}) );

    for ( var j = 0; j < Ads.length; j++ ) {
        for ( var k = 0; k < Ads[j].length; k++ ) {
            if ( Ads[j].length > 0 ) {
                var Ad_Post = $( Ads[j].parents('div[data-testid="fbfeed_story"]') );
                var AD_Text = Ads[j][k].innerText.split('\n')[0];
                try {
                    var Ad_Title = Ad_Post.find('a[data-hovercard*="/ajax/hovercard/page.php"]').get(0).innerHTML.split('aria-label="')[1].split('"')[0];
                    console.log('Facebook Fix:  Removing Sponsored Content from ' + Ad_Title);
                } catch(e) {}
                if ( AD_Text.length > 1 ) {
                    console.log('Facebook Fix:  Removing Facebook Content \"' + AD_Text + '\"');
                }
                Ad_Post.remove();
            }
        }
    }
}

function Fix_Links() {
    $('div.userContentWrapper').find('div.hidden_elem').removeClass('hidden_elem');
    $('div.userContentWrapper').find('div.ellipsis').css('padding-top','2px');
    $('a[data-gt*="home_chrome"]').attr("href","/?sk=h_chr");
    var links = $('a[href*="l.php?u="],a[href*="?fbclid="],a[href*="?igshid="],[onmousedown],[data-lynx-mode],[data-lynx-uri]');
    if ( links.length > 1 ) {
        //console.log("Facebook Fix:  Removing redirects on " + ( links.length ) + " URLs");
        for ( var i = 0; i < links.length; i++ ) {
            var link = links[i];
            if (link.hasAttribute("onmousedown") || link.hasAttribute("data-lynx-mode")) {
                link.removeAttribute("onmousedown");
                link.removeAttribute("data-lynx-mode");
                link.removeAttribute("data-lynx-uri");
                if (link.removeEventListener) {
                    link.removeEventListener("mousedown", link.onmousedown, false);
                } else if(link.detachEvent) {
                    link.detachEvent("onmousedown", link.onmousedown);
                }
            }
            if (link.href.indexOf("igshid=") > -1) {
                link.setAttribute("href",decodeURIComponent(link.href).split("?igshid=")[0]);
            }
            if (link.href.indexOf("fbclid=") > -1) {
                link.setAttribute("href",decodeURIComponent(link.href).split("?fbclid=")[0]);
            }
            if (link.href.indexOf("attribution_link") > -1) {
                console.log(link.href);
                link.setAttribute("href","https://www.youtube.com/watch?v=" + decodeURIComponent(decodeURIComponent(link.href)).split("?v=")[1].split("&feature=")[0]);
            }
            if (link.href.indexOf("l.php?u=") > -1) {
                link.setAttribute("href","http" + decodeURIComponent(link.href).split("http").slice(-1)[0].split('&')[0]);
            }
        }
    }
}

function Fix_Gifs() {
    var thumbgifs = $('[data-video-width="40"][data-video-height="40"]');
    if ( thumbgifs.length > 0 ) {
        for ( var j = 0; j < thumbgifs.length; j++ ) {
            thumbgifs[j].remove();
        }
        thumbimgs = document.querySelectorAll('[class="_m54 _1jto _3htz hidden_elem"]');
        for ( var k = 0; k < thumbimgs.length; k++ ) {
            thumbimgs[k].replaceWith("", thumbimgs[k].firstChild);
        }
    }
}

function Fix_Search(t) {
    if ( t == "on" ) { $('div[class="hidden_elem"]').attr('searchable','1').removeClass('hidden_elem'); }
    if ( t == "off" ) { $('div[searchable=1]').removeAttr('searchable').addClass('hidden_elem'); }
}

function Fix_Display() {
    // Wide Screen
    $('#globalContainer').css("cssText","margin-left: 20px !important;");
    $('#contentArea').css("cssText", "width: 125% !important; right: 0px !important;");
    $('#recent_capsule_container').css("cssText", "width: 75% !important;");

    // BannerTextPost Removal
    $('span._4a6n._a5_[cl!="1"]').each(function() {
        $(this).appendTo( $(this).parents('div.userContent') );
        $(this).attr("cl","1").css("cssText", "color: black; visibility: visible; font-size: 15px");
        $('div._5qxm').remove();
    });

    // Viewport Check
    $.fn.isInViewport = function() {
        var elementTop = $(this).offset().top;
        var elementBottom = elementTop + $(this).outerHeight();
        var viewportTop = $(window).scrollTop();
        var viewportBottom = viewportTop + $(window).height();
        return elementBottom > viewportTop && elementTop < viewportBottom;
    };

    // Zoom Images and Video
    $('.zoomed').each(function(){
        if ( ! $(this).isInViewport() ) {
            $(this).siblings('input.z-slider').attr("value",1).val(0);
            $(this).css("transform","scale(1)").css('z-index','');
        }
    });

    var hoverTimeOut, hoverTimeIn;
    var post_element = $('video[zoomable!=1],img[width!="16"][zoomable!=1]').attr('zoomable',1).parents('div[class="mtm"]');
    var presentation = $('video').parents('div[role="presentation"]').parent('div[zoomable!=1]').attr('zoomable',1);

    var slider1 = $("<input class='z-slider1' min='1' max='2.5' step='0.025' type='range' value='1' " +
                       "style='transform: rotate(-90deg); transform-origin: top left;; -moz-appearance: scrollbar-horizontal; width: 100px; height: 15px;' " +
                     "/>").appendTo(post_element);
    slider1.siblings('div').css('margin-inline-start','50px');
    $('.z-slider1').on("input", function() {
        var elem = $(this).siblings('div').css('position','relative').css('z-index','99999').addClass('zoomed');
        var value = $(this).val();
        elem.css("transform-origin","bottom left");
        elem.css("transform","scale("+value+")");
    });

    var slider2 = $("<input class='z-slider2' min='1' max='3' step='0.025' type='range' value='2' " +
                       "style='-moz-appearance: scrollbar-horizontal; width: 100px; height: 15px;' " +
                     "/>").appendTo(presentation);
    slider2.parent('div').css("transform-origin","top right").css("transform","scale(2)");
    $('.z-slider2').on("change", function() {
        var elem = $(this).parent('div');
        var value = $(this).val();
        elem.css("transform","scale("+value+")");
    });
}

function run() {
    Remove_Ads();
    Fix_Links();
    Fix_Gifs();
    Fix_Display();
}

setTimeout( function() {
    console.clear();
    window.addEventListener('click', function() {
        if ( counter === 0 ) {
            setTimeout (function() { run(); counter = 0; }, 500);
        }
        counter++;
    });
    window.addEventListener('scroll', function() {
        if ( counter === 0 ) {
            setTimeout (function() { run(); counter = 0; }, 500);
        }
        counter++;
    });
    window.addEventListener("keydown",function (e) {
        if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) { Fix_Search('on'); }
        if (e.keyCode === 27) { Fix_Search('off'); }
    });

    var counter = 0;
    run();
},200);