RageNugget / teil0r

// ==UserScript==
// @copyright 2018, RageNugget (https://openuserjs.org//users/RageNugget)
// @license MIT
// @name         teil0r
// @namespace    http://tampermonkey.net/
// @version      0.5
// @description  try to take over the world!
// @author       me
// @match        https://pr0gramm.com/*
// @match        http://pr0gramm.com/*
// @grant        GM_addStyle
// @require      https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js
// @require      http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js
// @require      https://raw.githubusercontent.com/js-cookie/js-cookie/master/src/js.cookie.js
// ==/UserScript==


(function() {
    'use strict';

    var websocketHost = '';
    var pr0grammSock;
    var pr0grammStomp;
    var container;
    var streamObserver;

    // wait for page build up
    $(document).ready(function(){
        setTimeout(teil0rInit, 1000);
    });

    function appendTeil0rBar(){
       container = createContainer();
    }

    function teil0rn(){
        var data ={
            'url': $('a[class="time"]').attr('href'),
            'thumb': $('.item-image-actual').attr('src').replace('//vid','//thumb').replace('//img','//thumb').replace('.mp4','.jpg').replace('.gif','.jpg').replace('.png','.jpg')
        };

        pr0grammStomp.send("/stomp/Pr0grammLink/send", {}, JSON.stringify(data));
        teilTriggerIndicator();
    }

    function les0rn(msg){
        var data = JSON.parse(msg);

        var autojump = false;
        var playSound = $('#playSound').is(':checked');

        if(data.length == 1 && $('#autoGoto').is(':checked')){
            autojump = true;
        }

        $.each(data,function(idx,item){
            var link = $('<a/>', {'class': 'silent thumb share', 'href': item.url, 'target': '_blank', 'id': 'share-item-'+item.url.replace('/new/','')});
            var img = $('<img>',{'src':item.thumb});
            img.addClass('teilThumbImg');

            link.prepend(img);
            link.addClass('teilThumb');
            link.hover(function(){
                link.addClass('noOutline');
            });

            //bind to page functionality
            link.click(thumbClick);

            container.prepend(link);
            link.show("scale",{}, 500);

            if(autojump){
                //check if img is already open, otherwise click link
                if(!( $('.item-image').prop('src').indexOf(item.thumb.replace('//thumb.','')) > -1 )){
                    link.click();
                }
            }

            if(playSound)
            {
                $('#notiSound').get(0).play();
            }
        });
    }

    function thumbClick(ev){
        var el=$('#'+$(ev.currentTarget)[0].id.replace('share-',''));
        if(el.length>0){
            ev.preventDefault();

             //check if img is already open, otherwise click link
            if($('.item-image').prop('src') && $('.item-image').prop('src').replace('mp4','jpg').indexOf(el.find('img').prop('src').replace('//thumb','').replace('https:','')) >= 0)
            {
                return;
            }

           el[0].click();

            setTimeout(function(){
                var offset = $(el[0]).offset();
                $('html,body').animate({scrollTop:offset.top+78,scrollLeft:offset.left});

                setTimeout(function(){
                    var offset = $(el[0]).offset();
                    $('html,body').animate({scrollTop:offset.top+78,scrollLeft:offset.left});
                },200);
            },200);
        }
    }

    function getMainViewObserver(){
        var observer = new MutationObserver(function(changes, observer){
            $.each(changes, function(index,change){
                if(change.target.id === 'main-view'){
                    if(change.addedNodes && change.addedNodes.length > 0){
                        $.each(change.addedNodes, function(index,node){
                            if(node.id == 'stream'){
                                var streamContainer = $('#stream')[0];
                                if(streamObserver){
                                    streamObserver.disconnect();
                                }
                                streamObserver = createItemContainerObserver();
                                streamObserver.observe(streamContainer,{childList: true, subtree: true});
                            }
                        });
                    }
                }
            });
        });
        observer.observe($('#main-view')[0],{childList: true, subtree: true});

        return observer;
    }

    function teil0rInit(){
        //setup websocket connection
        setupSocketStomp();

        //setup content observer
        var mainViewObserver = getMainViewObserver();

        var streamContainer = $('#stream')[0];
        if(streamContainer){
            var observer = createItemContainerObserver();
            observer.observe(streamContainer,{childList: true, subtree: true});
        }

        // register key stroke for 'r'
        $(document).keydown(function(e) {
            if (e.keyCode == 82) {
                var focused = false;
                $.each($('textarea.comment:focus'), function(index,area){
                    focused = true;
                    return;
                });
                $.each($('input.q:focus'), function(index,area){
                    focused = true;
                    return;
                });
                if(!focused){
                    teil0rn();
                }
            }
        });

        // add link to currently open content
        appendT3il0rnLink();
        appendTeil0rBar();

        //cookie
        readCookie(true);
    }

    function setupSocketStomp(){
        if(pr0grammSock)
        {
            pr0grammSock.close();
        }
        pr0grammSock = new SockJS(websocketHost);
        pr0grammStomp = Stomp.over(pr0grammSock);
        pr0grammStomp.reconnect_delay = 5000;
        pr0grammStomp.connect({},
                              function(frame) {
            pr0grammStomp.subscribe("/stomp/Pr0grammLink/recv", function(event) {
                if(event.body)
                {
                   les0rn(event.body);
                }
            });
        },function(error){
            setTimeout(setupSocketStomp,5000);
        });
    }

    function createItemContainerObserver(){
        var observer = new MutationObserver(function(changes, observer){
            $.each(changes, function(index,change){
                if(change.target.className === 'item-container'){
                    if(change.addedNodes && change.addedNodes.length > 0){
                        $.each(change.addedNodes, function(index,node){
                            if(node.className === 'item-container-content'){
                                appendT3il0rnLink();
                            }
                        });
                    }
                }
            });
        });
        return observer;
    }

    function appendT3il0rnLink(){
        var link = $('<span class="action">teil0rn</span>');
        link.click(function(event){
            teil0rn();
        });

        $('.item-details').append('[');
        $('.item-details').append(link);
        $('.item-details').append(']');
    }

    function teilTriggerIndicator(){
         if (!($('#key-indicator').length)){
            var indicator = $('<div/>').attr('id', 'key-indicator');
            $('body').append(indicator);
        }
        $('#key-indicator').stop().css('opacity', 1).toggleClass('pict', true).text('u').show().delay(500).fadeOut('fast');
    }

     function createContainer(){
        var container = $("<div></div>");
        container.id = "sharebar";
        container.addClass('teilContainer');

        var scrolly = $('<div/>');
        scrolly.addClass('scrolly');

        var audio = $('<audio/>',{'id':'notiSound', 'preload': 'auto'}).append($('<source/>',{'src': 'http://freesound.org/data/previews/13/13951_33634-lq.mp3'}));
        audio.get(0).volume = 0.2;

        var configDiv = $('<div>');
        var autoGoto = $('<input/>', {type: 'checkbox', id:'autoGoto'});
        configDiv.append(autoGoto);
        configDiv.append($('<span>').html('Autoscroll '));
        autoGoto.change(function(){saveCookie();});

        var playSound = $('<input/>', {type: 'checkbox', id:'playSound'});
        configDiv.append(playSound);
        configDiv.append($('<span>').html('Sound '));
        playSound.change(function(){saveCookie();});

        container.prepend(configDiv);
        container.prepend(audio);

        $('#page').prepend(container.append(scrolly));
        return scrolly;
    }

    function saveCookie(){
        var cookie = readCookie(false);
        cookie.autoGoto = $('#autoGoto').is(':checked');
        cookie.playSound = $('#playSound').is(':checked');
        $.cookie('teil0r',JSON.stringify(cookie));
    }

    function readCookie(update){
        var cookie = $.cookie('teil0r');
        if(!$.cookie('teil0r')){
             cookie = {autoGoto: false,playSound: false };
        }
        else{
            cookie = JSON.parse(cookie);
        }
        if(update){
            $('#autoGoto').prop('checked', cookie.autoGoto);
            $('#playSound').prop('checked', cookie.playSound);
        }
        return cookie;
    }

    GM_addStyle('.scrolly{padding-right: 15px; width: 125%; overflow:auto; height: 100%}');
    GM_addStyle('.teilContainer{width: 160px; height: 90vh;border: 1px solid #888; position: fixed; top: 52px; right: 67px; z-index: 10; padding: 11px; overflow: hidden;background-color:rgb(22, 22, 24);}');
    GM_addStyle('.teilThumbImg{width: 100%; height: 100%}');
    GM_addStyle('a.teilThumb{margin-top: 2px; outline: 2px solid #ee4d2e; display: none;}');
    GM_addStyle('a.teilThumb:hover{margin-top: 2px; outline: none;}');
    GM_addStyle('a.noOutline{outline: none;}');
})();