Updates company stock based on given numbers or percentages.
目前為
// ==UserScript==
// @name Company Stock update
// @namespace http://tampermonkey.net/
// @version 2.2
// @description Updates company stock based on given numbers or percentages.
// @author LordBusiness
// @match https://www.torn.com/companies.php
// @run-at document-idle
// @grant GM_addStyle
// @grant GM_getValue
// @grant GM_setValue
// ==/UserScript==
console.log("L1 - The script has loaded.");
GM_addStyle("#lbsloneParent{padding: 0 10px 10px 10px;display: flex}#lbslPlabel{line-height: 24px;padding-right: 5px}#lbslonePercent{background: white;border: 1px solid #CCC;padding: 5px;border-radius: 5px;flex: 1;white-space: nowrap; overflow: hidden}[contentEditable=true]:empty:not(:focus):before{content:attr(data-text);color: grey}");
var state = GM_getValue ("APIkey", "");
var Percent = GM_getValue ("Percent", "");
var APIkey, percent, PriceArray = [];
var isPercentage = true;
function getAPIKey() {
$.ajax({
url: "/preferences.php",
// 'xhr' option overrides jQuery's default
// factory for the XMLHttpRequest object.
// Use either in global settings or individual call as shown here.
xhr: function() {
// Get new xhr object using default factory
var xhr = jQuery.ajaxSettings.xhr();
// Copy the browser's native setRequestHeader method
var setRequestHeader = xhr.setRequestHeader;
// Replace with a wrapper
xhr.setRequestHeader = function(name, value) {
// Ignore the X-Requested-With header
if (name == 'X-Requested-With') return;
// Otherwise call the native setRequestHeader method
// Note: setRequestHeader requires its 'this' to be the xhr object,
// which is what 'this' is here when executed.
setRequestHeader.call(this, name, value);
}
// pass it on to jQuery
return xhr;
},
success: function(data, textStatus, jqXHR) {
// response from request without X-Requested-With header!
var tornKey = String($("#newapi",data).val());
GM_setValue ("APIkey", tornKey);
APIkey = tornKey;
}
// etc...
});
}
if ( ! state) {
getAPIKey();
} else if(state == "none") {
getAPIKey();
} else {
APIkey = String(state);
}
if ( ! Percent) {
GM_setValue ("Percent", "none");
percent = "none";
} else if(state == "none") {
percent = "none";
PriceArray = [];
} else {
percent = String(Percent);
PriceArray = percent.split(",");
}
// a minimal jQuery library for reacting to innerHTML changes
(function($) {
$.fn.change = function(cb, e) {
e = e || { subtree:true, childList:true, characterData:true };
$(this).each(function() {
function callback(changes) { cb.call(node, changes, this); }
var node = this;
(new MutationObserver(callback)).observe(node, e);
});
};
})(jQuery);
var storageURL = "https://api.torn.com/company/?selections=detailed&key=" + APIkey;
var flag = 0, flag2 = 0, pos = 0, maxStorage = 0;
var url = "https://api.torn.com/company/?selections=stock&key=" + APIkey;
var stockItems = [];
console.log("L2 - Basic values have been initialized and loaded.");
$("#ui-id-8").click(updateStock);
$("#manage-tabs").change(function() {
if($("#manage-tabs option:selected").val() == "stock") {
updateStock();
}
});
function updateStock() {
console.log("L3 - The Stock tab has been selected.");
if(flag2 == 0) {
$('#stock').change(function(changes, observer) {
if(($(".stock-list-wrap").length > 0) && ($("#lbslonePercent").length == 0)) {
console.log("L4 - The Stock content has loaded.");
$("#stock > form > div:first-child").after('<div id="lbsloneParent"><span id="lbslPlabel">Percentages:</span><div id="lbslonePercent" contenteditable="true" data-text="Enter percentages separated by commas here.."></div></div>');
if(percent != "none") {
$("#lbslonePercent").html(percent);
}
$("#lbslonePercent").keypress(function(ev) {
var keycode = (ev.keyCode ? ev.keyCode : ev.which);
$("#lbslonePercent").css("color", "#333");
if (keycode == '13') {
GM_setValue ("Percent", String($("#lbslonePercent").text()));
$("#lbslonePercent").css("color", "green");
ev.stopPropagation();
ev.preventDefault();
}
});
}
});
console.log("L4 - The GUI has finished loading.");
flag2 = 1;
if((isPercentage) && (APIkey != "none")) {
console.log("L5 - API key is not empty, trying to connect to Torn API.");
$.getJSON( storageURL )
.done(function( jsonSize ) {
console.log("L6 - Response received from server for Company storage request.");
try {
maxStorage = parseInt(jsonSize.company_detailed.upgrades.storage_space);
var sumPercent = 0;
for(var i=0;i<PriceArray.length;i++) {
PriceArray[i] = PriceArray[i].replace('%', '');
sumPercent += parseInt(PriceArray[i]);
PriceArray[i] = parseInt(PriceArray[i]) * maxStorage / 100;
console.log(sumPercent);
}
$.getJSON( url )
.done(function( json ) {
console.log("L7 - Response received from server for Company delivery request.");
for (var key in json.company_stock) {
console.log(1, key);
if(pos == 0) {
stockItems = [key];
pos = 1;
} else {
for(var i=0; i < stockItems.length; i++) {
var stockItemelem = parseInt(json.company_stock[stockItems[i]].rrp);
var currentelem = parseInt(json.company_stock[key].rrp);
if(stockItemelem >= currentelem) {
if((stockItemelem == currentelem) && (String(key).localeCompare(stockItems[i]) == 1))
if(++i == stockItems.length) {
stockItems.push(key);
break;
}
stockItems.splice(i, 0, key);
break;
}
else if(i == stockItems.length-1) {
stockItems.push(key);
break;
}
}
}
}
for(var j=0; j<stockItems.length; j++) {
PriceArray[j] = PriceArray[j] - parseInt(json.company_stock[stockItems[j]].in_stock) - parseInt(json.company_stock[stockItems[j]].on_order);
}
console.log("L8 - PriceArray Enumerated.");
if($(".stock-list-wrap").length > 0) {
try {
var k = 0;
$(".quantity > input").each(function() {
if(PriceArray[k] > 0) {
$(this).focus();
$(this).val(PriceArray[k]);
$(this).keydown();
$(this).keypress();
$(this).keyup();
$(this).blur();
}
k++;
});
k = 0;
console.log("L9 - Prices entered.");
}
catch(err) {
console.log("Err:" + err);
}
}
})
.fail(function( jqxhr, textStatus, error ) {
console.log( "Request Failed: " + textStatus + ", " + error );
});
} catch(ex) {
console.log(ex);
try {
var errorcode = jsonSize.error.code;
if(errorcode == 1 || errorcode == 2 || errorcode == 12) {
getAPIKey();
console.log(errorcode,jsonSize.error.error);
console.log("LInfo - Reset API key. Refresh Page plz.");
}
} catch(exex) {
console.log("LInfo - Not API key Error?");
}
}
})
.fail(function( jqxhr, textStatus, error ) {
console.log( "Request Failed: " + textStatus + ", " + error );
});
}
}
}
function flush() {
GM_setValue ("APIkey", "none");
GM_setValue ("Percent", "none");
}