frogspin / kb_track

// ==UserScript==
// @name         kb_track
// @version      0.1
// @description  Управляем группами котиков
// @author       Кышбрысь
// @match        https://*.catwar.su/*
// @include      /https:\/\/\w?\.?catwar\.su\/.*/
// @license      MIT; https://opensource.org/licenses/MIT
// @updateurl    https://openuserjs.org/install/infolafx.ru/kb_track.user.js
// @grant        GM_xmlhttpRequest
// @grant        GM.xmlHttpRequest
// @require      https://abstract-class-shed.github.io/cwshed/jquery-3.4.1.min.js
// @require      https://raw.githubusercontent.com/litera/jquery-scrollintoview/master/jquery.scrollintoview.min.js
// @require      https://abstract-class-shed.github.io/cwshed/jquery-ui.js
// ==/UserScript==

/*global jQuery*/
(function (window, document, $) {
    'use strict';


    if (typeof $ === 'undefined') return;
    const version = '0.1';

    const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
    const isDesktop = !$('meta[name=viewport]').length;
    const defaults = {
        'la_version' : version

        , 'la_min_value' : '-10000000000'
        , 'la_max_value' : '10000000000'
        , 'la_last_command' : '0'

        , 'la_cats_visible' : false
        , 'la_cats_list' : ''
        , 'la_maps_list' : ''

        , 'la_show_id' : true
        , 'la_show_title' : true
    };

    const globals = {}; //Настройки

    for (var key in defaults) {
        let settings = getSettings(key);
        if (settings === null) {
            globals[key] = defaults[key];
        } else {
            if (Array.isArray(defaults[key])) {
                globals[key] = JSON.parse(settings);
            } else {
                globals[key] = settings;
            }
         }
    }

    function getSettings(key) { //Получение настроек
        let setting = 'cws_sett_' + key;
        let val = window.localStorage.getItem(setting);
        switch (val) {
            case null: return null;
            case 'true': return true;
            case 'false': return false;
        default:
            return val;
        }
    }

    var error_tm;

    function error(t) {
        $("#error").text(t).show();
        clearTimeout(error_tm);
        error_tm = setTimeout(function () {
            hideError()
        }, 10000);
    }

    function hideError() {
        clearTimeout(error_tm);
        $("#error").fadeOut(500);
    }

    function setSettings(key, val) {
        let setting = 'cws_sett_' + key;
        window.localStorage.setItem(setting, val);
    }

    function removeSettings(key) {
        let setting = 'cws_sett_' + key;
        window.localStorage.removeItem(setting);
    }

    function addCSS(css) {
        $('head').append(`<style>${css}</style>`);
    }

    const pageurl = window.location.href;
    const isCW3 = (/^https:\/\/\w?\.?catwar.su\/cw3(?!(\/kns|\/jagd))/.test(pageurl));
    const isDM = (/^https:\/\/\w?\.?catwar.su\/ls/.test(pageurl));
    const isHunt = (/^https:\/\/\w?\.?catwar.su\/cw3\/jagd/.test(pageurl));
    const isSett = (/^https:\/\/\w?\.?catwar.su\/settings/.test(pageurl));
    const isMyCat = (/^https:\/\/\w?\.?catwar.su\/$/.test(pageurl));
    const isBlog = (/^https:\/\/\w?\.?catwar.su\/blog\d+/.test(pageurl));
    const isCUMoves = (/^https:\/\/\w?\.?catwar.su\/moves$/.test(pageurl));
    const isProfile = (/^https:\/\/\w?\.?catwar.su\/cat(\d+|\/)/.test(pageurl));
    const isChat = (/^https:\/\/\w?\.?catwar.su\/chat/.test(pageurl));

    try {
        console.log('start');

        if (isCW3) cw3();
        //if (isDM) dm();
        //if (isSett) sett();
        //if (isHunt) hunt();
        //if (isMyCat) myCat();
        //if (isBlog) blog();
        //if (isProfile) profile();
        //if (isCUMoves) cumoves();
        //if (isChat) chat();
    } catch (err) {
        window.console.error('la: Syslap error: ', err);
    }

    function cw3() {

        addCSS(`#la_group {background-color: #222222;}
                #la_table.hidden {display:none}
                #la_group hr {
                    margin: 2px 0;
                    padding: 0;
                    height: 1px;
                    border: none;
                    background: linear-gradient(45deg, #333, #ddd);
                }`);

        let ids = [];
        let names = [];
        let statuses = [];
        let titles = [];

        let needUpdate = false;
        let old_location = '';
        
        function change_statuses() {
            let color = '#000000';
            let list = $('#la_cats_list').val();
            let N = 0;

            let catlist = '';
            ids.forEach(id => {
                if (statuses[id] == '[ В игре ]') color = '#006400';
                if (statuses[id] == '[ Спит ]') color = '#640000';

                if (list.length == 0 || list.includes(names[id]) || list.includes(id)) {
                    catlist = catlist + `<font size=2px color=${color}><a id="cats_click" href=#>${names[id]}</a> (${id}), ${titles[id]}</font><br>
                    `;
                    N = N + 1;
                }
            });
            catlist = catlist + '';
            $('#la_cmd_title').html(catlist);
            $('#la_cats_count').html('[' + N + ']');
        };
        
        function update_maps() {
            let N = 0;
            let maplist = '';
            let maps = $('#la_maps_list').val().split(/[\,,;,➝]/);
            let currentMap = false;
            maps.forEach(map => {
                if (map.trim() != '') {
                    currentMap = map.trim().includes($('#location').html());
                    maplist = maplist + `<font size=2 color=#000000>${(currentMap ? '<b>' : '')}<a id="maps_click" href=#>${map.trim()}</a>${(currentMap ? '</b>' : '')}</font> -> `;
                    N = N + 1;
                };
            });
            maplist = maplist + '<font size=2 color=#000000><b><a id="maps_click" href=#>Отмена</a></b></font>';
            $('#la_maps_title').html(maplist);
            $('#la_maps_count').html('[' + N + ']');
        }

        function updateCatsList() {
            let cages = document.getElementById('cages');
    
            let elemList = cages.querySelectorAll('.catWithArrow');
            ids = [];
            elemList.forEach(elem => {
                let hrefa = $(elem).find('.cat_tooltip > u > a');
                let href = hrefa.attr('href');
                //debugger;
                if (href !== undefined) {
                    let cat_id = href.replace(/\D/g, '');
                    ids[cat_id] = cat_id;
                }
            })
        }

        function updateTimerTick() {
            if (globals.la_cats_visible && needUpdate) {
                needUpdate = false;
                updateCatsList();
                change_statuses();
                update_maps();
            };
        }; setInterval(updateTimerTick, 1000);

        $(document).ready(function () {
            ids = [];

            $("#cages").on('DOMNodeInserted', '.catWithArrow', function () {

                let href = $(this).find('.cat_tooltip > u > a').attr('href');
                if (href !== undefined) {
                  let cat_id = href.replace(/\D/g, '');
                  ids[cat_id] = cat_id;
                  if (titles[cat_id] === undefined) {
                    let title = $(this).find('.cat_tooltip > small > i').html();
                    titles[cat_id] = title;
                  }
                  if (names[cat_id] === undefined) {
                    let name = $(this).find('.cat_tooltip > u > a').html();
                    names[cat_id] = name;
                  }
                  let status = $(this).find('.online').text(); // [ На удалении ]
                  let is_punished = $(this).find('div[style*="costume/295."]').length; // Подстилки?
                  if (is_punished) {
                    status = "[ В подстилках ]";
                  }
                  statuses[cat_id] = status;
                  needUpdate = true;
                }
                
            });

            $("#cages").on('DOMNodeRemoved', '.catWithArrow', function () {
                let href = $(this).find('.cat_tooltip > u > a').attr('href');
                if (href !== undefined) {
                  let cat_id = href.replace(/\D/g, '');
                  delete ids[cat_id];
                  needUpdate = true;
                }
            });

            $(` <tr id="la_group">
                    <td><input type="checkbox" id="la_show_cats" ${(globals.la_cats_visible ? 'checked' : '')}><label><b>Коты и локации</b></label>
                        <table id="la_table"${(globals.la_cats_visible ? '' : ' class="hidden"')}><tr>
                            <td colspan=2><hr class="la_hr"></td>
                        </tr><tr>
                            <td width=50%> <b>Коты: </b> <label id="la_cats_count"></label>  <input id="la_cats_list" type="text" size="50"></td>
                            <td width=50%> <b>Локации: </b> <label id="la_maps_count"></label>  <input id="la_maps_list" type="text" size="50"></td>
                        </tr><tr>
                            <td colspan=2><hr class="la_hr"></td>
                        </tr><tr>
                            <td id="la_cmd_title"></td>
                            <td id="la_maps_title"></td>
                        </tr></table>
                    </td>
                </tr>`).insertAfter('#tr_chat');

            $('#la_cats_list').val(globals.la_cats_list);
            $('#la_maps_list').val(globals.la_maps_list);
            update_maps();

            $('body').on('change', '#la_show_cats', function () {
                globals.la_cats_visible = $(this).prop('checked');
                $('#la_table').toggleClass('hidden');
                setSettings('la_cats_visible', globals.la_cats_visible)
                needUpdate = true;
            });

            $('body').on('change', '#la_cats_list', function () {
                globals.la_cats_list = $('#la_cats_list').val();
                setSettings('la_cats_list', globals.la_cats_list);
                needUpdate = true;
            });
            $('body').on('change', '#la_maps_list', function () {
                globals.la_maps_list = $('#la_maps_list').val();
                setSettings('la_maps_list', globals.la_maps_list);
                update_maps();
            });

            $('body').on('click', '#cats_click', function () {
                $('#text').val($('#text').val() + $(this).html() + ', ');
            });
            $('body').on('click', '#maps_click', function () {
                $('#text').val($(this).html());
                update_maps();
            });
        });
    }

})(window, document, jQuery);