OGame: Messages

Messages espionage table

目前為 2015-11-04 提交的版本,檢視 最新版本

// ==UserScript== 
// @name OGame: Messages 
// @description Messages espionage table
// @namespace OGame: Messages
// @version 0.9.3
// @creator ter3ter 
// @include http://*/game/index.php?page=messages* 
// ==/UserScript==  

function strtotime(text, now) {
    // discuss at: http://phpjs.org/functions/strtotime/ 
    // version: 1109.2016 
    // original by: Caio Ariede (http://caioariede.com) 
    // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) 
    // improved by: Caio Ariede (http://caioariede.com) 
    // improved by: A. Matías Quezada (http://amatiasq.com) 
    // improved by: preuter 
    // improved by: Brett Zamir (http://brett-zamir.me) 
    // improved by: Mirko Faber 
    // input by: David 
    // bugfixed by: Wagner B. Soares 
    // bugfixed by: Artur Tchernychev 
    // note: Examples all have a fixed timestamp to prevent tests to fail because of variable time(zones) 
    // example 1: strtotime('+1 day', 1129633200); 
    // returns 1: 1129719600 
    // example 2: strtotime('+1 week 2 days 4 hours 2 seconds', 1129633200); 
    // returns 2: 1130425202 
    // example 3: strtotime('last month', 1129633200); 
    // returns 3: 1127041200 
    // example 4: strtotime('2009-05-04 08:30:00 GMT'); 
    // returns 4: 1241425800 

    var parsed, match, today, year, date, days, ranges, len, times, regex, i, fail = false;

    if (!text) {
        return fail;
    }

    // Unecessary spaces 
    text = text.replace(/^\s+|\s+$/g, '')
    .replace(/\s{2,}/g, ' ')
    .replace(/[\t\r\n]/g, '')
    .toLowerCase();

    // in contrast to php, js Date.parse function interprets: 
    // dates given as yyyy-mm-dd as in timezone: UTC, 
    // dates with "." or "-" as MDY instead of DMY 
    // dates with two-digit years differently 
    // etc...etc... 
    // ...therefore we manually parse lots of common date formats 
    match = text.match(
        /^(\d{1,4})([\-\.\/\:])(\d{1,2})([\-\.\/\:])(\d{1,4})(?:\s(\d{1,2}):(\d{2})?:?(\d{2})?)?(?:\s([A-Z]+)?)?$/);

    if (match && match[2] === match[4]) {
        if (match[1] > 1901) {
            switch (match[2]) {
                case '-':
                    { // YYYY-M-D
                        if (match[3] > 12 || match[5] > 31) {
                            return fail;
                        }

                        return new Date(match[1], parseInt(match[3], 10) - 1, match[5],
                                        match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000;
                    }
                case '.':
                    { // YYYY.M.D is not parsed by strtotime()
                        return fail;
                    }
                case '/':
                    { // YYYY/M/D
                        if (match[3] > 12 || match[5] > 31) {
                            return fail;
                        }

                        return new Date(match[1], parseInt(match[3], 10) - 1, match[5],
                                        match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000;
                    }
            }
        } else if (match[5] > 1901) {
            switch (match[2]) {
                case '-':
                    { // D-M-YYYY
                        if (match[3] > 12 || match[1] > 31) {
                            return fail;
                        }

                        return new Date(match[5], parseInt(match[3], 10) - 1, match[1],
                                        match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000;
                    }
                case '.':
                    { // D.M.YYYY
                        if (match[3] > 12 || match[1] > 31) {
                            return fail;
                        }

                        return new Date(match[5], parseInt(match[3], 10) - 1, match[1],
                                        match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000;
                    }
                case '/':
                    { // M/D/YYYY
                        if (match[1] > 12 || match[3] > 31) {
                            return fail;
                        }

                        return new Date(match[5], parseInt(match[1], 10) - 1, match[3],
                                        match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000;
                    }
            }
        } else {
            switch (match[2]) {
                case '-':
                    { // YY-M-D
                        if (match[3] > 12 || match[5] > 31 || (match[1] < 70 && match[1] > 38)) {
                            return fail;
                        }

                        year = match[1] >= 0 && match[1] <= 38 ? +match[1] + 2000 : match[1];
                        return new Date(year, parseInt(match[3], 10) - 1, match[5],
                                        match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000;
                    }
                case '.':
                    { // D.M.YY or H.MM.SS
                        if (match[5] >= 70) { // D.M.YY
                            if (match[3] > 12 || match[1] > 31) {
                                return fail;
                            }

                            return new Date(match[5], parseInt(match[3], 10) - 1, match[1],
                                            match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000;
                        }
                        if (match[5] < 60 && !match[6]) { // H.MM.SS
                            if (match[1] > 23 || match[3] > 59) {
                                return fail;
                            }

                            today = new Date();
                            return new Date(today.getFullYear(), today.getMonth(), today.getDate(),
                                            match[1] || 0, match[3] || 0, match[5] || 0, match[9] || 0) / 1000;
                        }

                        return fail; // invalid format, cannot be parsed
                    }
                case '/':
                    { // M/D/YY
                        if (match[1] > 12 || match[3] > 31 || (match[5] < 70 && match[5] > 38)) {
                            return fail;
                        }

                        year = match[5] >= 0 && match[5] <= 38 ? +match[5] + 2000 : match[5];
                        return new Date(year, parseInt(match[1], 10) - 1, match[3],
                                        match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000;
                    }
                case ':':
                    { // HH:MM:SS
                        if (match[1] > 23 || match[3] > 59 || match[5] > 59) {
                            return fail;
                        }

                        today = new Date();
                        return new Date(today.getFullYear(), today.getMonth(), today.getDate(),
                                        match[1] || 0, match[3] || 0, match[5] || 0) / 1000;
                    }
            }
        }
    }

    // other formats and "now" should be parsed by Date.parse() 
    if (text === 'now') {
        return now === null || isNaN(now) ? new Date()
        .getTime() / 1000 | 0 : now | 0;
    }
    if (!isNaN(parsed = Date.parse(text))) {
        return parsed / 1000 | 0;
    }

    date = now ? new Date(now * 1000) : new Date();
    days = {
        'sun': 0,
        'mon': 1,
        'tue': 2,
        'wed': 3,
        'thu': 4,
        'fri': 5,
        'sat': 6
    };
    ranges = {
        'yea': 'FullYear',
        'mon': 'Month',
        'day': 'Date',
        'hou': 'Hours',
        'min': 'Minutes',
        'sec': 'Seconds'
    };

    function lastNext(type, range, modifier) {
        var diff, day = days[range];

        if (typeof day !== 'undefined') {
            diff = day - date.getDay();

            if (diff === 0) {
                diff = 7 * modifier;
            } else if (diff > 0 && type === 'last') {
                diff -= 7;
            } else if (diff < 0 && type === 'next') {
                diff += 7;
            }

            date.setDate(date.getDate() + diff);
        }
    }

    function process(val) {
        var splt = val.split(' '), // Todo: Reconcile this with regex using \s, taking into account browser issues with split and regexes 
            type = splt[0],
            range = splt[1].substring(0, 3),
            typeIsNumber = /\d+/.test(type),
            ago = splt[2] === 'ago',
            num = (type === 'last' ? -1 : 1) * (ago ? -1 : 1);

        if (typeIsNumber) {
            num *= parseInt(type, 10);
        }

        if (ranges.hasOwnProperty(range) && !splt[1].match(/^mon(day|\.)?$/i)) {
            return date['set' + ranges[range]](date['get' + ranges[range]]() + num);
        }

        if (range === 'wee') {
            return date.setDate(date.getDate() + (num * 7));
        }

        if (type === 'next' || type === 'last') {
            lastNext(type, range, num);
        } else if (!typeIsNumber) {
            return false;
        }

        return true;
    }

    times = '(years?|months?|weeks?|days?|hours?|minutes?|min|seconds?|sec' +
        '|sunday|sun\\.?|monday|mon\\.?|tuesday|tue\\.?|wednesday|wed\\.?' +
        '|thursday|thu\\.?|friday|fri\\.?|saturday|sat\\.?)';
    regex = '([+-]?\\d+\\s' + times + '|' + '(last|next)\\s' + times + ')(\\sago)?';

    match = text.match(new RegExp(regex, 'gi'));
    if (!match) {
        return fail;
    }

    for (i = 0, len = match.length; i < len; i++) {
        if (!process(match[i])) {
            return fail;
        }
    }

    return (date.getTime() / 1000);
}

function shipCount (m, k, d, cargo)
{
    return Math.ceil (Math.ceil (Math.max (m + k + d, Math.min (0.75 * (m * 2 + k + d), m * 2 + d))) / cargo);
}

function norm_val(s) {
    var mn = 1;
    s = s.replace(/,/, '.');
    if (s.match(/M/)) {
        var rpos = s.length - s.indexOf('.');
        if (rpos == 3) {
           mn = 100000;
        } else if (rpos == 4) {
            mn = 10000;
        } else if (rpos == 5) {
            mn = 1000;
        } else {
            mn = 1000000;
        }
    }
    s = s.replace(/[M,\.]/g, "");
    s *= mn;
    return s;
}

var messages = [];

function parse_messages() {
    $('li.msg').each(function() {
        if ($(this).find('.msg_content>div').length == 4) {
            var coords = $(this).find('.msg_head>span>a').closest('span');
            var met = $(this).find('.msg_content>div.compacting:eq(1)>span.ctn4>span.resspan:eq(0)').text().substring(1).replace(/М/, 'M').replace(/[^0-9M,\.]/g,"");
            met = norm_val(met);
            var kris = $(this).find('.msg_content>div.compacting:eq(1)>span.ctn4>span.resspan:eq(1)').text().replace(/М/, 'M').replace(/[^0-9M,\.]/g,"");
            kris = norm_val(kris);
            var deut = $(this).find('.msg_content>div.compacting:eq(1)>span.ctn4>span.resspan:eq(2)').text().replace(/М/, 'M').replace(/[^0-9M,\.]/g,"");
            deut = norm_val(deut);
            var fleet = $(this).find('.msg_content>div.compacting:eq(3)>span.ctn.ctn4.tooltipLeft').text().replace(/М/, 'M').replace(/[^0-9M,\.]/g,"");
            if (!fleet) {
                fleet = 'Н/Д';
            }
            var def = $(this).find('.msg_content>div.compacting:eq(3)>span.ctn.ctn4.tooltipRight').text().replace(/М/, 'M').replace(/[^0-9M,\.]/g,"");
            if (!def) {
                def = 'Н/Д';
            }
            var link = $(this).find('.msg_actions>a:eq(3)').attr('href');
            var time = $(this).find('.msg_head>span.msg_date.fright').text();
            var nick;
            var status;
            if ($(this).find('.msg_content>div>span.status_abbr_honorableTarget').length) {
                nick = $(this).find('.msg_content>div>span.status_abbr_honorableTarget').text().substr(2);
                status = 'status_abbr_honorableTarget';
            } else if ($(this).find('.msg_content>div>span.status_abbr_longinactive').length) {
                nick = $(this).find('.msg_content>div>span.status_abbr_longinactive').text().substr(2);
                status = 'status_abbr_longinactive';
            } else if ($(this).find('.msg_content>div>span.status_abbr_inactive').length) {
                nick = $(this).find('.msg_content>div>span.status_abbr_inactive').text().substr(2);
                status = 'status_abbr_inactive';
            } else if ($(this).find('.msg_content>div>span.status_abbr_outlaw').length) {
                nick = $(this).find('.msg_content>div>span.status_abbr_outlaw').text().substr(2);
                status = 'status_abbr_outlaw';
            } else if ($(this).find('.msg_content>div>span.status_abbr_noob').length) {
                nick = $(this).find('.msg_content>div>span.status_abbr_noob').text().substr(2);
                status = 'status_abbr_noob';
            } else if ($(this).find('.msg_content>div>span.status_abbr_active').length) {
                nick = $(this).find('.msg_content>div>span.status_abbr_active').text().substr(2);
                status = 'status_abbr_active';
            } 
            var loot =$(this).find('.msg_content>div.compacting:eq(2)>span.ctn.ctn4').text().replace(/\D+/g,"");
            var activ = ' (' + $(this).find('.msg_content>div.compacting:eq(0)>span.fright').text().replace(/\D+/g,"") + ')';
            var all_res = met*1 + kris*1 + deut*1;
            all_res *= loot/100;
            all_res = Math.round(all_res);
            kris *= loot/100;
            kris = Math.round(kris);
            met *= loot/100;
            met = Math.round(met);
            deut *= loot/100;
            deut = Math.round(deut);
            var coords_array = $(this).find('.msg_head>span>a').text().match(/\[([0-9]):([0-9]+):([0-9]+)\]/); 
            messages.push({
                coords: coords,
                coords_array: coords_array[0].match(/[0-9]+/g),
                met: met,
                kris: kris,
                deut: deut,
                fleet: fleet,
                def: def,
                loot: loot,
                all_res: all_res,
                nick: nick,
                link: link,
                time: time,
                activ: activ,
                mt_count: shipCount(met, kris, deut, 5000),
                bt_count: shipCount(met, kris, deut, 25000),
                api: $(this).find('.msg_actions .icon_apikey').attr('title')
            });
        }
    });
}

function sort_by_res() {
    messages.sort(function(a, b) {
        return b.all_res - a.all_res;
    });
}
function sort_by_time() {
    messages.sort(function(a, b) {
        var d1 = strtotime(a.time);
        var d2 = strtotime(b.time);
        return d2 - d1;
    });
}
function sort_by_def() {
    messages.sort(function(a, b) {
        if (b.def == 'Н/Д') {
            //alert(b.coords);
            return -1;
        }
        if (a.def == 'Н/Д') {
            return 1;
        }
        console.log(b.def);
        //console.log(b.def == 'Н/Д');
        return norm_val(b.def) - norm_val(a.def);
    });
}
function sort_by_fleet() {
    messages.sort(function(a, b) {
        if (b.fleet == 'Н/Д') {
           return -1;
        }
        if (a.fleet == 'Н/Д') {
           return 1;
        }
        return norm_val(b.fleet) - norm_val(a.fleet);
    });
}

function show_table() {
    if ($('#scan_table').length > 0) {
        $('#scan_table').remove();
    }
    var cont = $('.pagination');
    var s = '<li id="scan_table"><table style="width: 100%;padding:5px">';
    s += '<tr><th></th><th id="order_time">Время</th><th>Ник</th><th>Координаты</th><th id="order_res">Добыча</th><th id="order_fleet">Флот</th><th id="order_def">Оборона</th><th></th><th></th><th>МТ</th><th>БТ</th></tr>';
    for(var i in messages) {
        var msg = messages[i];
        s += '<tr>';
        s += '<td style="padding:3px"><input type="checkbox"></td>';
        s += '<td>' + msg.time.substr(11) + '</td>';
        s += '<td><a class="txt_link msg_action_link overlay" href="'+msg.link+'">' + msg.nick + msg.activ + '</a></td>';
        s += '<td><a href="' + msg.coords.find('a').attr('href') + '">'+msg.coords.find('a').text().match(/\[[0-9]:[0-9]+:[0-9]+\]/)+'</a></td>';
        s += '<td title="met: '+msg.met+' kris:'+msg.kris+' deut:'+msg.deut+'">' + msg.all_res.toString().replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 ') + '</td>';
        s += '<td>' + msg.fleet + '</td>';
        s += '<td>' + msg.def + '</td>';
        s += '<td><a target="_blank" href="http://topraider.eu/index.php?SR_KEY='+msg.api+'&speed='+document.getElementsByName('ogame-universe-speed-fleet')[0].content+'">sim1</a></td>';
        s += '<td><a href="#none" class="open_websim">sim2</a></td>';
        s += '<td><a href="/game/index.php?page=fleet1&galaxy='+msg.coords_array[0]+'&system='+msg.coords_array[1]+'&position='+msg.coords_array[2]+'&type=1&mission=1&am202='+msg.mt_count+'">'+msg.mt_count+'</a></td>';
        s += '<td><a href="/game/index.php?page=fleet1&galaxy='+msg.coords_array[0]+'&system='+msg.coords_array[1]+'&position='+msg.coords_array[2]+'&type=1&mission=1&am203='+msg.bt_count+'">' + msg.bt_count + '</a></td>';
    }
    s += '</table></li>';
    cont.after(s);
    $('#order_time').click(function() {
        sort_by_time();
        show_table();
    });
    $('#order_res').click(function() {
        sort_by_res();
        show_table();
    });
    $('#order_def').click(function() {
        sort_by_def();
        show_table();
    });
    $('#order_fleet').click(function() {
        sort_by_fleet();
        show_table();
    });
    $('.open_websim').click(function() {
        var tr = $(this).closest('tr');
        var full_link = tr.find('td>a.msg_action_link').attr('href');
        $.get(full_link, function(data) {
            var dom = $(data);
            var ships = {};
            var url = 'http://websim.speedsim.net/?';
            for (i = 202;i<216;i++) {
                if (dom.find('.tech'+i).length == 1) {
                    var num = i - 202;
                    url += 'ship_d0_'+num+'_b='+dom.find('.tech'+i).closest('.detail_list_el').find('span.fright').text().replace(/\D+/g,"")+'&';
                }
            }
            for (i = 401;i<409;i++) {
                if (dom.find('.defense'+i).length == 1) {
                    var num = i - 401 + 14;
                    url += 'ship_d0_'+num+'_b='+dom.find('.defense'+i).closest('.detail_list_el').find('span.fright').text().replace(/\D+/g,"")+'&';
                }
            }
            url += 'enemy_metal=' + norm_val(dom.find('.resourceIcon.metal').closest('.resource_list_el').find('.res_value').text());
            url += '&enemy_crystal=' + norm_val(dom.find('.resourceIcon.crystal').closest('.resource_list_el').find('.res_value').text());
            url += '&enemy_deut=' + norm_val(dom.find('.resourceIcon.deuterium').closest('.resource_list_el').find('.res_value').text());
            url += '&enemy_pos=' + tr.find('td:eq(3)>a').text().replace(/[\[\]]/g,'');
            if (dom.find('.research109').length == 1) {
                url += '&tech_d0_0='+dom.find('.research109').closest('.detail_list_el.odd').find('.fright').text();
            }
            if (dom.find('.research109').length == 1) {
                url += '&tech_d0_1='+dom.find('.research110').closest('.detail_list_el.odd').find('.fright').text();
            }
            if (dom.find('.research109').length == 1) {
                url += '&tech_d0_2='+dom.find('.research111').closest('.detail_list_el.odd').find('.fright').text();
            }
            url += '&uni_speed=' + $("meta[name=ogame-universe-speed-fleet]").attr('content');
            var api_url = 'http://' + $("meta[name=ogame-universe]").attr('content') + '/api/serverData.xml';
            $.get(api_url, function(data) {
                url += '&perc-df='+$(data).find('debrisFactor').text()*100;
                url += '&def_to_df='+$(data).find('defToTF').text();
                if (navigator.userAgent.search(/Firefox/) > -1) {
                    unsafeWindow.open(url, '_blank');
                } else {
                    GM_openInTab(url);
                }
            });
            return false;
        });

    });
}

function do_msg() {
    parse_messages();

    show_table()
}
function wait_msg() {
    if ($('.msg_status').length > 0) {
        do_msg();
    } else {
        setTimeout(wait_msg, 1000);
    }
}
wait_msg();

$(document).ready(function() {
    $(document).on('click', '#ui-id-19', function() {
        setTimeout(wait_msg, 1000);
    });
    $(document).on('load', '#ui-id-20', function() {
        setTimeout(wait_msg, 1000);
    });
});