TSR - Freemium

Access some Subscriber/VIP functionality.

As of 2017-01-26 09:00:47 UTC. See the latest version.

// ==UserScript==
// @name        TSR - Freemium
// @description Access some Subscriber/VIP functionality.
// @namespace   The Sims Resource
// @include     http://*thesimsresource.com/*
// @include     https://*thesimsresource.com/*
// @exclude     *wiki.thesimsresource.com/*
// @exclude     *forums.thesimsresource.com/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @run-at      document-start
// @version     2.0.2r
// @grant       none
// @compatible  firefox
// @incompatible chrome Inconsistent Results
// @incompatible opera Not Tested
// @incompatible safari Not Tested
// @noframes
// ==/UserScript==

//region Handle Facebook Login Process

if(localStorage.getItem('facebook-login') === 'true'){
    localStorage.setItem('facebook-login', 'false');
    window.location = 'http://www.thesimsresource.com?cachebust=' + Math.round(new Date().getTime() / 1000);
}
else{
    if(window.location.href.indexOf('facebookLogin') > -1 || document.referrer.indexOf('facebookLogin') > -1){
        localStorage.setItem('facebook-login', 'true');
    }
}

//endregion

//region Junk

window.$.cookie = function (a, b, c) {};
window.displayAd = function (a, b, c, d, e, f, g, h, i) {};

var junkScriptSources = [

    'monetizemore',
    'pubmatic',
    'glam',
    'glm',
    'pagefair',
    'quantserve',
    'moatads',
    'google',
    'morpheus',
    'sonobi',
    'scorecardresearch',
    'analytics',
    'pq-direct',
    'cloudfront',
    'adsystem',
    'doubleclick',
    'googletagservices',
    'quant'

];
var junkInlineScripts = [

    '//Start DFP code sync DFP',
    'var forceLogout = false;',
    'var src = \'/css/merge/page/nonsubscriber.css\';',
    'if(!isVIP()) sbi_morpheus.setKeys();',
    'forceLogout || !isVIP()',
    'var gaPageName = \'\';',
    'function async_load',
    'var _qevents',
    'glam_affiliate_id',
    'window.displayAd'

];
window.addEventListener('beforescriptexecute', function(e) {

    var src = e.target.src;

    for(var j=0; j < junkInlineScripts.length; j++){
        if(e.target.innerHTML.indexOf(junkInlineScripts[j]) > -1){
            e.stopPropagation();
            e.preventDefault();
        }
    }

    for(var i = 0; i < junkScriptSources.length; i++){
        if(src.indexOf(junkScriptSources[i]) > -1){
            e.preventDefault();
            e.stopPropagation();
        }
    }

}, true);

//endregion

//region Misc Stuff
function varExists(obj){
    return typeof(obj) !== 'undefined';
}
function scrollToQuickView(){
    var ele = document.getElementsByClassName('browse-file active')[0];
    var offset = ele.offsetTop + (ele.offsetHeight);

    $("html, body").animate({scrollTop: offset}, 500);
}
function sendQuickViewRequest(id, category, quickviewElement){
    $.get('/downloads/quickview/category/' + category + '/id/' + id, function(r){

        scrollToQuickView();

        window.$(quickviewElement).html(r);
        $(quickviewElement).find('.magnific-gallery-image').magnificPopup({
            type: 'image',
            gallery: {
                enabled: true
            }
        });
        $('.flexslider').flexslider({
            animation: "slide"
        });
        window.initSmilies();
        window.initDlButtons();

    });
}
function BasketDownloader(){

    var basketDownloading = false;
    var basketItems = [];
    var basketDownloaded = null;

    function downloadBasket(completedCallback){
        basketDownloaded = completedCallback;
        if(basketDownloading){return;}
        basketDownloading = true;

        var basket = $('.basketcheckbox');
        for(var i=0; i < basket.length; i++){
            basketItems.push(basket[i].getAttribute('value'));
        }
        if(basketItems.length > 0){
            getNextBasketDownload();
        }
        else{
            //alert('No basket items.');
        }
    }

    function getNextBasketDownload(){
        if(basketItems.length > 0){
            var popped = basketItems.pop();
            window._dl(popped, null, function(url, data){
                downloadFile(url);
                removeBasketItem(popped);
                setTimeout(getNextBasketDownload, 2500);
            });
        }
        else{
            basketDownloading = false;
            if(typeof basketDownloaded === 'function'){
                basketDownloaded();
            }
            $('#md-modal').hide();
            $('.md-overlay').hide();
        }
    }

    function downloadFile(url){
        window.location.assign(url);
    }

    function removeBasketItem(id){
        $('#basketitem_' + id + ' .basketcheckbox').click();
        $('#basketRemoveSelectedBtn').click();
    }

    this.download = downloadBasket;
}
function CookieManager(){

    this.addCookie = function(id, value){
        addCookie(id, value);
    };
    this.getCookie = function(name){
        return getCookie(name);
    };

    this.updateCookies = function (cookieDictionary) {
        updateCookies(cookieDictionary);
    };

    function addCookie(id, value){

        window.document.cookie = id + '=' + value;

    }
    function getCookie(cname) {
        var name = cname + '=';
        var ca = window.document.cookie.split(';');
        for(var i = 0; i <ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) === 0) {
                return c.substring(name.length,c.length);
            }
        }
        return '';
    }
    function getCookies(){
        return window.document.cookie;
    }

    function updateCookies(cookieDictionary){

        var updates = 0;

        for(var i in cookieDictionary) {

            if(cookieDictionary.hasOwnProperty(i)) {

                if (getCookie(i) === '0' || getCookie(i) === '') {
                    messageSystem.sendMessage(userScriptName + ': [cookie-manager] Adding cookie [' + i + '].', messageType.system);
                    addCookie(i, cookieDictionary[i]);
                    updates++;
                }

            }
        }

        if(updates > 0) {
            messageSystem.sendMessage(userScriptName + ': [cookie-manager] Cookies updated. (some changes may require a reload)', messageType.system);
        }
        else{
            messageSystem.sendMessage(userScriptName + ': [cookie-manager] Cookies already set.', messageType.system);
        }

    }
}
function foSho(){
    return true;
}
//endregion

var userScriptVersion = GM_info.script.version;

var cookieManager = new CookieManager();

var firstRun = cookieManager.getCookie('FFR') !== '0';
var isUpdated = cookieManager.getCookie('FreemiumVersion') !== userScriptVersion;
var loginGenuine = cookieManager.getCookie('MemberID') != '' && cookieManager.getCookie('MemberID') != '0';
var contentItems = [
    userEscalationContent(),
    contentCleanerContent(),
    quickViewFixContent(),
    loginEnablerContent()
];

//region Content Items
function ContentItem(){

    this.name = null;
    this.canLoad = null;
    this.isLoaded = null;
    this.load = null;
    this.loadedCallback = null;
    this.sentCallback = false;

}

function userEscalationContent(){

    var contentItem = new ContentItem();

    contentItem.name = 'User Escalation';

    contentItem.canLoad = function(){
        return varExists(window.isSubscriber) && varExists(window.isVIP) && varExists(window.isLoggedIn) && varExists(window.auth_isLoggedIn);
    };
    contentItem.isLoaded = function(){
        return window.isSubscriber() === true && window.isVIP() === true && auth_isLoggedIn() === true && isLoggedIn() === true;
    };

    contentItem.load = function(){
        window.isSubscriber = foSho;
        window.isVIP = foSho;
        window.auth_isLoggedIn = foSho;
        window.isLoggedIn = foSho;
    };

    contentItem.loadedCallback = function(){

        console.log('Loaded User Escalation.');

    };

    return contentItem;
}
function quickViewFixContent(){
    var contentItem = new ContentItem();

    contentItem.name = 'Quick View Fix';

    contentItem.canLoad = function(){
        return varExists(window.doQuickView);
    };

    contentItem.load = function(){
        window.quickViewFixed = true;
        window.doQuickView = function (link, id, category) {
            if(link === true){
                return 1;
            }
            if (!isSubscriber())
                return (true);
            if (isSubscriber()) {
                if (prevLink)
                    prevLink.removeClass('active');
                var browse_file = $(link).parent().parent();
                $(browse_file).addClass('active');
                prevLink = $(browse_file);
                //console.log("QuickView(fixed)");
                //console.log($(browse_file));
                if (!$(browse_file).hasClass('browse-file')) {
                    //console.log('Browse file did not have class browse-file');
                    return;
                }
                while (browse_file.attr('data-expand-after') != '1') {
                    browse_file = browse_file.next();
                    if (!browse_file)break;
                }
                var quickviewElement = null;
                var previousQuickviewElement = null;
                var dataId = browse_file.attr('data-id');
                for (var i = 0; i < quickviewElements.length; i++) {
                    if (quickviewElements[i].dataId == dataId) {
                        quickviewElement = quickviewElements[i].element;
                    }
                    if (quickviewElements[i].dataId == lastDataId) {
                        previousQuickviewElement = quickviewElements[i].element;
                    }
                }
                if (!quickviewElement) {
                    quickviewElement = $(document.createElement('div'));
                    quickviewElements.push({dataId: dataId, element: quickviewElement});
                }
                browse_file.after(quickviewElement);
                var pmin = 0;
                if (lastDataId != dataId) {
                    quickviewElement.css({
                        background: 'white',
                        height: '0px',
                        width: '100%',
                        float: 'left',
                        marginBottom: '20px'
                    });
                    quickviewElement.show();
                    quickviewElement.animate({height: qvHeight + "px"}, 500);
                    if (previousQuickviewElement) {
                        $(previousQuickviewElement).slideUp(500,

                            function(){
                                $(previousQuickviewElement).hide();
                                scrollToQuickView();
                                pmin = -qvHeight;
                                quickviewElement.html('<img src="/images/v9/ajax-loader.gif" />');
                                sendQuickViewRequest(id, category, quickviewElement);
                                lastDataId = browse_file.attr('data-id');
                            }

                        );
                        return false;
                    }
                }
                quickviewElement.html('<img src="/images/v9/ajax-loader.gif" />');
                sendQuickViewRequest(id, category, quickviewElement);
                lastDataId = browse_file.attr('data-id');
            }
            return (false);
        };
    };

    contentItem.isLoaded = function(){
        return window.quickViewFixed === true;
    };


    contentItem.loadedCallback = function(){

        console.log('Loaded Quick View Fix.');

    };

    return contentItem;
}
function contentCleanerContent(){
    var contentItem = new ContentItem();

    contentItem.name = 'Content Cleaner.';

    contentItem.canLoad = function(){
        return document.getElementById('nav-wrap') !== null;
    };
    contentItem.isLoaded = function(){
        return window.contentCleanerLoaded;
    };

    contentItem.load = function(){
        var head = $('head');
        head.prepend('<style>.notloggedin, .nonsubscriber, body .top-300-ad, .no-sub-button, .vip-link, body .ad-alsorectangle, body .ad-browse-rectangle, body .ad-bottomleader, body .ad-midleader, .sitemenu .not-logged-in, body .ad-topleader, .siteskin, .dl-menuwrapper .not-logged-in, .footer-glam, body .rectangle-1, .medianet { display: none !important; } .big-download-buttons, .file-data-index, .sub-button { display: block; } .iloggedin { display: inline-block; } .sitemenu .logged-in-account, .sitemenu .has-basket { display: inline-block; } .no-right-margin { margin-right: 0; } .big-data { top: 0; } .file-data-profile { border: 0; padding: 0; position: relative; } .big-data-profile { position: relative; float: left; } .big-download-profile { position: relative; bottom: auto; margin-top: 44px; border-top: 1px dotted #b7b7b7; padding-top: 20px; } #pushdown { display: none; } .wrapper { padding-top: 20px; margin-top: 0; } .mid-wrapper { padding-top: 0; margin-top: -30px !important; } .index-wrapper { position: relative; top: -20px; margin-top: 0 !important; } #updates { margin-top: 0; } #footer-stats { width: auto; } #footer-legal { width: 100%; } @media(min-width: 320px) and (max-width: 500px) { .big-info { height: 210px !important; margin-bottom: 30px !important; } .details .bsk, .big-info .bsk { display: block !important; width: 300px !important; margin: 0 !important; top: 0 !important; } .admin-link { top: -452px !important; right: 0 !important; } .index-page .big-info .button { top: 210px; } .index-page .big-info .bsk { top: 48px !important; } .index-page .big-info { height: 262px !important; } .profile-avatar { top: 40px !important; } .wrapper { padding-top: 10px; } .big-download-buttons strong { bottom: 505px !important; } .big-download-buttons { bottom: 45px; } .big-download-buttons .admin-link { top: -387px !important; right: -45px !important; } }  </style>');
        head.prepend('<style> .hide { display: none !important; } .ad-browse-rectangle.hide { display: none !important; } .ad-topleader { display: none !important; height: 0px !important; position: absolute !important; } </style>');
        window.contentCleanerLoaded = true;
    };

    contentItem.loadedCallback = function(){

        console.log('Loaded Content Cleaner.');

    };

    return contentItem;
}
function loginEnablerContent(){

    $.ajaxSetup({cache: false});
    window.$.ajaxSetup({cache: false});

    var contentItem = new ContentItem();

    contentItem.name = 'Login Enabler';

    contentItem.canLoad = function () {
        return window.document.getElementsByClassName('sitemenu clearfix')[0] !== undefined && typeof window.logout !== 'undefined' && window.document.getElementsByTagName('head').length > 0;
    };

    contentItem.isLoaded = function(){
        return window.document.getElementById('freemium-login-button') !== null;
    };

    contentItem.load = function(){

        window.logout = function () {

            $.ajax({
                url: '/account/logout', data: {ajax: 1}, success: function (data) {
                    console.log("Logging out");
                    clearSession(false);
                    document.location.href = '/';
                }, error: function (req, text) {
                    alert("Failed to log out");
                }
            });

        };

        window.clearSession = function(clearAll) {
            localStorage.memberId = 0;
            localStorage.LoginKey = 0;
            localStorage.cachedDate = 0;
            $.cookie('LoginKey', null, {domain: '.thesimsresource.com', path: '/'});
            $.cookie('MemberID', null, {domain: '.thesimsresource.com', path: '/'});
            cookieManager.addCookie('FFR', '0');
            cookieManager.addCookie('FreemiumVersion', userScriptVersion);
        };


        $('.sitemenu.clearfix').append('<li id="freemium-login-menu-item"><span class="nav-divider"></span><a id="freemium-login-button" href="#">Log in</a></li>');

        if(loginGenuine) {
            var loginButton = $('#freemium-login-menu-item');
            loginButton.hide();
        }
        else{
            $('.has-basket').hide();
            $('.logged-in-account').hide();
            $('.not-logged-in').hide();
            $('.button-submit').hide();
            $('head').prepend('<style> .bsk{display: none !important;} </style>');
        }
    };

    contentItem.loadedCallback = function(){

        if(document.getElementById('freemium-login-button') !== null){
            document.getElementById('freemium-login-button').onclick = function(){
                $('.loginBtn').click();
            }
        }
        console.log('Loaded Login Enabler.');
    };

    return contentItem;

}
function basketDownloaderContent(){

    var contentItem = new ContentItem();

    contentItem.name = 'Basket Downloader';

    contentItem.canLoad = function () {
        return loginGenuine && varExists(window.showbasket) && varExists(window.initBasket) && varExists(window._dl);
    };

    contentItem.isLoaded = function(){
        return varExists(window.basketDownloader);
    };

    contentItem.load = function(){

        window.basketDownloader = new BasketDownloader();

        window.initBasket = function(){};

        window.showbasket = function(test){

            if(test){
                return true;
            }

            $('#md-modal').show();
            $('#md-overlay').show();

            $.ajax({
                url: "/downloads/basket", data: {ajax: 1}, success: function (req, text) {
                    $().fancyModal({title: 'Download basket', data: req, width: 680, height: 696});
                    $('#zipdla').hide();
                    $('#basketFormDownloadRemoveAll').hide();
                    $('#basketForm').append('<div id="basket-downloader-button" class="button input-button pull-left">Download Basket</div>');
                    document.getElementById('basket-downloader-button').onclick = window.basketDownloader.download;
                }, error: function (req, text) {
                    //console.log("Failed to load basket: " + req.responseText);
                    if (req.responseText.match(/nosession/)) {
                        //console.log("Clear session and reload");
                        clearSession(false);
                        document.location.reload();
                    }
                }
            });

        };

        window._dl = function(itemid, format, callback, extraInfo){

            var mid = typeof(localStorage.memberId) !== 'undefined' ? localStorage.memberId : 0;
            var lk = typeof(localStorage.LoginKey) !== 'undefined' ? localStorage.LoginKey : 0;
            var ex = '';

            if (typeof(extraInfo) !== 'undefined')ex = '&ex=1';

            var ajxc = '/ajax.php?c=downloads&a=getdownloadurl&ajax=1&itemid=' + itemid + '&mid=' + mid + '&lk=' + lk + ex;

            $.ajax(ajxc).done(function (data) {
                if (data.error.length > 0) {
                    //alert(data.error);
                    if (data.logout)
                        logout();
                } else {
                    if (typeof(callback) !== 'undefined')
                        callback(data.url, data.data); else
                        document.location.href = data.url;
                }
            }).fail(function (err) {
                console.log("Error in _dl");
                console.log(err);
                //alert(err);
            });

        };

    } ;

    contentItem.loadedCallback = function(){
        console.log('Loaded Basket Enabler.');
    };

    return contentItem;
}
function firstRunContent(){

    var contentItem = new ContentItem();

    contentItem.name = 'First Run Message';

    contentItem.canLoad = function(){ return $('body')[0] !== undefined; };

    contentItem.isLoaded = function(){

        return document.getElementById('ffr') !== null;

    };

    contentItem.load = function() {

        $('head').prepend('<style>  #ffr { background-color: rgba(0, 0, 0, 0.8); height: 100%; position: fixed; width: 100%; z-index: 900410; } #ffr-message-container { background-color: rgba(245, 245, 245, 0.8); margin: auto; padding: 10px; width: 75%; } #ffr-title { font-size: 30px; height: 30px; line-height: 30px; margin-bottom: 20px; margin-top: 10px; text-align: center; } .no-ab { background-size: 25px auto, 25px auto; display: block; height: 25px; width: 25px; } #ffr-blocker-notice { font-size: 20px; height: 25px; line-height: 25px; } .ffr-feature-item { font-size: 20px; height: 25px; line-height: 25px; margin-bottom: 10px; } #ffr-feature-title { font-size: 25px; margin-bottom: 20px; margin-top: 34px; } .ffr-flex { display: inline-flex; height: 25px; margin-bottom: 10px; } #ffr-okay-btn { background-color: black; color: white; font-size: 20px; height: 35px; line-height: 35px; text-align: center; width: 100%; margin-top: 30px; } #ffr-okay-btn:hover { background-color: rgb(40, 40, 40); } #ffr-okay-btn:active { background-color: black; } .ffr-note { margin-bottom: 10px; margin-top: 0px; font-size: 17px; } .ffr-ab-red { background-image: url("http://66.media.tumblr.com/c23154e3145385fd35d79d87c780fdcd/tumblr_inline_nj60qrByht1scbcui.png"); } .ffr-ab-yellow { background-image: url("https://s19.postimg.org/oa32tqu3l/no_ad_block_yellow.png"); }    </style> ');
        $('body').prepend('<div id="ffr"> <div id="ffr-message-container"> <div id="ffr-title">TSR - Freemium</div> <!--<div class="ffr-flex"> <div class="no-ab ffr-ab-red"></div> <div id="ffr-blocker-notice">For full functionality ad/script blockers need to be disabled.</div> </div>--> <div class="ffr-note"><b> If you have any issues with the script CTRL+F5 should fix them, otherwise try closing the page and loading it again. Worst case clear cache. </b></div> <div id="ffr-message"> <div id="ffr-feature-title">Current feature list</div> <div class="ffr-feature-item">Premium style</div> <div class="ffr-feature-item">Login not required</div> <!--<div class="ffr-flex"> <div class="no-ab ffr-ab-yellow"></div>--> <div class="ffr-feature-item">Direct downloads</div> <!--</div>--> <div class="ffr-feature-item">Quick View scroll fix</div> <!--<div class="ffr-flex"> <div class="no-ab ffr-ab-red"></div>--> <div class="ffr-feature-item">Shopping Cart (work in progress - requires login)</div> <!--</div>--> <div class="ffr-feature-item">Ad and bloat scripts removed.</div> </div> <div id="ffr-okay-btn">Okay</div> </div> </div>'); //ffr_message.html

    };

    contentItem.loadedCallback = function(){

        document.getElementById('ffr-okay-btn').onclick = function(){

            cookieManager.addCookie('FFR', '0');
            $('#ffr').remove();

        };

        console.log('First Run Message Loaded.');
    };

    return contentItem;

}

if(firstRun){
    //contentItems.push(firstRunContent());
}
if(isUpdated){
    cookieManager.addCookie('FreemiumVersion', userScriptVersion);
}
if(loginGenuine) {
    contentItems.push(basketDownloaderContent());
}
//endregion

//region Loader
function Loader(contentItemArray, loadedCallback){

    var contentItems = contentItemArray;
    var loaderInterval = null;
    var loopRunning = false;

    var failedAttempts = {};
    var failLimit = 100;

    var loadedContentItems = [];
    var failedContentItems = [];

    this.load = function(){

        if(loaderInterval === null){
            loaderInterval = setInterval(loaderLoop, 100);
            console.log('TSR - Freemium');
            console.log('Loading...');
        }

    };

    function loaderLoop(){

        if(loopRunning){return;}
        loopRunning = true;

        for(var i =0; i < contentItems.length; i++){

            if(loadedContentItems.indexOf(contentItems[i].name) > -1|| failedContentItems.indexOf(contentItems[i].name) > -1){
                continue;
            }

            if(failedAttempts[contentItems[i].name] === undefined){
                failedAttempts[contentItems[i].name] = 0;
                //console.log(contentItems[i]);
            }

            if(contentItems[i].canLoad()){
                //console.log('Page ready..');
                if(!contentItems[i].isLoaded()){
                    //console.log('Loading..');
                    contentItems[i].load();
                    if(contentItems[i].isLoaded){
                        //console.log('Loaded.');
                        loadedContentItems.push(contentItems[i].name);
                        if(!contentItems[i].sentCallback){
                            //console.log('Sending callback.');
                            sendCallback(contentItems[i].loadedCallback);
                            contentItems[i].sentCallback = true;
                        }
                    }
                    else{
                        //console.log('Load failed.');
                        //console.log(contentItems[i]);
                        failedAttempts[contentItems[i].name]++;
                    }
                }
                else{
                    //console.log('Already Loaded.');
                    loadedContentItems.push(contentItems[i].name);
                }
            }
            else{
                //console.log('Unable to load right now. Page Not ready.');
                //console.log(contentItems[i]);
                failedAttempts[contentItems[i].name]++;
            }

            if(failedAttempts[contentItems[i].name] >= failLimit){
                //console.log(contentItems[i]);
                //console.log('Load failed.');
                failedContentItems.push(contentItems[i].name);
            }

        }

        if(isLoaded()){
            clearInterval(loaderInterval);
            loaderInterval = null;
            if(typeof(loadedCallback) === 'function'){
                loadedCallback([loadedContentItems.length, contentItems.length]);
            }
        }

        loopRunning = false;
    }

    function isLoaded(){
        for(var i = 0; i < contentItems.length; i++){
            if(failedContentItems.indexOf(contentItems[i].name) > -1 || loadedContentItems.indexOf(contentItems[i].name) > -1){
                continue;
            }
            return false;
        }
        return true;
    }
    function sendCallback(callback){
        if(typeof(callback) === 'function'){
            callback();
        }
    }

}
//endregion

var loader = new Loader(contentItems, function (loaded) {
    console.log('Freemium Loaded [' + loaded[0] + '/' + loaded[1] + '].');
});
loader.load();