Marketplace Hover Prices

Find out prices of items in your inventory by hovering over them while at the Marketplace

Version au 25/05/2019. Voir la dernière version.

Vous devrez installer une extension telle que Tampermonkey, Greasemonkey ou Violentmonkey pour installer ce script.

Vous devrez installer une extension telle que Tampermonkey pour installer ce script.

Vous devrez installer une extension telle que Tampermonkey ou Violentmonkey pour installer ce script.

Vous devrez installer une extension telle que Tampermonkey ou Userscripts pour installer ce script.

Vous devrez installer une extension telle que Tampermonkey pour installer ce script.

Vous devrez installer une extension de gestionnaire de script utilisateur pour installer ce script.

(J'ai déjà un gestionnaire de scripts utilisateur, laissez-moi l'installer !)

Vous devrez installer une extension telle que Stylus pour installer ce style.

Vous devrez installer une extension telle que Stylus pour installer ce style.

Vous devrez installer une extension telle que Stylus pour installer ce style.

Vous devrez installer une extension du gestionnaire de style pour utilisateur pour installer ce style.

Vous devrez installer une extension du gestionnaire de style pour utilisateur pour installer ce style.

Vous devrez installer une extension du gestionnaire de style pour utilisateur pour installer ce style.

(J'ai déjà un gestionnaire de style utilisateur, laissez-moi l'installer!)

// ==UserScript==
// @name         Marketplace Hover Prices
// @namespace    http://tampermonkey.net/
// @version      1.11
// @description  Find out prices of items in your inventory by hovering over them while at the Marketplace
// @author       SilverBeam
// @match        https://fairview.deadfrontier.com/onlinezombiemmo/index.php?page=35
// @include      */inventory_new.php
// @grant        GM_webRequest
// @webRequest   [{"selector":"*/inventory_new.php","action":"cancel"},{"selector":{"include":"*","exclude":"http://exclude.me/*"},"action":{"redirect":"http://new_static.url"}},{"selector":{"match":"*://match.me/*"},"action":{"redirect":{"from":"([^:]+)://match.me/(.*)","to":"$1://redirected.to/$2"}}}]

// ==/UserScript==

(function() {
    'use strict';

    function parseAmmo(ammo){
        let resp = "";
        switch(ammo){

                case '32ammo': resp = '.32 Handgun Bullets'; break;
                case '35ammo': resp = '9 mm Handgun Bullets'; break;
                case '38ammo': resp = '.38 Handgun Bullets'; break;
                case '40ammo': resp = '.40 Handgun Bullets'; break;
                case '357ammo': resp = '.357 Handgun Bullets'; break;
                case '45ammo': resp = '.45 Handgun Bullets'; break;
                case '50ammo': resp = '.50 Handgun Bullets'; break;
                case '55ammo': resp = '.55'; break;
                case '55rifleammo': resp = '5.5mm Rifle Bullets'; break;
                case '75rifleammo': resp = '7.5mm Rifle Bullets'; break;
                case '9rifleammo': resp = '9mm Rifle Bullets'; break;
                case '127rifleammo': resp = '12.7mm Rifle Bullets'; break;
                case '14rifleammo': resp = '14mm Rifle Bullets'; break;
                case '12gaugeammo': resp = '12 Gauge Shells'; break;
                case '16gaugeammo': resp = '16 Gauge Shells'; break;
                case '20gaugeammo': resp = '20 Gauge Shells'; break;
                case '10gaugeammo': resp = '10 Gauge Shells'; break;
                case 'heavygrenadeammo': resp = 'Heavy Grenades'; break;
                case 'grenadeammo': resp = 'Grenades'; break;
                default: resp = 'Sum Ting Wong';

        }
        return resp;
    }

    function capitalizeFirstLetter(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }

    function fillDataBank(id,name){
       let found = false;
       //console.log("Entering dataBank fill with: "+dataBank);

       for(let x of dataBank){
           if(x.id == id){
               found = true;
               break;
           }
       }

       if(!found){
           let item = {};
           item.id = id;
           item.name = name;
           dataBank.push(item);
       }
    }

    function filterParams(txt){
        let tmp = {};
        tmp.tradeZone = txt.match(/df_tradezone=\d*/)[0].split("=")[1];
        tmp.slotNum = parseInt(txt.match(/df_invslots=\d*/)[0].split("=")[1]);
        tmp.invArr = [];

        for(let i=1;i<=tmp.slotNum;i++){
            let item = {};
            let extraInfo;
            item.id = txt.match(new RegExp("df_inv" + i + "_type=*[^&]*"))[0].split("=")[1];
            if(item.id != ""){
                //console.log(item.id);
                if(item.id.indexOf("ammo") != -1){
                    item.code = "";
                    item.name = parseAmmo(item.id);
                    item.quantity = parseInt(txt.match(new RegExp("df_inv" + i + "_quantity=[0-9]+"))[0].split("=")[1]);
                }else if(item.id.split("_")[0] != null && txt.match(new RegExp("GLOBALDATA_armour[0-9]+_code="+item.id.split("_")[0])) != null){ //Check the item is an armor
                    item.code = txt.match(new RegExp("GLOBALDATA_armour[0-9]+_code="+item.id.split("_")[0]))[0].split("=")[0].match(/[0-9]+/)[0];
                    item.name = txt.match(new RegExp("GLOBALDATA_armour"+item.code+"_name=*[^&]*"))[0].split("=")[1];
                    item.quantity = 1;
                }else if(txt.match(new RegExp("GLOBALDATA_weapon[0-9]+_code="+item.id)) != null){ //Check if the item is a weapon
                    item.code = txt.match(new RegExp("GLOBALDATA_weapon[0-9]*_code="+item.id))[0].split("=")[0].match(/[0-9]+/)[0];
                    item.name = txt.match(new RegExp("GLOBALDATA_weapon"+item.code+"_name=*[^&]*"))[0].split("=")[1];
                    item.quantity = parseInt(txt.match(new RegExp("df_inv" + i + "_quantity=[0-9]+"))[0].split("=")[1]);
                }else{ //Default to item or implant
                    let baseItemName;
                    if(item.id.indexOf("_") != -1){
                        extraInfo = capitalizeFirstLetter(item.id.split("_")[1]);
                        baseItemName = item.id.split("_")[0];
                    }else{
                        baseItemName = item.id;
                    }
                    item.code = txt.match(new RegExp("GLOBALDATA_item[0-9]+_code="+baseItemName))[0].split("=")[0].match(/[0-9]+/)[0];
                    item.name = txt.match(new RegExp("GLOBALDATA_item"+item.code+"_name=*[^&]*"))[0].split("=")[1];
                    if(extraInfo){
                        item.name = extraInfo + " " + item.name;
                    }
                    item.quantity = parseInt(txt.match(new RegExp("df_inv" + i + "_quantity=[0-9]+"))[0].split("=")[1]);
                }
                fillDataBank(item.id,item.name);
            }else{
                item.code = "";
                item.name = "";
                item.quantity = 0;
            }

            //console.log(item);
            tmp.invArr.push(item);

        }

        return tmp;
    }

    function requestItem(tradezone,data,items){

        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                data.rawServerResponse = this.responseText;
                filterResponseText(data);
                updateParams(data,items);
                requestsCompleted += 1;
                //console.log(requestsCompleted);
                if(requestsCompleted >= requestsNum){console.log(dataBank);console.log(items);}
                //console.log(calculateAvailableOffers(this.responseText));
            }
        };
        xhttp.open("POST", "trade_search.php", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send("hash=16cc837c932e96f694b012566cddec40&pagetime=1558282908&tradezone="+tradezone+"&searchname="+encodeURI(data.name)+"&category=&profession=&memID=&searchtype=buyinglistitemname&search=trades");
        //console.log("hash=16cc837c932e96f694b012566cddec40&pagetime=1558282908&tradezone="+tradezone+"&searchname="+encodeURI(item.name)+"&category=&profession=&memID=&searchtype=buyinglistitemname&search=trades");

    }

    function requestInvItems(items,databank){

        requestsNum = databank.length;

        for(let i=0;i<databank.length;i++){
            if(databank[i].name != ""){
                requestItem(items.tradeZone,databank[i],items);
            }else{
                databank[i].rawServerResponse = "";
            }
        }

    }

    function calculateAvailableOffers(resp){
        return resp.match(/tradelist_[0-9]+_trade_id=/g).length;
    }

    function filterResponseText(item){
            let itemRawResponse = item.rawServerResponse;
            if(itemRawResponse != ""){
                let maxTrades = calculateAvailableOffers(itemRawResponse);
                let firstOccurence = parseInt(itemRawResponse.match(new RegExp("tradelist_[0-9]+_item="+item.id+"&"))[0].split("=")[0].match(/[0-9]+/)[0]);
                let availableTrades = maxTrades - firstOccurence + 1;
                let avgPrice = 0;
                let examinedTrades = 0;

                for(;(examinedTrades<availableTrades)&&(examinedTrades<10);examinedTrades++){
                    //console.log("Examination "+examinedTrades);
                    let pricePerUnit = parseInt(itemRawResponse.match(new RegExp("tradelist_"+(firstOccurence+examinedTrades)+"_price=[0-9]+&"))[0].split("=")[1].match(/[0-9]+/)[0]) /
                                       parseInt(itemRawResponse.match(new RegExp("tradelist_"+(firstOccurence+examinedTrades)+"_quantity=[0-9]+&"))[0].split("=")[1].match(/[0-9]+/)[0]);
                    avgPrice += pricePerUnit;
                    if(examinedTrades == 0){
                        item.bestPricePerUnit = pricePerUnit;
                    }
                }
                //console.log(item.id +": "+avgPrice+" "+examinedTrades);
                item.averagePricePerUnit = avgPrice / examinedTrades;
            }
    }

    function updateParams(data,params){
        for(let x of params.invArr){
            if(x.id == data.id){
                x.bestPricePerUnit = data.bestPricePerUnit;
                x.averagePricePerUnit = data.averagePricePerUnit;
            }
        }
    }

    function fillHoverBox(cellNum){

        return params.invArr[cellNum-1].name + "\nQuantity: " + params.invArr[cellNum-1].quantity +
               "\nBest price per unit: " + params.invArr[cellNum-1].bestPricePerUnit.toFixed(2) + "\nBest price this stack: " + (params.invArr[cellNum-1].bestPricePerUnit*params.invArr[cellNum-1].quantity).toFixed(2) +
               "\nAverage price per unit: " + params.invArr[cellNum-1].averagePricePerUnit.toFixed(2) + "\nAverage price this stack: " + (params.invArr[cellNum-1].averagePricePerUnit*params.invArr[cellNum-1].quantity).toFixed(2);

    }

    function checkHover(event){

        let bodyRect = document.body.getBoundingClientRect();
        let adjustY = document.getElementById("block13").children[0].children[0].children[0].getBoundingClientRect().height - 25;

        if(event.clientX-bodyRect.x > invLeft && event.clientX-bodyRect.x <= invLeft+invWidth && event.clientY-bodyRect.y-adjustY > invTop && event.clientY-bodyRect.y-adjustY <= invTop+invHeight){
            let cellNum = parseInt(((event.clientX-bodyRect.x - invLeft)/cellSize))*2 + parseInt((((event.clientY-bodyRect.y-adjustY - invTop)/cellSize)+1));
            if(params.invArr[cellNum-1].name != ""){
                hoverText.textContent = fillHoverBox(cellNum);
                hoverContainer.style.left = event.clientX - bodyRect.x + 20 + "px";
                hoverContainer.style.top = event.clientY - bodyRect.y + 20 + "px";
                hoverContainer.style.display = "block";
            }else{
                hoverContainer.style.display = "none";
            }
        }else{
            hoverContainer.style.display = "none";
        }

    }

    function adjustButtonY(){
        let flashRect = document.getElementById("flashMain1").getBoundingClientRect();
        let bodyRect = document.body.getBoundingClientRect();
        let adjustY = document.getElementById("block13").children[0].children[0].children[0].getBoundingClientRect().height - 25;
        enableButton.style.top = flashRect.y + flashRect.height - bodyRect.y - 120 + "px";
        //console.log(adjustY);
    }

    function startScript(){

        requestInvItems(params,dataBank);
        flashNode.addEventListener("mousemove",checkHover,true);
        enableButton.style.display = "none";
        clearInterval(interval);

    }

    var flashNode = document.getElementById("flashMain1");
    var flashParamsNode = flashNode.children[0];
    var flashRect = flashNode.getBoundingClientRect();
    var rawParams = flashParamsNode.value;
    var dataBank = [];
    var params = filterParams(rawParams);
    var requestsNum = 0;
    var requestsCompleted = 0;

    //requestInvItems(params,dataBank);


    var cellSize = (flashRect.height / 520) * 44;
    var invHeight = (cellSize * 2);
    var invWidth = cellSize * (params.slotNum/2);
    var invLeft = ((flashRect.width / 685) * (12.5 + (660 - invWidth)/2)) + flashRect.left - document.body.getBoundingClientRect().x;
    var invTop = ((flashRect.height / 520) * 425.5) + flashRect.top - document.body.getBoundingClientRect().y;
    var adjustTop = document.getElementById("block13").children[0].children[0].children[0].getBoundingClientRect().height - 25;

    var hoverContainer = document.createElement("div");
    hoverContainer.style.position = "absolute";
    hoverContainer.style.backgroundColor = "white";
    hoverContainer.style.display = "none";
    hoverContainer.style.height = "120px";
    hoverContainer.style.width = "200px";
    var hoverText = document.createElement("p");
    hoverText.style.color = "black";
        hoverText.style.whiteSpace = "pre";
    hoverContainer.appendChild(hoverText);
    document.getElementsByTagName("body")[0].appendChild(hoverContainer);

    var enableButton = document.createElement("button");
    enableButton.style.position = "absolute";
    enableButton.style.height = "18px";
    enableButton.style.fontSize = "12px";
    enableButton.innerHTML = "Enable hover box";
    enableButton.style.left = flashRect.left + 15 + "px";
    //enableButton.style.top = flashRect.y + flashRect.height - document.body.getBoundingClientRect().y - adjustTop + "px";
    enableButton.addEventListener("click",startScript,true);

    var interval = setInterval(adjustButtonY,20);
    document.getElementsByTagName("body")[0].appendChild(enableButton);





    ////////////////////////////////////////////////

   // var currently_active_webrequest_rule = JSON.stringify(GM_info.script.webRequest); // == @webRequst header from above
    //var rules = [{"selector":"*/inventory_new.php","action":"cancel"},{"selector":{"include":"*","exclude":"http://exclude.me/*"},"action":{"redirect":"http://new_static.url"}},{"selector":{"match":"*://match.me/*"},"action":{"redirect":{"from":"([^:]+)://match.me/(.*)","to":"$1://redirected.to/$2"}}}];
    //GM_webRequest(rules, function(info, message, events) {
        //console.log(info, message, events); // ex. events.request.url or events.response.body
    //});



    ///////////////////////////////


    /*
    var injectNode = 'console.log("Hi from injection 1");(function (open) {console.log("Hi from injection 2");XMLHttpRequest.prototype.open = function (method, url, async, user, pass){this.addEventListener ("readystatechange", function (evt){if (this.readyState == 4)  {console.log(this);}}, false);open.call (this, method, url, async, user, pass);};} ) (XMLHttpRequest.prototype.open);';

    //(function (open) {console.log("Hi from injection 2");XMLHttpRequest.prototype.open = function (method, url, async, user, pass){this.addEventListener ("readystatechange", function (evt){if (this.readyState == 4  &&  this.status == 200)  {console.log(this);}}, false);open.call (this, method, url, async, user, pass);};} ) (XMLHttpRequest.prototype.open);
    //var injectNode = "<!--debug-->";

    function addJS_Node (text){
        var scriptNode = document.createElement ('script');
        scriptNode.type = "text/javascript";
        scriptNode.id = "ResponseHook";
        if (text) scriptNode.innerHTML = text;

        var targ = document.getElementsByTagName('head')[0];
        targ.appendChild (scriptNode);
        console.log("Hey there");
    }

    addJS_Node (injectNode);
    */

})();