ResetEra Live Thread

Update threads without refreshing

当前为 2017-10-28 提交的版本,查看 最新版本

// ==UserScript==
// @name         ResetEra Live Thread
// @namespace    http://madjoki.com
// @version      1.1
// @description  Update threads without refreshing
// @author       Madjoki
// @match        https://www.resetera.com/threads/*
// @grant        GM_addStyle
// ==/UserScript==

(function() {
    'use strict';

    var defaultThreadSettings = {
        updateTime: 30,
        enabled: false,
    };

    function getSettings(thread)
    {
        var stored = localStorage.getItem("livethread_" + thread);

        if (stored === null)
            return defaultThreadSettings;

        return JSON.parse(stored);
    }

    function setSettings(thread, settings)
    {
        localStorage.setItem("livethread_" + thread, JSON.stringify(settings));
    }

	function saveSettings()
	{
		setSettings(threadID, currentThreadSettings);
	}

    var threadID = parseInt($('[name="type[post][thread_id]"]').val(), 10);

    var currentThreadSettings = getSettings(threadID);

    var countNew = 0;
    var countNewLast = 0;
    var errors = 0;
    var timeToNextUpdate = currentThreadSettings.updateTime;
    var updating = false;
    var lastUrl = window.location;
    var currentPage = $('div.PageNav').first().data('page') || 1;
    var lastLoadedPage = currentPage;
    var lastPage = $('div.PageNav').first().data('last') || 1;
    var threadTitle = $('title').text();

    GM_addStyle(
"#livethreadControl {\n" +
"    text-align: center; \n" +
"    margin-bottom: 5px; \n" +
"}\n" +
"#livethreadStatus {\n" +
"    text-align: center; \n" +
"}\n" +
"#livethreadSettings {\n" +
"    text-align: center; \n" +
"    margin: auto;\n" +
"}\n" +
        "");

	var timeout = setInterval(timerTick, 1000);

    function updateStatus()
    {
        var status  = "";

        if (updating)
            status += "Updating";
        else if (currentThreadSettings.enabledEnabled)
        {
            status += "Next Update In " + timeToNextUpdate + " seconds - ";

            if (countNewLast > 0)
                status += countNewLast + " New Messages!";
            else
                status += "No New Messages";
        }
        else
            status += "Auto Update Disabled";

        $("#livethreadStatus").text(status);

        if (countNew > 0)
            $('title').text("(" + countNew + ") " + threadTitle);
        else
            $('title').text(threadTitle);
    }

    function enableDisable(event)
    {
        event.preventDefault();

        currentThreadSettings.enabledEnabled = !currentThreadSettings.enabledEnabled;

		saveSettings();

        updateStatus();
    }

    function timerTick()
    {
		if (!currentThreadSettings.enabledEnabled)
			return;

        timeToNextUpdate--;

        if (timeToNextUpdate === 0)
        {
            updateMessages();
            timeToNextUpdate = currentThreadSettings.updateTime;
        }

        updateStatus();
    }

    // Inserts marker after last message
    function insertNotifi(text)
    {
        var $el = $('<div>', {'class': "newMessagesNotice", 'text': text});

        $("#messageList").append($el);

        return $el;
    }

    // Get URL for current page
    function getCurrentURL()
    {
        var pageNav = $('div.PageNav').first();

        currentPage = pageNav.data('page') || 1;
        lastPage = pageNav.data('last') || 1;

        if (pageNav.data('baseurl') === undefined)
            return window.location;

        if (lastPage > currentPage)
            currentPage++;

        return pageNav.data('baseurl').replace('{{sentinel}}', currentPage);
    }

    function updateMessagesClick(event)
    {
        event.preventDefault();
        updateMessages();
    }

    function updateMessages()
    {
        if (updating)
            return;

        updating = true;
        updateStatus();

        countNewLast = 0;

        var thisUrl = getCurrentURL();
        lastUrl = getCurrentURL();

        $.get(lastUrl, function (data) {

            // If new page insert marker and update history
            if (lastLoadedPage < currentPage)
            {
                window.history.pushState(null, null, thisUrl);
                lastUrl = thisUrl;

                insertNotifi("Page " + currentPage);

                lastLoadedPage = currentPage;
            }

            var node = $($.parseHTML(data));

            var newNav = node.find('div.PageNav').first();

            $('div.PageNav').each(function (i, el) {

                $(el).replaceWith(newNav.clone());

            });

            // To avoid reloading mesasges after posting
            $('input[name="last_date"]').val(node.find('input[name="last_date"]').val());
            $('input[name="last_known_date"]').val(node.find('input[name="last_known_date"]').val());

            node.find('#messageList > li').each(function (i, el) {

                var $el = $(el);

                var id = $el.attr('id');

                var $curr = $('#' + id);

                // Update old message if changed
                if ($curr.length)
                {
                    var newMessage = $el.find('article');
                    var oldMessage = $curr.find('article');

                    if (newMessage.text() != oldMessage.text())
                    {
                        oldMessage.replaceWith(newMessage).xfActivate();

                        $curr.xfActivate();
                    }
                }
                // Insert new messages
                else
                {
                    $el.xfInsert('appendTo', $("#messageList"));

                    countNew++;
                    countNewLast++;
                }

            });

            // If we have more pages to load, use shorter timer
            if (currentPage < lastPage)
                timeToNextUpdate = 5;

        }).always(function () {
            updating = false;
            updateStatus();
        });
    }

    $('Div.pageNavLinkGroup').last().before('\
<div id="livethreadPanel" class="DiscussionListOptions secondaryContent">\
   <div id="livethreadStatus"></div>\
   <div id="livethreadControl" class="publicControls">\
       <a id="livethreadEnabled" href="#" class="callToAction"><span>Auto Update On/Off</span></a>\
       <a id="livethreadUpdate" href="#" class="callToAction"><span>Update Now</span></a>\
   </div>\
   <div id="livethreadSettings">\
      <div class="controlGroup">\
         <label for="updateTime">Update Speed:</label>\
         <select id="updateTime" class="textCtrl">\
             <option value="15">Fast</option>\
             <option value="30" selected>Normal</option>\
             <option value="60">Slow</option>\
         </select>\
    </div>\
</div>');

    $('#livethreadEnabled').click(enableDisable);
    $('#livethreadUpdate').click(updateMessagesClick);

    $('#updateTime').change(function () {
        currentThreadSettings.updateTime = parseInt($('#updateTime').val());

		saveSettings();

        if (currentThreadSettings.updateTime < timeToNextUpdate)
            timeToNextUpdate = currentThreadSettings.updateTime;

        updateStatus();
    });

    $(window).focus(function () {
        // Reset new messages on focus
        countNew = 0;
        updateStatus();
    });

    updateStatus();
})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址