diff --git a/code.user.js b/code.user.js index cd309c2..46a1bbc 100644 --- a/code.user.js +++ b/code.user.js @@ -27,15 +27,13 @@ // ==/UserScript== /* disable some eslint rules until the code is cleaned up */ -/* global unsafeWindow, luxon, jQuery, async, localforage */ -/* eslint no-undef: off, no-unused-vars: off */ +/* global unsafeWindow, luxon, jQuery, async, List, localforage */ +/* eslint no-undef: off */ // jQuery is already added by Steam, force no conflict mode. (function($, async) { $.noConflict(true); - var DateTime = luxon.DateTime; - const PAGE_MARKET = 0; const PAGE_MARKET_LISTING = 1; const PAGE_TRADEOFFER = 2; @@ -53,49 +51,51 @@ const ERROR_FAILED = 1; const ERROR_DATA = 2; - var marketLists = []; - var totalNumberOfProcessedQueueItems = 0; - var totalNumberOfQueuedItems = 0; - var totalPriceWithFeesOnMarket = 0; - var totalPriceWithoutFeesOnMarket = 0; - var totalScrap = 0; + const marketLists = []; + let totalNumberOfProcessedQueueItems = 0; + let totalNumberOfQueuedItems = 0; + let totalPriceWithFeesOnMarket = 0; + let totalPriceWithoutFeesOnMarket = 0; + let totalScrap = 0; - var spinnerBlock = + const spinnerBlock = '
 
 
 
 
 
'; - var numberOfFailedRequests = 0; + let numberOfFailedRequests = 0; - var enableConsoleLog = false; + const enableConsoleLog = false; - var country = typeof unsafeWindow.g_strCountryCode !== 'undefined' ? unsafeWindow.g_strCountryCode : undefined; - var isLoggedIn = typeof unsafeWindow.g_rgWalletInfo !== 'undefined' && unsafeWindow.g_rgWalletInfo != null || (typeof unsafeWindow.g_bLoggedIn !== 'undefined' && unsafeWindow.g_bLoggedIn); + const country = typeof unsafeWindow.g_strCountryCode !== 'undefined' ? unsafeWindow.g_strCountryCode : undefined; + const isLoggedIn = typeof unsafeWindow.g_rgWalletInfo !== 'undefined' && unsafeWindow.g_rgWalletInfo != null || typeof unsafeWindow.g_bLoggedIn !== 'undefined' && unsafeWindow.g_bLoggedIn; - var currentPage = window.location.href.includes('.com/market') ? - (window.location.href.includes('market/listings') ? - PAGE_MARKET_LISTING : - PAGE_MARKET) : - (window.location.href.includes('.com/tradeoffer') ? - PAGE_TRADEOFFER : - PAGE_INVENTORY); + const currentPage = window.location.href.includes('.com/market') + ? window.location.href.includes('market/listings') + ? PAGE_MARKET_LISTING + : PAGE_MARKET + : window.location.href.includes('.com/tradeoffer') + ? PAGE_TRADEOFFER + : PAGE_INVENTORY; - var market = new SteamMarket(unsafeWindow.g_rgAppContextData, + const market = new SteamMarket( + unsafeWindow.g_rgAppContextData, getInventoryUrl(), - isLoggedIn ? unsafeWindow.g_rgWalletInfo : undefined); + isLoggedIn ? unsafeWindow.g_rgWalletInfo : undefined + ); - var currencyId = + const currencyId = isLoggedIn && market != null && market.walletInfo != null && - market.walletInfo.wallet_currency != null ? - market.walletInfo.wallet_currency : - 3; + market.walletInfo.wallet_currency != null + ? market.walletInfo.wallet_currency + : 3; const currencyCountry = isLoggedIn && market != null && market.walletInfo != null && - market.walletInfo.wallet_country != null ? - market.walletInfo.wallet_country : - 'US'; + market.walletInfo.wallet_country != null + ? market.walletInfo.wallet_country + : 'US'; const currencyCode = unsafeWindow.GetCurrencyCode(currencyId); @@ -104,8 +104,9 @@ this.inventoryUrl = inventoryUrl; this.walletInfo = walletInfo; this.inventoryUrlBase = inventoryUrl.replace('/inventory/json', ''); - if (!this.inventoryUrlBase.endsWith('/')) + if (!this.inventoryUrlBase.endsWith('/')) { this.inventoryUrlBase += '/'; + } } @@ -119,7 +120,7 @@ if (unsafeWindow.g_strProfileURL) { profileUrl = unsafeWindow.g_strProfileURL; } else { - const avatar = document.querySelector( '#global_actions a.user_avatar' ); + const avatar = document.querySelector('#global_actions a.user_avatar'); if (avatar) { profileUrl = avatar.href; @@ -148,7 +149,7 @@ const SETTING_RELIST_AUTOMATICALLY = 'SETTING_RELIST_AUTOMATICALLY'; const SETTING_MARKET_PAGE_COUNT = 'SETTING_MARKET_PAGE_COUNT'; - var settingDefaults = { + const settingDefaults = { SETTING_MIN_NORMAL_PRICE: 0.05, SETTING_MAX_NORMAL_PRICE: 2.50, SETTING_MIN_FOIL_PRICE: 0.15, @@ -179,21 +180,22 @@ //#region Storage - var storagePersistent = localforage.createInstance({ + const storagePersistent = localforage.createInstance({ name: 'see_persistent' }); - var storageSession; + let storageSession; - var currentUrl = new URL(window.location.href); - var noCache = currentUrl.searchParams.get('no-cache') != null; + const currentUrl = new URL(window.location.href); + const noCache = currentUrl.searchParams.get('no-cache') != null; // This does not work the same as the 'normal' session storage because opening a new browser session/tab will clear the cache. // For this reason, a rolling cache is used. if (getSessionStorageItem('SESSION') == null || noCache) { - var lastCache = getSettingWithDefault(SETTING_LAST_CACHE); - if (lastCache > 5) + let lastCache = getSettingWithDefault(SETTING_LAST_CACHE); + if (lastCache > 5) { lastCache = 0; + } setSetting(SETTING_LAST_CACHE, lastCache + 1); @@ -213,6 +215,7 @@ try { return localStorage.getItem(name); } catch (e) { + logConsole('Failed to get local storage item ' + name + ', ' + e + '.'); return null; } } @@ -222,7 +225,7 @@ localStorage.setItem(name, value); return true; } catch (e) { - logConsole('Failed to set local storage item ' + name + ', ' + e + '.') + logConsole('Failed to set local storage item ' + name + ', ' + e + '.'); return false; } } @@ -231,6 +234,7 @@ try { return sessionStorage.getItem(name); } catch (e) { + logConsole('Failed to get session storage item ' + name + ', ' + e + '.'); return null; } } @@ -240,7 +244,7 @@ sessionStorage.setItem(name, value); return true; } catch (e) { - logConsole('Failed to set session storage item ' + name + ', ' + e + '.') + logConsole('Failed to set session storage item ' + name + ', ' + e + '.'); return false; } } @@ -252,32 +256,32 @@ } function getPriceInformationFromItem(item) { - var isTradingCard = getIsTradingCard(item); - var isFoilTradingCard = getIsFoilTradingCard(item); + const isTradingCard = getIsTradingCard(item); + const isFoilTradingCard = getIsFoilTradingCard(item); return getPriceInformation(isTradingCard, isFoilTradingCard); } function getPriceInformation(isTradingCard, isFoilTradingCard) { - var maxPrice = 0; - var minPrice = 0; + let maxPrice = 0; + let minPrice = 0; if (!isTradingCard) { maxPrice = getSettingWithDefault(SETTING_MAX_MISC_PRICE); minPrice = getSettingWithDefault(SETTING_MIN_MISC_PRICE); } else { - maxPrice = isFoilTradingCard ? - getSettingWithDefault(SETTING_MAX_FOIL_PRICE) : - getSettingWithDefault(SETTING_MAX_NORMAL_PRICE); - minPrice = isFoilTradingCard ? - getSettingWithDefault(SETTING_MIN_FOIL_PRICE) : - getSettingWithDefault(SETTING_MIN_NORMAL_PRICE); + maxPrice = isFoilTradingCard + ? getSettingWithDefault(SETTING_MAX_FOIL_PRICE) + : getSettingWithDefault(SETTING_MAX_NORMAL_PRICE); + minPrice = isFoilTradingCard + ? getSettingWithDefault(SETTING_MIN_FOIL_PRICE) + : getSettingWithDefault(SETTING_MIN_NORMAL_PRICE); } maxPrice = maxPrice * 100.0; minPrice = minPrice * 100.0; - var maxPriceBeforeFees = market.getPriceBeforeFees(maxPrice); - var minPriceBeforeFees = market.getPriceBeforeFees(minPrice); + const maxPriceBeforeFees = market.getPriceBeforeFees(maxPrice); + const minPriceBeforeFees = market.getPriceBeforeFees(minPrice); return { maxPrice, @@ -289,15 +293,15 @@ // Calculates the average history price, before the fee. function calculateAverageHistoryPriceBeforeFees(history) { - var highest = 0; - var total = 0; + let highest = 0; + let total = 0; if (history != null) { // Highest average price in the last xx hours. - var timeAgo = Date.now() - (getSettingWithDefault(SETTING_PRICE_HISTORY_HOURS) * 60 * 60 * 1000); + const timeAgo = Date.now() - getSettingWithDefault(SETTING_PRICE_HISTORY_HOURS) * 60 * 60 * 1000; - history.forEach(function(historyItem) { - var d = new Date(historyItem[0]); + history.forEach((historyItem) => { + const d = new Date(historyItem[0]); if (d.getTime() > timeAgo) { highest += historyItem[1] * historyItem[2]; total += historyItem[2]; @@ -305,8 +309,9 @@ }); } - if (total == 0) + if (total == 0) { return 0; + } highest = Math.floor(highest / total); return market.getPriceBeforeFees(highest); @@ -315,23 +320,24 @@ // Calculates the listing price, before the fee. function calculateListingPriceBeforeFees(histogram) { if (typeof histogram === 'undefined' || - histogram == null || - histogram.lowest_sell_order == null || - histogram.sell_order_graph == null) + histogram == null || + histogram.lowest_sell_order == null || + histogram.sell_order_graph == null) { return 0; + } - var listingPrice = market.getPriceBeforeFees(histogram.lowest_sell_order); + let listingPrice = market.getPriceBeforeFees(histogram.lowest_sell_order); - var shouldIgnoreLowestListingOnLowQuantity = getSettingWithDefault(SETTING_PRICE_IGNORE_LOWEST_Q) == 1; + const shouldIgnoreLowestListingOnLowQuantity = getSettingWithDefault(SETTING_PRICE_IGNORE_LOWEST_Q) == 1; if (shouldIgnoreLowestListingOnLowQuantity && histogram.sell_order_graph.length >= 2) { - var listingPrice2ndLowest = market.getPriceBeforeFees(histogram.sell_order_graph[1][0] * 100); + const listingPrice2ndLowest = market.getPriceBeforeFees(histogram.sell_order_graph[1][0] * 100); if (listingPrice2ndLowest > listingPrice) { - var numberOfListingsLowest = histogram.sell_order_graph[0][1]; - var numberOfListings2ndLowest = histogram.sell_order_graph[1][1]; + const numberOfListingsLowest = histogram.sell_order_graph[0][1]; + const numberOfListings2ndLowest = histogram.sell_order_graph[1][1]; - var percentageLower = (100 * (numberOfListingsLowest / numberOfListings2ndLowest)); + const percentageLower = 100 * (numberOfListingsLowest / numberOfListings2ndLowest); // The percentage should change based on the quantity (for example, 1200 listings vs 5, or 1 vs 25). if (numberOfListings2ndLowest >= 1000 && percentageLower <= 5) { @@ -354,8 +360,9 @@ } function calculateBuyOrderPriceBeforeFees(histogram) { - if (typeof histogram === 'undefined') + if (typeof histogram === 'undefined') { return 0; + } return market.getPriceBeforeFees(histogram.highest_buy_order); } @@ -363,16 +370,16 @@ // Calculate the sell price based on the history and listings. // applyOffset specifies whether the price offset should be applied when the listings are used to determine the price. function calculateSellPriceBeforeFees(history, histogram, applyOffset, minPriceBeforeFees, maxPriceBeforeFees) { - var historyPrice = calculateAverageHistoryPriceBeforeFees(history); - var listingPrice = calculateListingPriceBeforeFees(histogram); - var buyPrice = calculateBuyOrderPriceBeforeFees(histogram); + const historyPrice = calculateAverageHistoryPriceBeforeFees(history); + const listingPrice = calculateListingPriceBeforeFees(histogram); + const buyPrice = calculateBuyOrderPriceBeforeFees(histogram); - var shouldUseAverage = getSettingWithDefault(SETTING_PRICE_ALGORITHM) == 1; - var shouldUseBuyOrder = getSettingWithDefault(SETTING_PRICE_ALGORITHM) == 3; + const shouldUseAverage = getSettingWithDefault(SETTING_PRICE_ALGORITHM) == 1; + const shouldUseBuyOrder = getSettingWithDefault(SETTING_PRICE_ALGORITHM) == 3; // If the highest average price is lower than the first listing, return the offset + that listing. // Otherwise, use the highest average price instead. - var calculatedPrice = 0; + let calculatedPrice = 0; if (shouldUseBuyOrder && buyPrice !== -2) { calculatedPrice = buyPrice; } else if (historyPrice < listingPrice || !shouldUseAverage) { @@ -381,7 +388,7 @@ calculatedPrice = historyPrice; } - var changedToMax = false; + let changedToMax = false; // List for the maximum price if there are no listings yet. if (calculatedPrice == 0) { calculatedPrice = maxPriceBeforeFees; @@ -391,7 +398,7 @@ // Apply the offset to the calculated price, but only if the price wasn't changed to the max (as otherwise it's impossible to list for this price). if (!changedToMax && applyOffset) { - calculatedPrice = calculatedPrice + (getSettingWithDefault(SETTING_PRICE_OFFSET) * 100); + calculatedPrice = calculatedPrice + getSettingWithDefault(SETTING_PRICE_OFFSET) * 100; } @@ -401,9 +408,10 @@ // In case there's a buy order higher than the calculated price. if (typeof histogram !== 'undefined' && histogram != null && histogram.highest_buy_order != null) { - var buyOrderPrice = market.getPriceBeforeFees(histogram.highest_buy_order); - if (buyOrderPrice > calculatedPrice) + const buyOrderPrice = market.getPriceBeforeFees(histogram.highest_buy_order); + if (buyOrderPrice > calculatedPrice) { calculatedPrice = buyOrderPrice; + } } return calculatedPrice; @@ -416,12 +424,12 @@ } function getNumberOfDigits(x) { - return (Math.log10((x ^ (x >> 31)) - (x >> 31)) | 0) + 1; + return (Math.log10((x ^ x >> 31) - (x >> 31)) | 0) + 1; } function padLeftZero(str, max) { str = str.toString(); - return str.length < max ? padLeftZero("0" + str, max) : str; + return str.length < max ? padLeftZero('0' + str, max) : str; } function replaceNonNumbers(str) { @@ -433,11 +441,11 @@ // Sell an item with a price in cents. // Price is before fees. - SteamMarket.prototype.sellItem = function(item, price, callback /*err, data*/ ) { - var sessionId = readCookie('sessionid'); - var itemId = item.assetid || item.id; + SteamMarket.prototype.sellItem = function(item, price, callback /*err, data*/) { + const sessionId = readCookie('sessionid'); + const itemId = item.assetid || item.id; $.ajax({ - type: "POST", + type: 'POST', url: window.location.origin + '/market/sellitem/', data: { sessionid: sessionId, @@ -463,21 +471,21 @@ // Removes an item. // Item is the unique item id. - SteamMarket.prototype.removeListing = function(item, isBuyOrder, callback /*err, data*/ ) { - var sessionId = readCookie('sessionid'); + SteamMarket.prototype.removeListing = function(item, isBuyOrder, callback /*err, data*/) { + const sessionId = readCookie('sessionid'); if (isBuyOrder) { $.ajax({ - type: "POST", + type: 'POST', url: window.location.origin + '/market/cancelbuyorder/', data: { sessionid: sessionId, buy_orderid: item }, - success: function (data) { + success: function(data) { callback(ERROR_SUCCESS, data); }, - error: function () { + error: function() { return callback(ERROR_FAILED); }, dataType: 'json' @@ -486,7 +494,7 @@ } $.ajax({ - type: "POST", + type: 'POST', url: window.location.origin + '/market/removelisting/' + item, data: { sessionid: sessionId @@ -509,44 +517,46 @@ // Price is inclusive of fees. SteamMarket.prototype.getPriceHistory = function(item, cache, callback) { try { - var market_name = getMarketHashName(item); + const market_name = getMarketHashName(item); if (market_name == null) { callback(ERROR_FAILED); return; } - var appid = item.appid; + const appid = item.appid; if (cache) { - var storage_hash = 'pricehistory_' + appid + '+' + market_name; + const storage_hash = 'pricehistory_' + appid + '+' + market_name; - storageSession.getItem(storage_hash) - .then(function(value) { - if (value != null) + storageSession.getItem(storage_hash). + then((value) => { + if (value != null) { callback(ERROR_SUCCESS, value, true); - else + } else { market.getCurrentPriceHistory(appid, market_name, callback); - }) - .catch(function(error) { + } + }). + catch(() => { market.getCurrentPriceHistory(appid, market_name, callback); }); - } else + } else { market.getCurrentPriceHistory(appid, market_name, callback); - } catch (e) { + } + } catch { return callback(ERROR_FAILED); } }; SteamMarket.prototype.getGooValue = function(item, callback) { try { - var appid = item.market_fee_app; + let appid = item.market_fee_app; for (const action of item.owner_actions) { if (!action.link || !action.link.startsWith('javascript:GetGooValue')) { continue; } - var rgMatches = action.link.match( /GetGooValue\( *'%contextid%', *'%assetid%', *'?(?[0-9]+)'?/ ); + const rgMatches = action.link.match(/GetGooValue\( *'%contextid%', *'%assetid%', *'?(?[0-9]+)'?/); if (!rgMatches) { continue; @@ -556,9 +566,9 @@ break; } - var sessionId = readCookie('sessionid'); + const sessionId = readCookie('sessionid'); $.ajax({ - type: "GET", + type: 'GET', url: this.inventoryUrlBase + 'ajaxgetgoovalue/', data: { sessionid: sessionId, @@ -574,7 +584,7 @@ }, dataType: 'json' }); - } catch (e) { + } catch { return callback(ERROR_FAILED); } //http://steamcommunity.com/auction/ajaxgetgoovalueforitemtype/?appid=582980&item_type=18&border_color=0 @@ -584,15 +594,15 @@ //appid = 535690 //assetid = 4830605461 //contextid = 6 - } + }; // Grinds the item into gems. SteamMarket.prototype.grindIntoGoo = function(item, callback) { try { - var sessionId = readCookie('sessionid'); + const sessionId = readCookie('sessionid'); $.ajax({ - type: "POST", + type: 'POST', url: this.inventoryUrlBase + 'ajaxgrindintogoo/', data: { sessionid: sessionId, @@ -609,7 +619,7 @@ }, dataType: 'json' }); - } catch (e) { + } catch { return callback(ERROR_FAILED); } @@ -619,15 +629,15 @@ //contextid = 6 //goo_value_expected = 10 //http://steamcommunity.com/my/ajaxgrindintogoo/ - } + }; // Unpacks the booster pack. SteamMarket.prototype.unpackBoosterPack = function(item, callback) { try { - var sessionId = readCookie('sessionid'); + const sessionId = readCookie('sessionid'); $.ajax({ - type: "POST", + type: 'POST', url: this.inventoryUrlBase + 'ajaxunpackbooster/', data: { sessionid: sessionId, @@ -642,7 +652,7 @@ }, dataType: 'json' }); - } catch (e) { + } catch { return callback(ERROR_FAILED); } @@ -650,37 +660,39 @@ //appid = 535690 //communityitemid = 4830605461 //http://steamcommunity.com/my/ajaxunpackbooster/ - } + }; // Get the current price history for an item. SteamMarket.prototype.getCurrentPriceHistory = function(appid, market_name, callback) { - var url = window.location.origin + - '/market/pricehistory/?appid=' + - appid + - '&market_hash_name=' + - market_name; - - $.get(url, - function(data) { - if (!data || !data.success || !data.prices) { - callback(ERROR_DATA); - return; - } + const url = window.location.origin + + '/market/pricehistory/?appid=' + + appid + + '&market_hash_name=' + + market_name; + + $.get( + url, + (data) => { + if (!data || !data.success || !data.prices) { + callback(ERROR_DATA); + return; + } - // Multiply prices so they're in pennies. - for (var i = 0; i < data.prices.length; i++) { - data.prices[i][1] *= 100; - data.prices[i][2] = parseInt(data.prices[i][2]); - } + // Multiply prices so they're in pennies. + for (let i = 0; i < data.prices.length; i++) { + data.prices[i][1] *= 100; + data.prices[i][2] = parseInt(data.prices[i][2]); + } - // Store the price history in the session storage. - var storage_hash = 'pricehistory_' + appid + '+' + market_name; - storageSession.setItem(storage_hash, data.prices); + // Store the price history in the session storage. + const storage_hash = 'pricehistory_' + appid + '+' + market_name; + storageSession.setItem(storage_hash, data.prices); - callback(ERROR_SUCCESS, data.prices, false); - }, - 'json') - .fail(function(data) { + callback(ERROR_SUCCESS, data.prices, false); + }, + 'json' + ). + fail((data) => { if (!data || !data.responseJSON) { return callback(ERROR_FAILED); } @@ -690,57 +702,60 @@ } return callback(ERROR_FAILED); }); - } + }; // Get the item name id from a market item. // // This id never changes so we can store this in the persistent storage. SteamMarket.prototype.getMarketItemNameId = function(item, callback) { try { - var market_name = getMarketHashName(item); + const market_name = getMarketHashName(item); if (market_name == null) { callback(ERROR_FAILED); return; } - var appid = item.appid; - var storage_hash = 'itemnameid_' + appid + '+' + market_name; + const appid = item.appid; + const storage_hash = 'itemnameid_' + appid + '+' + market_name; - storagePersistent.getItem(storage_hash) - .then(function(value) { - if (value != null) + storagePersistent.getItem(storage_hash). + then((value) => { + if (value != null) { callback(ERROR_SUCCESS, value); - else + } else { return market.getCurrentMarketItemNameId(appid, market_name, callback); - }) - .catch(function(error) { + } + }). + catch(() => { return market.getCurrentMarketItemNameId(appid, market_name, callback); }); - } catch (e) { + } catch { return callback(ERROR_FAILED); } - } + }; // Get the item name id from a market item. SteamMarket.prototype.getCurrentMarketItemNameId = function(appid, market_name, callback) { - var url = window.location.origin + '/market/listings/' + appid + '/' + market_name; - $.get(url, - function(page) { - var matches = /Market_LoadOrderSpread\( (\d+) \);/.exec(page); - if (matches == null) { - callback(ERROR_DATA); - return; - } + const url = window.location.origin + '/market/listings/' + appid + '/' + market_name; + $.get( + url, + (page) => { + const matches = (/Market_LoadOrderSpread\( (\d+) \);/).exec(page); + if (matches == null) { + callback(ERROR_DATA); + return; + } - var item_nameid = matches[1]; + const item_nameid = matches[1]; - // Store the item name id in the persistent storage. - var storage_hash = 'itemnameid_' + appid + '+' + market_name; - storagePersistent.setItem(storage_hash, item_nameid); + // Store the item name id in the persistent storage. + const storage_hash = 'itemnameid_' + appid + '+' + market_name; + storagePersistent.setItem(storage_hash, item_nameid); - callback(ERROR_SUCCESS, item_nameid); - }) - .fail(function(e) { + callback(ERROR_SUCCESS, item_nameid); + } + ). + fail((e) => { return callback(ERROR_FAILED, e.status); }); }; @@ -765,252 +780,278 @@ //} SteamMarket.prototype.getItemOrdersHistogram = function(item, cache, callback) { try { - var market_name = getMarketHashName(item); + const market_name = getMarketHashName(item); if (market_name == null) { callback(ERROR_FAILED); return; } - var appid = item.appid; + const appid = item.appid; if (cache) { - var storage_hash = 'itemordershistogram_' + appid + '+' + market_name; - storageSession.getItem(storage_hash) - .then(function(value) { - if (value != null) + const storage_hash = 'itemordershistogram_' + appid + '+' + market_name; + storageSession.getItem(storage_hash). + then((value) => { + if (value != null) { callback(ERROR_SUCCESS, value, true); - else { + } else { market.getCurrentItemOrdersHistogram(item, market_name, callback); } - }) - .catch(function(error) { + }). + catch(() => { market.getCurrentItemOrdersHistogram(item, market_name, callback); }); } else { market.getCurrentItemOrdersHistogram(item, market_name, callback); } - } catch (e) { + } catch { return callback(ERROR_FAILED); } }; // Get the sales listings for this item in the market, with more information. SteamMarket.prototype.getCurrentItemOrdersHistogram = function(item, market_name, callback) { - market.getMarketItemNameId(item, - function(error, item_nameid) { + market.getMarketItemNameId( + item, + (error, item_nameid) => { if (error) { - if (item_nameid != 429) // 429 = Too many requests made. + if (item_nameid != 429) { // 429 = Too many requests made. callback(ERROR_DATA); - else + } else { callback(ERROR_FAILED); + } return; } - var url = window.location.origin + - '/market/itemordershistogram?country=' + - country + - '&language=english¤cy=' + - currencyId + - '&item_nameid=' + - item_nameid + - '&two_factor=0'; - - $.get(url, - function(histogram) { - // Store the histogram in the session storage. - var storage_hash = 'itemordershistogram_' + item.appid + '+' + market_name; - storageSession.setItem(storage_hash, histogram); - - callback(ERROR_SUCCESS, histogram, false); - }) - .fail(function() { + const url = window.location.origin + + '/market/itemordershistogram?country=' + + country + + '&language=english¤cy=' + + currencyId + + '&item_nameid=' + + item_nameid + + '&two_factor=0'; + + $.get( + url, + (histogram) => { + // Store the histogram in the session storage. + const storage_hash = 'itemordershistogram_' + item.appid + '+' + market_name; + storageSession.setItem(storage_hash, histogram); + + callback(ERROR_SUCCESS, histogram, false); + } + ). + fail(() => { return callback(ERROR_FAILED, null); }); - }); + } + ); }; // Calculate the price before fees (seller price) from the buyer price SteamMarket.prototype.getPriceBeforeFees = function(price, item) { - var publisherFee = -1; + let publisherFee = -1; if (item != null) { - if (item.market_fee != null) + if (item.market_fee != null) { publisherFee = item.market_fee; - else if (item.description != null && item.description.market_fee != null) + } else if (item.description != null && item.description.market_fee != null) { publisherFee = item.description.market_fee; + } } if (publisherFee == -1) { - if (this.walletInfo != null) + if (this.walletInfo != null) { publisherFee = this.walletInfo['wallet_publisher_fee_percent_default']; - else + } else { publisherFee = 0.10; + } } price = Math.round(price); - var feeInfo = CalculateFeeAmount(price, publisherFee, this.walletInfo); + const feeInfo = CalculateFeeAmount(price, publisherFee, this.walletInfo); return price - feeInfo.fees; }; // Calculate the buyer price from the seller price SteamMarket.prototype.getPriceIncludingFees = function(price, item) { - var publisherFee = -1; + let publisherFee = -1; if (item != null) { - if (item.market_fee != null) + if (item.market_fee != null) { publisherFee = item.market_fee; - else if (item.description != null && item.description.market_fee != null) + } else if (item.description != null && item.description.market_fee != null) { publisherFee = item.description.market_fee; + } } if (publisherFee == -1) { - if (this.walletInfo != null) + if (this.walletInfo != null) { publisherFee = this.walletInfo['wallet_publisher_fee_percent_default']; - else + } else { publisherFee = 0.10; + } } price = Math.round(price); - var feeInfo = CalculateAmountToSendForDesiredReceivedAmount(price, publisherFee, this.walletInfo); + const feeInfo = CalculateAmountToSendForDesiredReceivedAmount(price, publisherFee, this.walletInfo); return feeInfo.amount; }; //#endregion - function replaceAll(str, find, replace) { - return str.replace(new RegExp(find, 'g'), replace); - } - // Cannot use encodeURI / encodeURIComponent, Steam only escapes certain characters. function escapeURI(name) { - var previousName = ''; + let previousName = ''; while (previousName != name) { previousName = name; - name = name.replace('?', '%3F') - .replace('#', '%23') - .replace(' ', '%09'); + name = name.replace('?', '%3F'). + replace('#', '%23'). + replace(' ', '%09'); } return name; } //#region Steam Market / Inventory helpers function getMarketHashName(item) { - if (item == null) + if (item == null) { return null; + } - if (item.description != null && item.description.market_hash_name != null) + if (item.description != null && item.description.market_hash_name != null) { return escapeURI(item.description.market_hash_name); + } - if (item.description != null && item.description.name != null) + if (item.description != null && item.description.name != null) { return escapeURI(item.description.name); + } - if (item.market_hash_name != null) + if (item.market_hash_name != null) { return escapeURI(item.market_hash_name); + } - if (item.name != null) + if (item.name != null) { return escapeURI(item.name); + } return null; } function getIsCrate(item) { - if (item == null) + if (item == null) { return false; + } // This is available on the inventory page. - var tags = item.tags != null ? - item.tags : - (item.description != null && item.description.tags != null ? - item.description.tags : - null); + const tags = item.tags != null + ? item.tags + : item.description != null && item.description.tags != null + ? item.description.tags + : null; if (tags != null) { - var isTaggedAsCrate = false; - tags.forEach(function (arrayItem) { - if (arrayItem.category == 'Type') - if (arrayItem.internal_name == 'Supply Crate') + let isTaggedAsCrate = false; + tags.forEach((arrayItem) => { + if (arrayItem.category == 'Type') { + if (arrayItem.internal_name == 'Supply Crate') { isTaggedAsCrate = true; + } + } }); - if (isTaggedAsCrate) + if (isTaggedAsCrate) { return true; + } } } function getIsTradingCard(item) { - if (item == null) + if (item == null) { return false; + } // This is available on the inventory page. - var tags = item.tags != null ? - item.tags : - (item.description != null && item.description.tags != null ? - item.description.tags : - null); + const tags = item.tags != null + ? item.tags + : item.description != null && item.description.tags != null + ? item.description.tags + : null; if (tags != null) { - var isTaggedAsTradingCard = false; - tags.forEach(function(arrayItem) { - if (arrayItem.category == 'item_class') - if (arrayItem.internal_name == 'item_class_2') // trading card. + let isTaggedAsTradingCard = false; + tags.forEach((arrayItem) => { + if (arrayItem.category == 'item_class') { + if (arrayItem.internal_name == 'item_class_2') { // trading card. isTaggedAsTradingCard = true; + } + } }); - if (isTaggedAsTradingCard) + if (isTaggedAsTradingCard) { return true; + } } // This is available on the market page. if (item.owner_actions != null) { - for (var i = 0; i < item.owner_actions.length; i++) { - if (item.owner_actions[i].link == null) + for (let i = 0; i < item.owner_actions.length; i++) { + if (item.owner_actions[i].link == null) { continue; + } // Cards include a link to the gamecard page. // For example: "http://steamcommunity.com/my/gamecards/503820/". - if (item.owner_actions[i].link.toString().toLowerCase().includes('gamecards')) + if (item.owner_actions[i].link.toString().toLowerCase().includes('gamecards')) { return true; + } } } // A fallback for the market page (only works with language on English). - if (item.type != null && item.type.toLowerCase().includes('trading card')) + if (item.type != null && item.type.toLowerCase().includes('trading card')) { return true; + } return false; } function getIsFoilTradingCard(item) { - if (!getIsTradingCard(item)) + if (!getIsTradingCard(item)) { return false; + } // This is available on the inventory page. - var tags = item.tags != null ? - item.tags : - (item.description != null && item.description.tags != null ? - item.description.tags : - null); + const tags = item.tags != null + ? item.tags + : item.description != null && item.description.tags != null + ? item.description.tags + : null; if (tags != null) { - var isTaggedAsFoilTradingCard = false; - tags.forEach(function(arrayItem) { - if (arrayItem.category == 'cardborder') - if (arrayItem.internal_name == 'cardborder_1') // foil border. - isTaggedAsFoilTradingCard = true; + let isTaggedAsFoilTradingCard = false; + tags.forEach((arrayItem) => { + if (arrayItem.category == 'cardborder' && arrayItem.internal_name == 'cardborder_1') { // foil border. + isTaggedAsFoilTradingCard = true; + } }); - if (isTaggedAsFoilTradingCard) + if (isTaggedAsFoilTradingCard) { return true; + } } // This is available on the market page. if (item.owner_actions != null) { - for (var i = 0; i < item.owner_actions.length; i++) { - if (item.owner_actions[i].link == null) + for (let i = 0; i < item.owner_actions.length; i++) { + if (item.owner_actions[i].link == null) { continue; + } // Cards include a link to the gamecard page. // The border parameter specifies the foil cards. // For example: "http://steamcommunity.com/my/gamecards/503820/?border=1". if (item.owner_actions[i].link.toString().toLowerCase().includes('gamecards') && - item.owner_actions[i].link.toString().toLowerCase().includes('border')) + item.owner_actions[i].link.toString().toLowerCase().includes('border')) { return true; + } } } // A fallback for the market page (only works with language on English). - if (item.type != null && item.type.toLowerCase().includes('foil trading card')) + if (item.type != null && item.type.toLowerCase().includes('foil trading card')) { return true; + } return false; } @@ -1022,25 +1063,28 @@ }; } - publisherFee = (publisherFee == null) ? 0 : publisherFee; + publisherFee = publisherFee == null ? 0 : publisherFee; // Since CalculateFeeAmount has a Math.floor, we could be off a cent or two. Let's check: - var iterations = 0; // shouldn't be needed, but included to be sure nothing unforseen causes us to get stuck - var nEstimatedAmountOfWalletFundsReceivedByOtherParty = + let iterations = 0; // shouldn't be needed, but included to be sure nothing unforseen causes us to get stuck + let nEstimatedAmountOfWalletFundsReceivedByOtherParty = parseInt((amount - parseInt(walletInfo['wallet_fee_base'])) / - (parseFloat(walletInfo['wallet_fee_percent']) + parseFloat(publisherFee) + 1)); - var bEverUndershot = false; - var fees = CalculateAmountToSendForDesiredReceivedAmount(nEstimatedAmountOfWalletFundsReceivedByOtherParty, + (parseFloat(walletInfo['wallet_fee_percent']) + parseFloat(publisherFee) + 1)); + let bEverUndershot = false; + let fees = CalculateAmountToSendForDesiredReceivedAmount( + nEstimatedAmountOfWalletFundsReceivedByOtherParty, publisherFee, - walletInfo); + walletInfo + ); while (fees.amount != amount && iterations < 10) { if (fees.amount > amount) { if (bEverUndershot) { fees = CalculateAmountToSendForDesiredReceivedAmount( nEstimatedAmountOfWalletFundsReceivedByOtherParty - 1, publisherFee, - walletInfo); - fees.steam_fee += (amount - fees.amount); - fees.fees += (amount - fees.amount); + walletInfo + ); + fees.steam_fee += amount - fees.amount; + fees.fees += amount - fees.amount; fees.amount = amount; break; } else { @@ -1050,9 +1094,11 @@ bEverUndershot = true; nEstimatedAmountOfWalletFundsReceivedByOtherParty++; } - fees = CalculateAmountToSendForDesiredReceivedAmount(nEstimatedAmountOfWalletFundsReceivedByOtherParty, + fees = CalculateAmountToSendForDesiredReceivedAmount( + nEstimatedAmountOfWalletFundsReceivedByOtherParty, publisherFee, - walletInfo); + walletInfo + ); iterations++; } // fees.amount should equal the passed in amount @@ -1061,11 +1107,13 @@ // Clamps cur between min and max (inclusive). function clamp(cur, min, max) { - if (cur < min) + if (cur < min) { cur = min; + } - if (cur > max) + if (cur > max) { cur = max; + } return cur; } @@ -1078,12 +1126,14 @@ }; } - publisherFee = (publisherFee == null) ? 0 : publisherFee; - var nSteamFee = parseInt(Math.floor(Math.max(receivedAmount * parseFloat(walletInfo['wallet_fee_percent']), - walletInfo['wallet_fee_minimum']) + - parseInt(walletInfo['wallet_fee_base']))); - var nPublisherFee = parseInt(Math.floor(publisherFee > 0 ? Math.max(receivedAmount * publisherFee, 1) : 0)); - var nAmountToSend = receivedAmount + nSteamFee + nPublisherFee; + publisherFee = publisherFee == null ? 0 : publisherFee; + const nSteamFee = parseInt(Math.floor(Math.max( + receivedAmount * parseFloat(walletInfo['wallet_fee_percent']), + walletInfo['wallet_fee_minimum'] + ) + + parseInt(walletInfo['wallet_fee_base']))); + const nPublisherFee = parseInt(Math.floor(publisherFee > 0 ? Math.max(receivedAmount * publisherFee, 1) : 0)); + const nAmountToSend = receivedAmount + nSteamFee + nPublisherFee; return { steam_fee: nSteamFee, publisher_fee: nPublisherFee, @@ -1093,23 +1143,25 @@ } function readCookie(name) { - var nameEQ = name + "="; - var ca = document.cookie.split(';'); - for (var i = 0; i < ca.length; i++) { - var c = ca[i]; - while (c.charAt(0) == ' ') + const nameEQ = name + '='; + const ca = document.cookie.split(';'); + for (let i = 0; i < ca.length; i++) { + let c = ca[i]; + while (c.charAt(0) == ' ') { c = c.substring(1, c.length); - if (c.indexOf(nameEQ) == 0) + } + if (c.indexOf(nameEQ) == 0) { return decodeURIComponent(c.substring(nameEQ.length, c.length)); + } } return null; } function isRetryMessage(message) { - var messageList = [ - "You cannot sell any items until your previous action completes.", - "There was a problem listing your item. Refresh the page and try again.", - "We were unable to contact the game's item server. The game's item server may be down or Steam may be experiencing temporary connectivity issues. Your listing has not been created. Refresh the page and try again." + const messageList = [ + 'You cannot sell any items until your previous action completes.', + 'There was a problem listing your item. Refresh the page and try again.', + 'We were unable to contact the game\'s item server. The game\'s item server may be down or Steam may be experiencing temporary connectivity issues. Your listing has not been created. Refresh the page and try again.' ]; return messageList.indexOf(message) !== -1; @@ -1117,13 +1169,13 @@ //#endregion //#region Logging - var userScrolled = false; - var logger = document.createElement('div'); + let userScrolled = false; + const logger = document.createElement('div'); logger.setAttribute('id', 'logger'); function updateScroll() { if (!userScrolled) { - var element = document.getElementById("logger"); + const element = document.getElementById('logger'); element.scrollTop = element.scrollHeight; } } @@ -1134,12 +1186,6 @@ updateScroll(); } - function clearLogDOM() { - logger.innerHTML = ''; - - updateScroll(); - } - function logConsole(text) { if (enableConsoleLog) { console.log(text); @@ -1161,93 +1207,99 @@ $(logger).parent().append('
'); } - var totals = document.getElementById('loggerTotal'); + const totals = document.getElementById('loggerTotal'); totals.innerHTML = ''; if (totalPriceWithFeesOnMarket > 0) { totals.innerHTML += '
Total listed for ' + - formatPrice(totalPriceWithFeesOnMarket) + - ', you will receive ' + - formatPrice(totalPriceWithoutFeesOnMarket) + - '.
'; + formatPrice(totalPriceWithFeesOnMarket) + + ', you will receive ' + + formatPrice(totalPriceWithoutFeesOnMarket) + + '.'; } if (totalScrap > 0) { totals.innerHTML += '
Total scrap ' + totalScrap + '.
'; } } - var sellQueue = async.queue(function(task, next) { - market.sellItem(task.item, + const sellQueue = async.queue( + (task, next) => { + market.sellItem( + task.item, task.sellPrice, - function(err, data) { + (err, data) => { totalNumberOfProcessedQueueItems++; - var digits = getNumberOfDigits(totalNumberOfQueuedItems); - var itemId = task.item.assetid || task.item.id; - var itemName = task.item.name || task.item.description.name; - var padLeft = padLeftZero('' + totalNumberOfProcessedQueueItems, digits) + ' / ' + totalNumberOfQueuedItems; + const digits = getNumberOfDigits(totalNumberOfQueuedItems); + const itemId = task.item.assetid || task.item.id; + const itemName = task.item.name || task.item.description.name; + const padLeft = padLeftZero('' + totalNumberOfProcessedQueueItems, digits) + ' / ' + totalNumberOfQueuedItems; if (!err) { logDOM(padLeft + - ' - ' + - itemName + - ' listed for ' + - formatPrice(market.getPriceIncludingFees(task.sellPrice)) + - ', you will receive ' + - formatPrice(task.sellPrice) + - '.'); + ' - ' + + itemName + + ' listed for ' + + formatPrice(market.getPriceIncludingFees(task.sellPrice)) + + ', you will receive ' + + formatPrice(task.sellPrice) + + '.'); - $('#' + task.item.appid + '_' + task.item.contextid + '_' + itemId) - .css('background', COLOR_SUCCESS); + $('#' + task.item.appid + '_' + task.item.contextid + '_' + itemId). + css('background', COLOR_SUCCESS); totalPriceWithoutFeesOnMarket += task.sellPrice; totalPriceWithFeesOnMarket += market.getPriceIncludingFees(task.sellPrice); updateTotals(); } else if (data != null && isRetryMessage(data.message)) { logDOM(padLeft + - ' - ' + - itemName + - ' retrying listing because ' + - data.message[0].toLowerCase() + - data.message.slice(1)); + ' - ' + + itemName + + ' retrying listing because ' + + data.message[0].toLowerCase() + + data.message.slice(1)); totalNumberOfProcessedQueueItems--; sellQueue.unshift(task); sellQueue.pause(); - setTimeout(function() { + setTimeout(() => { sellQueue.resume(); }, getRandomInt(30000, 45000)); } else { if (data != null && data.responseJSON != null && data.responseJSON.message != null) { logDOM(padLeft + - ' - ' + - itemName + - ' not added to market because ' + - data.responseJSON.message[0].toLowerCase() + - data.responseJSON.message.slice(1)); - } else + ' - ' + + itemName + + ' not added to market because ' + + data.responseJSON.message[0].toLowerCase() + + data.responseJSON.message.slice(1)); + } else { logDOM(padLeft + ' - ' + itemName + ' not added to market.'); + } - $('#' + task.item.appid + '_' + task.item.contextid + '_' + itemId) - .css('background', COLOR_ERROR); + $('#' + task.item.appid + '_' + task.item.contextid + '_' + itemId). + css('background', COLOR_ERROR); } next(); - }); + } + ); }, - 1); + 1 + ); sellQueue.drain = function() { onQueueDrain(); - } + }; - function sellAllItems(appId) { - loadAllInventories().then(function() { - var items = getInventoryItems(); - var filteredItems = []; + function sellAllItems() { + loadAllInventories().then( + () => { + const items = getInventoryItems(); + const filteredItems = []; - items.forEach(function(item) { + items.forEach((item) => { if (!item.marketable) { return; } @@ -1257,87 +1309,94 @@ sellItems(filteredItems); }, - function() { + () => { logDOM('Could not retrieve the inventory...'); - }); + } + ); } function sellAllDuplicateItems() { - loadAllInventories().then(function () { - var items = getInventoryItems(); - var marketableItems = []; - var filteredItems = []; + loadAllInventories().then( + () => { + const items = getInventoryItems(); + const marketableItems = []; + let filteredItems = []; - items.forEach(function (item) { - if (!item.marketable) { - return; - } + items.forEach((item) => { + if (!item.marketable) { + return; + } - marketableItems.push(item); - }); + marketableItems.push(item); + }); - filteredItems = marketableItems.filter((e, i) => marketableItems.map(m => m.classid).indexOf(e.classid) !== i); + filteredItems = marketableItems.filter((e, i) => marketableItems.map((m) => m.classid).indexOf(e.classid) !== i); - sellItems(filteredItems); - }, - function () { - logDOM('Could not retrieve the inventory...'); - }); + sellItems(filteredItems); + }, + () => { + logDOM('Could not retrieve the inventory...'); + } + ); } function gemAllDuplicateItems() { - loadAllInventories().then(function () { - var items = getInventoryItems(); - var filteredItems = []; - var numberOfQueuedItems = 0; + loadAllInventories().then( + () => { + const items = getInventoryItems(); + let filteredItems = []; + let numberOfQueuedItems = 0; - filteredItems = items.filter((e, i) => items.map(m => m.classid).indexOf(e.classid) !== i); + filteredItems = items.filter((e, i) => items.map((m) => m.classid).indexOf(e.classid) !== i); - filteredItems.forEach(function (item) { - if (item.queued != null) { - return; - } + filteredItems.forEach((item) => { + if (item.queued != null) { + return; + } - if (item.owner_actions == null) { - return; - } + if (item.owner_actions == null) { + return; + } - var canTurnIntoGems = false; - for (var owner_action in item.owner_actions) { - if (item.owner_actions[owner_action].link != null && item.owner_actions[owner_action].link.includes('GetGooValue')) { - canTurnIntoGems = true; + let canTurnIntoGems = false; + for (const owner_action in item.owner_actions) { + if (item.owner_actions[owner_action].link != null && item.owner_actions[owner_action].link.includes('GetGooValue')) { + canTurnIntoGems = true; + } } - } - if (!canTurnIntoGems) - return; + if (!canTurnIntoGems) { + return; + } - item.queued = true; - scrapQueue.push(item); - numberOfQueuedItems++; - }); + item.queued = true; + scrapQueue.push(item); + numberOfQueuedItems++; + }); - if (numberOfQueuedItems > 0) { - totalNumberOfQueuedItems += numberOfQueuedItems; + if (numberOfQueuedItems > 0) { + totalNumberOfQueuedItems += numberOfQueuedItems; - $('#inventory_items_spinner').remove(); - $('#inventory_sell_buttons').append('
' + + $('#inventory_items_spinner').remove(); + $('#inventory_sell_buttons').append('
' + spinnerBlock + '
Processing ' + numberOfQueuedItems + ' items
' + '
'); + } + }, + () => { + logDOM('Could not retrieve the inventory...'); } - }, - function () { - logDOM('Could not retrieve the inventory...'); - }); + ); } function sellAllCards() { - loadAllInventories().then(function() { - var items = getInventoryItems(); - var filteredItems = []; + loadAllInventories().then( + () => { + const items = getInventoryItems(); + const filteredItems = []; - items.forEach(function(item) { + items.forEach((item) => { if (!getIsTradingCard(item) || !item.marketable) { return; } @@ -1347,16 +1406,18 @@ sellItems(filteredItems); }, - function() { + () => { logDOM('Could not retrieve the inventory...'); - }); + } + ); } function sellAllCrates() { - loadAllInventories().then(function () { - var items = getInventoryItems(); - var filteredItems = []; - items.forEach(function (item) { + loadAllInventories().then( + () => { + const items = getInventoryItems(); + const filteredItems = []; + items.forEach((item) => { if (!getIsCrate(item) || !item.marketable) { return; } @@ -1365,26 +1426,28 @@ sellItems(filteredItems); }, - function() { + () => { logDOM('Could not retrieve the inventory...'); - }); + } + ); } - var scrapQueue = async.queue(function(item, next) { - scrapQueueWorker(item, function(success) { + const scrapQueue = async.queue((item, next) => { + scrapQueueWorker(item, (success) => { if (success) { - setTimeout(function() { + setTimeout(() => { next(); }, 250); } else { - var delay = numberOfFailedRequests > 1 ? - getRandomInt(30000, 45000) : - getRandomInt(1000, 1500); + const delay = numberOfFailedRequests > 1 + ? getRandomInt(30000, 45000) + : getRandomInt(1000, 1500); - if (numberOfFailedRequests > 3) + if (numberOfFailedRequests > 3) { numberOfFailedRequests = 0; + } - setTimeout(function() { + setTimeout(() => { next(); }, delay); } @@ -1393,19 +1456,19 @@ scrapQueue.drain = function() { onQueueDrain(); - } + }; function scrapQueueWorker(item, callback) { - var failed = 0; - var itemName = item.name || item.description.name; - var itemId = item.assetid || item.id; + const itemName = item.name || item.description.name; + const itemId = item.assetid || item.id; - market.getGooValue(item, - function(err, goo) { + market.getGooValue( + item, + (err, goo) => { totalNumberOfProcessedQueueItems++; - var digits = getNumberOfDigits(totalNumberOfQueuedItems); - var padLeft = padLeftZero('' + totalNumberOfProcessedQueueItems, digits) + ' / ' + totalNumberOfQueuedItems; + const digits = getNumberOfDigits(totalNumberOfQueuedItems); + const padLeft = padLeftZero('' + totalNumberOfProcessedQueueItems, digits) + ' / ' + totalNumberOfQueuedItems; if (err != ERROR_SUCCESS) { logConsole('Failed to get gems value for ' + itemName); @@ -1417,8 +1480,9 @@ item.goo_value_expected = parseInt(goo.goo_value, 10); - market.grindIntoGoo(item, - function(err, result) { + market.grindIntoGoo( + item, + (err) => { if (err != ERROR_SUCCESS) { logConsole('Failed to turn item into gems for ' + itemName); logDOM(padLeft + ' - ' + itemName + ' not turned into gems due to unknown error.'); @@ -1427,7 +1491,7 @@ return callback(false); } - logConsole('============================') + logConsole('============================'); logConsole(itemName); logConsole('Turned into ' + goo.goo_value + ' gems'); logDOM(padLeft + ' - ' + itemName + ' turned into ' + item.goo_value_expected + ' gems.'); @@ -1437,25 +1501,28 @@ updateTotals(); callback(true); - }); - }); + } + ); + } + ); } - var boosterQueue = async.queue(function(item, next) { - boosterQueueWorker(item, function(success) { + const boosterQueue = async.queue((item, next) => { + boosterQueueWorker(item, (success) => { if (success) { - setTimeout(function() { + setTimeout(() => { next(); }, 250); } else { - var delay = numberOfFailedRequests > 1 ? - getRandomInt(30000, 45000) : - getRandomInt(1000, 1500); + const delay = numberOfFailedRequests > 1 + ? getRandomInt(30000, 45000) + : getRandomInt(1000, 1500); - if (numberOfFailedRequests > 3) + if (numberOfFailedRequests > 3) { numberOfFailedRequests = 0; + } - setTimeout(function() { + setTimeout(() => { next(); }, delay); } @@ -1464,19 +1531,19 @@ boosterQueue.drain = function() { onQueueDrain(); - } + }; function boosterQueueWorker(item, callback) { - var failed = 0; - var itemName = item.name || item.description.name; - var itemId = item.assetid || item.id; + const itemName = item.name || item.description.name; + const itemId = item.assetid || item.id; - market.unpackBoosterPack(item, - function(err, goo) { + market.unpackBoosterPack( + item, + (err) => { totalNumberOfProcessedQueueItems++; - var digits = getNumberOfDigits(totalNumberOfQueuedItems); - var padLeft = padLeftZero('' + totalNumberOfProcessedQueueItems, digits) + ' / ' + totalNumberOfQueuedItems; + const digits = getNumberOfDigits(totalNumberOfQueuedItems); + const padLeft = padLeftZero('' + totalNumberOfProcessedQueueItems, digits) + ' / ' + totalNumberOfQueuedItems; if (err != ERROR_SUCCESS) { logConsole('Failed to unpack booster pack ' + itemName); @@ -1490,19 +1557,20 @@ $('#' + item.appid + '_' + item.contextid + '_' + itemId).css('background', COLOR_SUCCESS); callback(true); - }); + } + ); } // Turns the selected items into gems. function turnSelectedItemsIntoGems() { - var ids = getSelectedItems(); + const ids = getSelectedItems(); - loadAllInventories().then(function() { - var items = getInventoryItems(); + loadAllInventories().then(() => { + const items = getInventoryItems(); - var numberOfQueuedItems = 0; - items.forEach(function(item) { + let numberOfQueuedItems = 0; + items.forEach((item) => { // Ignored queued items. if (item.queued != null) { return; @@ -1512,17 +1580,18 @@ return; } - var canTurnIntoGems = false; - for (var owner_action in item.owner_actions) { + let canTurnIntoGems = false; + for (const owner_action in item.owner_actions) { if (item.owner_actions[owner_action].link != null && item.owner_actions[owner_action].link.includes('GetGooValue')) { canTurnIntoGems = true; } } - if (!canTurnIntoGems) + if (!canTurnIntoGems) { return; + } - var itemId = item.assetid || item.id; + const itemId = item.assetid || item.id; if (ids.indexOf(itemId) !== -1) { item.queued = true; scrapQueue.push(item); @@ -1535,24 +1604,24 @@ $('#inventory_items_spinner').remove(); $('#inventory_sell_buttons').append('
' + - spinnerBlock + - '
Processing ' + numberOfQueuedItems + ' items
' + - '
'); + spinnerBlock + + '
Processing ' + numberOfQueuedItems + ' items
' + + '
'); } - }, function() { + }, () => { logDOM('Could not retrieve the inventory...'); }); } // Unpacks the selected booster packs. function unpackSelectedBoosterPacks() { - var ids = getSelectedItems(); + const ids = getSelectedItems(); - loadAllInventories().then(function() { - var items = getInventoryItems(); + loadAllInventories().then(() => { + const items = getInventoryItems(); - var numberOfQueuedItems = 0; - items.forEach(function(item) { + let numberOfQueuedItems = 0; + items.forEach((item) => { // Ignored queued items. if (item.queued != null) { return; @@ -1562,17 +1631,18 @@ return; } - var canOpenBooster = false; - for (var owner_action in item.owner_actions) { + let canOpenBooster = false; + for (const owner_action in item.owner_actions) { if (item.owner_actions[owner_action].link != null && item.owner_actions[owner_action].link.includes('OpenBooster')) { canOpenBooster = true; } } - if (!canOpenBooster) + if (!canOpenBooster) { return; + } - var itemId = item.assetid || item.id; + const itemId = item.assetid || item.id; if (ids.indexOf(itemId) !== -1) { item.queued = true; boosterQueue.push(item); @@ -1585,17 +1655,17 @@ $('#inventory_items_spinner').remove(); $('#inventory_sell_buttons').append('
' + - spinnerBlock + - '
Processing ' + numberOfQueuedItems + ' items
' + - '
'); + spinnerBlock + + '
Processing ' + numberOfQueuedItems + ' items
' + + ''); } - }, function() { + }, () => { logDOM('Could not retrieve the inventory...'); }); } function sellSelectedItems() { - getInventorySelectedMarketableItems(function(items) { + getInventorySelectedMarketableItems((items) => { sellItems(items); }); } @@ -1603,45 +1673,44 @@ function canSellSelectedItemsManually(items) { // We have to construct an URL like this // https://steamcommunity.com/market/multisell?appid=730&contextid=2&items[]=Falchion%20Case&qty[]=100 - var appid = items[0].appid; - var contextid = items[0].contextid; - - var hasInvalidItem = false; + const contextid = items[0].contextid; + let hasInvalidItem = false; - items.forEach(function(item) { - if (item.contextid != contextid || item.commodity == false) + items.forEach((item) => { + if (item.contextid != contextid || item.commodity == false) { hasInvalidItem = true; + } }); return !hasInvalidItem; } function sellSelectedItemsManually() { - getInventorySelectedMarketableItems(function(items) { + getInventorySelectedMarketableItems((items) => { // We have to construct an URL like this // https://steamcommunity.com/market/multisell?appid=730&contextid=2&items[]=Falchion%20Case&qty[]=100 - var appid = items[0].appid; - var contextid = items[0].contextid; + const appid = items[0].appid; + const contextid = items[0].contextid; - var itemsWithQty = {}; + const itemsWithQty = {}; - items.forEach(function(item) { - itemsWithQty[item.market_hash_name] = itemsWithQty[item.market_hash_name] + 1 || 1; + items.forEach((item) => { + itemsWithQty[item.market_hash_name] = itemsWithQty[item.market_hash_name] + 1 || 1; }); - var itemsString = ''; - for (var itemName in itemsWithQty) { + let itemsString = ''; + for (const itemName in itemsWithQty) { itemsString += '&items[]=' + encodeURIComponent(itemName) + '&qty[]=' + itemsWithQty[itemName]; } - var baseUrl = window.location.origin + '/market/multisell'; - var redirectUrl = baseUrl + '?appid=' + appid + '&contextid=' + contextid + itemsString; + const baseUrl = window.location.origin + '/market/multisell'; + const redirectUrl = baseUrl + '?appid=' + appid + '&contextid=' + contextid + itemsString; - var dialog = unsafeWindow.ShowDialog('Steam Economy Enhancer', ''); - dialog.OnDismiss(function() { - items.forEach(function(item) { - var itemId = item.assetid || item.id; + const dialog = unsafeWindow.ShowDialog('Steam Economy Enhancer', ''); + dialog.OnDismiss(() => { + items.forEach((item) => { + const itemId = item.assetid || item.id; $('#' + item.appid + '_' + item.contextid + '_' + itemId).css('background', COLOR_PENDING); }); }); @@ -1655,16 +1724,15 @@ return; } - var numberOfQueuedItems = 0; + let numberOfQueuedItems = 0; - items.forEach(function(item, index, array) { + items.forEach((item) => { // Ignored queued items. if (item.queued != null) { return; } item.queued = true; - var itemId = item.assetid || item.id; item.ignoreErrors = false; itemQueue.push(item); numberOfQueuedItems++; @@ -1675,87 +1743,100 @@ $('#inventory_items_spinner').remove(); $('#inventory_sell_buttons').append('
' + - spinnerBlock + - '
Processing ' + numberOfQueuedItems + ' items
' + - '
'); + spinnerBlock + + '
Processing ' + numberOfQueuedItems + ' items
' + + ''); } } - var itemQueue = async.queue(function(item, next) { - itemQueueWorker(item, + const itemQueue = async.queue((item, next) => { + itemQueueWorker( + item, item.ignoreErrors, - function(success, cached) { + (success, cached) => { if (success) { - setTimeout(function() { + setTimeout( + () => { next(); }, - cached ? 0 : getRandomInt(1000, 1500)); + cached ? 0 : getRandomInt(1000, 1500) + ); } else { if (!item.ignoreErrors) { item.ignoreErrors = true; itemQueue.push(item); } - var delay = numberOfFailedRequests > 1 ? - getRandomInt(30000, 45000) : - getRandomInt(1000, 1500); + const delay = numberOfFailedRequests > 1 + ? getRandomInt(30000, 45000) + : getRandomInt(1000, 1500); - if (numberOfFailedRequests > 3) + if (numberOfFailedRequests > 3) { numberOfFailedRequests = 0; + } - setTimeout(function() { + setTimeout( + () => { next(); }, - cached ? 0 : delay); + cached ? 0 : delay + ); } - }); + } + ); }, 1); function itemQueueWorker(item, ignoreErrors, callback) { - var priceInfo = getPriceInformationFromItem(item); + const priceInfo = getPriceInformationFromItem(item); - var failed = 0; - var itemName = item.name || item.description.name; + let failed = 0; + const itemName = item.name || item.description.name; - market.getPriceHistory(item, + market.getPriceHistory( + item, true, - function(err, history, cachedHistory) { + (err, history, cachedHistory) => { if (err) { logConsole('Failed to get price history for ' + itemName); - if (err == ERROR_FAILED) + if (err == ERROR_FAILED) { failed += 1; + } } - market.getItemOrdersHistogram(item, + market.getItemOrdersHistogram( + item, true, - function(err, histogram, cachedListings) { + (err, histogram, cachedListings) => { if (err) { logConsole('Failed to get orders histogram for ' + itemName); - if (err == ERROR_FAILED) + if (err == ERROR_FAILED) { failed += 1; + } } if (failed > 0 && !ignoreErrors) { return callback(false, cachedHistory && cachedListings); } - logConsole('============================') + logConsole('============================'); logConsole(itemName); - var sellPrice = calculateSellPriceBeforeFees(history, + const sellPrice = calculateSellPriceBeforeFees( + history, histogram, true, priceInfo.minPriceBeforeFees, - priceInfo.maxPriceBeforeFees); + priceInfo.maxPriceBeforeFees + ); logConsole('Sell price: ' + - sellPrice / 100.0 + - ' (' + - market.getPriceIncludingFees(sellPrice) / 100.0 + - ')'); + sellPrice / 100.0 + + ' (' + + market.getPriceIncludingFees(sellPrice) / 100.0 + + ')'); sellQueue.push({ item: item, @@ -1763,39 +1844,46 @@ }); return callback(true, cachedHistory && cachedListings); - }); - }); + } + ); + } + ); } // Initialize the inventory UI. - function initializeInventoryUI() { - var isOwnInventory = unsafeWindow.g_ActiveUser.strSteamId == unsafeWindow.g_steamID; - var previousSelection = -1; // To store the index of the previous selection. + function initializeInventoryUI() { + const isOwnInventory = unsafeWindow.g_ActiveUser.strSteamId == unsafeWindow.g_steamID; + let previousSelection = -1; // To store the index of the previous selection. updateInventoryUI(isOwnInventory); - $('.games_list_tabs').on('click', + $('.games_list_tabs').on( + 'click', '*', - function() { + () => { updateInventoryUI(isOwnInventory); - }); + } + ); // Ignore selection on other user's inventories. - if (!isOwnInventory) + if (!isOwnInventory) { return; + } // Steam adds 'display:none' to items while searching. These should not be selected while using shift/ctrl. - var filter = ".itemHolder:not([style*=none])"; + const filter = '.itemHolder:not([style*=none])'; $('#inventories').selectable({ filter: filter, selecting: function(e, ui) { // Get selected item index. - var selectedIndex = $(ui.selecting.tagName, e.target).index(ui.selecting); + const selectedIndex = $(ui.selecting.tagName, e.target).index(ui.selecting); // If shift key was pressed and there is previous - select them all. if (e.shiftKey && previousSelection > -1) { - $(ui.selecting.tagName, e.target) - .slice(Math.min(previousSelection, selectedIndex), - 1 + Math.max(previousSelection, selectedIndex)).each(function() { + $(ui.selecting.tagName, e.target). + slice( + Math.min(previousSelection, selectedIndex), + 1 + Math.max(previousSelection, selectedIndex) + ).each(function() { if ($(this).is(filter)) { $(this).addClass('ui-selected'); } @@ -1805,33 +1893,33 @@ previousSelection = selectedIndex; // Save previous. } }, - selected: function(e, ui) { + selected: function() { updateButtons(); } }); if (typeof unsafeWindow.CInventory !== 'undefined') { - var originalSelectItem = unsafeWindow.CInventory.prototype.SelectItem; + const originalSelectItem = unsafeWindow.CInventory.prototype.SelectItem; - unsafeWindow.CInventory.prototype.SelectItem = function(event, elItem, rgItem, bUserAction) { + unsafeWindow.CInventory.prototype.SelectItem = function(event, elItem, rgItem) { originalSelectItem.apply(this, arguments); updateButtons(); updateInventorySelection(rgItem); - } + }; } } // Gets the selected items in the inventory. function getSelectedItems() { - var ids = []; + const ids = []; $('.inventory_ctn').each(function() { $(this).find('.inventory_page').each(function() { - var inventory_page = this; + const inventory_page = this; $(inventory_page).find('.itemHolder.ui-selected:not([style*=none])').each(function() { $(this).find('.item').each(function() { - var matches = this.id.match(/_(-?\d+)$/); + const matches = this.id.match(/_(-?\d+)$/); if (matches) { ids.push(matches[1]); } @@ -1845,95 +1933,97 @@ // Gets the selected and marketable items in the inventory. function getInventorySelectedMarketableItems(callback) { - var ids = getSelectedItems(); + const ids = getSelectedItems(); - loadAllInventories().then(function() { - var items = getInventoryItems(); - var filteredItems = []; + loadAllInventories().then(() => { + const items = getInventoryItems(); + const filteredItems = []; - items.forEach(function(item) { + items.forEach((item) => { if (!item.marketable) { return; } - var itemId = item.assetid || item.id; + const itemId = item.assetid || item.id; if (ids.indexOf(itemId) !== -1) { filteredItems.push(item); } }); callback(filteredItems); - }, function() { + }, () => { logDOM('Could not retrieve the inventory...'); }); } // Gets the selected and gemmable items in the inventory. function getInventorySelectedGemsItems(callback) { - var ids = getSelectedItems(); + const ids = getSelectedItems(); - loadAllInventories().then(function() { - var items = getInventoryItems(); - var filteredItems = []; + loadAllInventories().then(() => { + const items = getInventoryItems(); + const filteredItems = []; - items.forEach(function(item) { - var canTurnIntoGems = false; - for (var owner_action in item.owner_actions) { + items.forEach((item) => { + let canTurnIntoGems = false; + for (const owner_action in item.owner_actions) { if (item.owner_actions[owner_action].link != null && item.owner_actions[owner_action].link.includes('GetGooValue')) { canTurnIntoGems = true; } } - if (!canTurnIntoGems) + if (!canTurnIntoGems) { return; + } - var itemId = item.assetid || item.id; + const itemId = item.assetid || item.id; if (ids.indexOf(itemId) !== -1) { filteredItems.push(item); } }); callback(filteredItems); - }, function() { + }, () => { logDOM('Could not retrieve the inventory...'); }); } // Gets the selected and booster pack items in the inventory. function getInventorySelectedBoosterPackItems(callback) { - var ids = getSelectedItems(); + const ids = getSelectedItems(); - loadAllInventories().then(function() { - var items = getInventoryItems(); - var filteredItems = []; + loadAllInventories().then(() => { + const items = getInventoryItems(); + const filteredItems = []; - items.forEach(function(item) { - var canOpenBooster = false; - for (var owner_action in item.owner_actions) { + items.forEach((item) => { + let canOpenBooster = false; + for (const owner_action in item.owner_actions) { if (item.owner_actions[owner_action].link != null && item.owner_actions[owner_action].link.includes('OpenBooster')) { canOpenBooster = true; } } - if (!canOpenBooster) + if (!canOpenBooster) { return; + } - var itemId = item.assetid || item.id; + const itemId = item.assetid || item.id; if (ids.indexOf(itemId) !== -1) { filteredItems.push(item); } }); callback(filteredItems); - }, function() { + }, () => { logDOM('Could not retrieve the inventory...'); }); } // Updates the (selected) sell ... items button. function updateSellSelectedButton() { - getInventorySelectedMarketableItems(function(items) { - var selectedItems = items.length; + getInventorySelectedMarketableItems((items) => { + const selectedItems = items.length; if (items.length == 0) { $('.sell_selected').hide(); $('.sell_manual').hide(); @@ -1952,28 +2042,28 @@ // Updates the (selected) turn into ... gems button. function updateTurnIntoGemsButton() { - getInventorySelectedGemsItems(function(items) { - var selectedItems = items.length; + getInventorySelectedGemsItems((items) => { + const selectedItems = items.length; if (items.length == 0) { $('.turn_into_gems').hide(); } else { $('.turn_into_gems').show(); - $('.turn_into_gems > span') - .text('Turn ' + selectedItems + (selectedItems == 1 ? ' Item Into Gems' : ' Items Into Gems')); + $('.turn_into_gems > span'). + text('Turn ' + selectedItems + (selectedItems == 1 ? ' Item Into Gems' : ' Items Into Gems')); } }); } // Updates the (selected) open ... booster packs button. function updateOpenBoosterPacksButton() { - getInventorySelectedBoosterPackItems(function(items) { - var selectedItems = items.length; + getInventorySelectedBoosterPackItems((items) => { + const selectedItems = items.length; if (items.length == 0) { $('.unpack_booster_packs').hide(); } else { $('.unpack_booster_packs').show(); - $('.unpack_booster_packs > span') - .text('Unpack ' + selectedItems + (selectedItems == 1 ? ' Booster Pack' : ' Booster Packs')); + $('.unpack_booster_packs > span'). + text('Unpack ' + selectedItems + (selectedItems == 1 ? ' Booster Pack' : ' Booster Packs')); } }); } @@ -1985,42 +2075,46 @@ } function updateInventorySelection(selectedItem) { - var item_info = $('#iteminfo' + unsafeWindow.iActiveSelectView); + const item_info = $('#iteminfo' + unsafeWindow.iActiveSelectView); - if (!item_info.length) + if (!item_info.length) { return; + } - if (item_info.html().indexOf('checkout/sendgift/') > -1) // Gifts have no market information. + if (item_info.html().indexOf('checkout/sendgift/') > -1) { // Gifts have no market information. return; + } // Use a 'hard' item id instead of relying on the selected item_info (sometimes Steam temporarily changes the correct item (?)). - var item_info_id = item_info.attr('id'); + const item_info_id = item_info.attr('id'); // Move scrap to bottom, this is of little interest. - var scrap = $('#' + item_info_id + '_scrap_content'); + const scrap = $('#' + item_info_id + '_scrap_content'); scrap.next().insertBefore(scrap); // Skip unmarketable items - if (!selectedItem.marketable) - return; + if (!selectedItem.marketable) { + return; + } // Starting at prices are already retrieved in the table. //$('#' + item_info_id + '_item_market_actions > div:nth-child(1) > div:nth-child(2)') // .remove(); // Starting at: x,xx. - var market_hash_name = getMarketHashName(selectedItem); - if (market_hash_name == null) + const market_hash_name = getMarketHashName(selectedItem); + if (market_hash_name == null) { return; + } - var appid = selectedItem.appid; - var item = { + const appid = selectedItem.appid; + const item = { appid: parseInt(appid), description: { market_hash_name: market_hash_name } }; - var ownerActions = $('#' + item_info_id + '_item_owner_actions'); + const ownerActions = $('#' + item_info_id + '_item_owner_actions'); // Move market link to a button ownerActions.append('View in Community Market'); @@ -2029,9 +2123,9 @@ // ownerActions is hidden on other games' inventories, we need to show it to have a "Market" button visible ownerActions.show(); - var isBoosterPack = selectedItem.name.toLowerCase().endsWith('booster pack'); + const isBoosterPack = selectedItem.name.toLowerCase().endsWith('booster pack'); if (isBoosterPack) { - var tradingCardsUrl = "/market/search?q=&category_753_Game%5B%5D=tag_app_" + selectedItem.market_fee_app + "&category_753_item_class%5B%5D=tag_item_class_2&appid=753"; + const tradingCardsUrl = '/market/search?q=&category_753_Game%5B%5D=tag_app_' + selectedItem.market_fee_app + '&category_753_item_class%5B%5D=tag_item_class_2&appid=753'; ownerActions.append('
View trading cards in Community Market'); } @@ -2044,9 +2138,10 @@ return; } - market.getItemOrdersHistogram(item, + market.getItemOrdersHistogram( + item, false, - function(err, histogram) { + (err, histogram) => { if (err) { logConsole('Failed to get orders histogram for ' + (selectedItem.name || selectedItem.description.name)); return; @@ -2057,19 +2152,19 @@ return; } - var groupMain = $('
' + - '
Sell
' + - histogram.sell_order_table + - '
' + - '
Buy
' + - histogram.buy_order_table + - '
' + - '
'); + const groupMain = $('
' + + '
Sell
' + + histogram.sell_order_table + + '
' + + '
Buy
' + + histogram.buy_order_table + + '
' + + '
'); $('#' + item_info_id + '_item_market_actions > div').after(groupMain); // Generate quick sell buttons. - var prices = []; + let prices = []; if (histogram != null && histogram.highest_buy_order != null) { prices.push(parseInt(histogram.highest_buy_order)); @@ -2085,8 +2180,8 @@ prices = prices.filter((v, i) => prices.indexOf(v) === i).sort((a, b) => a - b); - var buttons = ' '; - prices.forEach(function(e) { + let buttons = ' '; + prices.forEach((e) => { buttons += '' + '' + - '' + ''; }); $('#' + item_info_id + '_item_market_actions', item_info).append(buttons); - $('#' + item_info_id + '_item_market_actions', item_info).append( - '
' + - '' + - ' ' + - '' + - '➜ Sell' + - '' + - '' + - '' + - '
'); + $('#' + item_info_id + '_item_market_actions', item_info).append('
' + + '' + + ' ' + + '' + + '➜ Sell' + + '' + + '' + + '' + + '
'); - $('.quick_sell').on('click', + $('.quick_sell').on( + 'click', function() { - var price = $(this).attr('id').replace('quick_sell', ''); + let price = $(this).attr('id').replace('quick_sell', ''); price = market.getPriceBeforeFees(price); totalNumberOfQueuedItems++; @@ -2124,11 +2219,13 @@ item: selectedItem, sellPrice: price }); - }); + } + ); - $('.quick_sell_custom').on('click', - function() { - var price = $('#quick_sell_input', $('#' + item_info_id + '_item_market_actions', item_info)).val() * 100; + $('.quick_sell_custom').on( + 'click', + () => { + let price = $('#quick_sell_input', $('#' + item_info_id + '_item_market_actions', item_info)).val() * 100; price = market.getPriceBeforeFees(price); totalNumberOfQueuedItems++; @@ -2137,8 +2234,10 @@ item: selectedItem, sellPrice: price }); - }); - }); + } + ); + } + ); } // Update the inventory UI. @@ -2149,31 +2248,31 @@ $('#inventory_reload_button').remove(); $('#see_settings').remove(); - $('#global_action_menu') - .prepend('⬖ Steam Economy Enhancer'); + $('#global_action_menu'). + prepend('⬖ Steam Economy Enhancer'); $('#see_settings').on('click', '*', () => openSettings()); - var appId = getActiveInventory().m_appid; - var showMiscOptions = appId == 753; - var TF2 = appId == 440; - - var sellButtons = $(''); - - var reloadButton = + const appId = getActiveInventory().m_appid; + const showMiscOptions = appId == 753; + const TF2 = appId == 440; + + const sellButtons = $(''); + + const reloadButton = $('Reload Inventory'); const logo = $('#inventory_logos')[0]; @@ -2184,24 +2283,28 @@ $('#inventory_applogo').after(logger); - $("#logger").on('scroll', - function() { - var hasUserScrolledToBottom = - $("#logger").prop('scrollHeight') - $("#logger").prop('clientHeight') <= - $("#logger").prop('scrollTop') + 1; + $('#logger').on( + 'scroll', + () => { + const hasUserScrolledToBottom = + $('#logger').prop('scrollHeight') - $('#logger').prop('clientHeight') <= + $('#logger').prop('scrollTop') + 1; userScrolled = !hasUserScrolledToBottom; - }); + } + ); // Only add buttons on the user's inventory. if (isOwnInventory) { $('#inventory_applogo').after(sellButtons); // Add bindings to sell buttons. - $('.sell_all').on('click', + $('.sell_all').on( + 'click', '*', - function() { - sellAllItems(appId); - }); + () => { + sellAllItems(); + } + ); $('.sell_selected').on('click', '*', sellSelectedItems); $('.sell_all_duplicates').on('click', '*', sellAllDuplicateItems); $('.gem_all_duplicates').on('click', '*', gemAllDuplicateItems); @@ -2214,14 +2317,17 @@ } $('.inventory_rightnav').prepend(reloadButton); - $('.reload_inventory').on('click', + $('.reload_inventory').on( + 'click', '*', - function() { + () => { window.location.reload(); - }); + } + ); - loadAllInventories().then(function() { - var updateInventoryPrices = function() { + loadAllInventories().then( + () => { + const updateInventoryPrices = function() { if (getSettingWithDefault(SETTING_INVENTORY_PRICE_LABELS) == 1) { setInventoryPrices(getInventoryItems()); } @@ -2230,26 +2336,31 @@ // Load after the inventory is loaded. updateInventoryPrices(); - $('#inventory_pagecontrols').observe('childlist', + $('#inventory_pagecontrols').observe( + 'childlist', '*', - function(record) { + () => { updateInventoryPrices(); - }); + } + ); }, - function() { + () => { logDOM('Could not retrieve the inventory...'); - }); + } + ); } // Loads the specified inventories. function loadInventories(inventories) { - return new Promise(function(resolve) { - inventories.reduce(function(promise, inventory) { - return promise.then(function() { - return inventory.LoadCompleteInventory().done(function() {}); + return new Promise((resolve) => { + inventories.reduce( + (promise, inventory) => { + return promise.then(() => { + return inventory.LoadCompleteInventory().done(() => {}); }); }, - Promise.resolve()); + Promise.resolve() + ); resolve(); }); @@ -2257,9 +2368,9 @@ // Loads all inventories. function loadAllInventories() { - var items = []; + const items = []; - for (var child in getActiveInventory().m_rgChildInventories) { + for (const child in getActiveInventory().m_rgChildInventories) { items.push(getActiveInventory().m_rgChildInventories[child]); } items.push(getActiveInventory()); @@ -2269,9 +2380,9 @@ // Gets the inventory items from the active inventory. function getInventoryItems() { - var arr = []; + const arr = []; - for (var child in getActiveInventory().m_rgChildInventories) { + for (const child in getActiveInventory().m_rgChildInventories) { for (const key in getActiveInventory().m_rgChildInventories[child].m_rgAssets) { const value = getActiveInventory().m_rgChildInventories[child].m_rgAssets[key]; if (typeof value === 'object') { @@ -2305,20 +2416,20 @@ if (currentPage == PAGE_INVENTORY || currentPage == PAGE_TRADEOFFER) { // Gets the active inventory. - function getActiveInventory() { + function getActiveInventory() { return unsafeWindow.g_ActiveInventory; } // Sets the prices for the items. - function setInventoryPrices(items) { + function setInventoryPrices(items) { inventoryPriceQueue.kill(); - items.forEach(function(item) { + items.forEach((item) => { if (!item.marketable) { return; } - if (!$(item.element).is(":visible")) { + if (!$(item.element).is(':visible')) { return; } @@ -2326,15 +2437,19 @@ }); } - var inventoryPriceQueue = async.queue(function(item, next) { - inventoryPriceQueueWorker(item, + const inventoryPriceQueue = async.queue( + (item, next) => { + inventoryPriceQueueWorker( + item, false, - function(success, cached) { + (success, cached) => { if (success) { - setTimeout(function() { + setTimeout( + () => { next(); }, - cached ? 0 : getRandomInt(1000, 1500)); + cached ? 0 : getRandomInt(1000, 1500) + ); } else { if (!item.ignoreErrors) { item.ignoreErrors = true; @@ -2343,68 +2458,72 @@ numberOfFailedRequests++; - var delay = numberOfFailedRequests > 1 ? - getRandomInt(30000, 45000) : - getRandomInt(1000, 1500); + const delay = numberOfFailedRequests > 1 + ? getRandomInt(30000, 45000) + : getRandomInt(1000, 1500); - if (numberOfFailedRequests > 3) + if (numberOfFailedRequests > 3) { numberOfFailedRequests = 0; + } - setTimeout(function() { + setTimeout(() => { next(); }, cached ? 0 : delay); } - }); + } + ); }, - 1); + 1 + ); function inventoryPriceQueueWorker(item, ignoreErrors, callback) { - var priceInfo = getPriceInformationFromItem(item); - - var failed = 0; - var itemName = item.name || item.description.name; + let failed = 0; + const itemName = item.name || item.description.name; // Only get the market orders here, the history is not important to visualize the current prices. - market.getItemOrdersHistogram(item, + market.getItemOrdersHistogram( + item, true, - function(err, histogram, cachedListings) { + (err, histogram, cachedListings) => { if (err) { logConsole('Failed to get orders histogram for ' + itemName); - if (err == ERROR_FAILED) + if (err == ERROR_FAILED) { failed += 1; + } } if (failed > 0 && !ignoreErrors) { return callback(false, cachedListings); } - var sellPrice = calculateSellPriceBeforeFees(null, histogram, false, 0, 65535); + const sellPrice = calculateSellPriceBeforeFees(null, histogram, false, 0, 65535); - var itemPrice = sellPrice == 65535 ? - '∞' : - formatPrice(market.getPriceIncludingFees(sellPrice)); + const itemPrice = sellPrice == 65535 + ? '∞' + : formatPrice(market.getPriceIncludingFees(sellPrice)); - var elementName = (currentPage == PAGE_TRADEOFFER ? '#item' : '#') + - item.appid + - '_' + - item.contextid + - '_' + - item.id; - var element = $(elementName); + const elementName = (currentPage == PAGE_TRADEOFFER ? '#item' : '#') + + item.appid + + '_' + + item.contextid + + '_' + + item.id; + const element = $(elementName); $('.inventory_item_price', element).remove(); element.append('' + itemPrice + ''); return callback(true, cachedListings); - }); + } + ); } } //#endregion //#region Market if (currentPage == PAGE_MARKET || currentPage == PAGE_MARKET_LISTING) { - var marketListingsRelistedAssets = []; + const marketListingsRelistedAssets = []; let marketProgressBar; function increaseMarketProgressMax() { @@ -2428,37 +2547,46 @@ } } - var marketListingsQueue = async.queue(function(listing, next) { - marketListingsQueueWorker(listing, + const marketListingsQueue = async.queue((listing, next) => { + marketListingsQueueWorker( + listing, false, - function(success, cached) { + (success, cached) => { if (success) { - setTimeout(function() { - increaseMarketProgress(); - next(); - }, - cached ? 0 : getRandomInt(1000, 1500)); + setTimeout( + () => { + increaseMarketProgress(); + next(); + }, + cached ? 0 : getRandomInt(1000, 1500) + ); } else { - setTimeout(function() { - marketListingsQueueWorker(listing, - true, - function(success, cached) { - increaseMarketProgress(); - next(); // Go to the next queue item, regardless of success. - }); - }, - cached ? 0 : getRandomInt(30000, 45000)); + setTimeout( + () => { + marketListingsQueueWorker( + listing, + true, + () => { + increaseMarketProgress(); + next(); // Go to the next queue item, regardless of success. + } + ); + }, + cached ? 0 : getRandomInt(30000, 45000) + ); } - }); + } + ); }, 1); // Gets the price, in cents, from a market listing. function getPriceFromMarketListing(listing) { - var priceLabel = listing.trim().replace('--', '00'); + let priceLabel = listing.trim().replace('--', '00'); // Fixes RUB, which has a dot at the end. - if (priceLabel[priceLabel.length - 1] === '.' || priceLabel[priceLabel.length - 1] === ",") + if (priceLabel[priceLabel.length - 1] === '.' || priceLabel[priceLabel.length - 1] === ',') { priceLabel = priceLabel.slice(0, -1); + } // For round numbers (e.g., 100 EUR). if (priceLabel.indexOf('.') === -1 && priceLabel.indexOf(',') === -1) { @@ -2469,7 +2597,7 @@ } function marketListingsQueueWorker(listing, ignoreErrors, callback) { - var asset = unsafeWindow.g_rgAssets[listing.appid][listing.contextid][listing.assetid]; + const asset = unsafeWindow.g_rgAssets[listing.appid][listing.contextid][listing.assetid]; // An asset: //{ @@ -2511,13 +2639,13 @@ // "owner" : 0 //} - var market_hash_name = getMarketHashName(asset); - var appid = listing.appid; + const market_hash_name = getMarketHashName(asset); + const appid = listing.appid; - var listingUI = $(getListingFromLists(listing.listingid).elm); + const listingUI = $(getListingFromLists(listing.listingid).elm); - var game_name = asset.type; - var price = getPriceFromMarketListing($('.market_listing_price > span:nth-child(1) > span:nth-child(1)', listingUI).text()); + const game_name = asset.type; + const price = getPriceFromMarketListing($('.market_listing_price > span:nth-child(1) > span:nth-child(1)', listingUI).text()); if (price <= getSettingWithDefault(SETTING_PRICE_MIN_CHECK_PRICE) * 100) { $('.market_listing_my_price', listingUI).last().css('background', COLOR_PRICE_NOT_CHECKED); @@ -2527,34 +2655,38 @@ return callback(true, true); } - var priceInfo = getPriceInformationFromItem(asset); - var item = { + const priceInfo = getPriceInformationFromItem(asset); + const item = { appid: parseInt(appid), description: { market_hash_name: market_hash_name } }; - var failed = 0; + let failed = 0; - market.getPriceHistory(item, + market.getPriceHistory( + item, true, - function(errorPriceHistory, history, cachedHistory) { + (errorPriceHistory, history, cachedHistory) => { if (errorPriceHistory) { logConsole('Failed to get price history for ' + game_name); - if (errorPriceHistory == ERROR_FAILED) + if (errorPriceHistory == ERROR_FAILED) { failed += 1; + } } - market.getItemOrdersHistogram(item, + market.getItemOrdersHistogram( + item, true, - function(errorHistogram, histogram, cachedListings) { + (errorHistogram, histogram, cachedListings) => { if (errorHistogram) { logConsole('Failed to get orders histogram for ' + game_name); - if (errorHistogram == ERROR_FAILED) + if (errorHistogram == ERROR_FAILED) { failed += 1; + } } if (failed > 0 && !ignoreErrors) { @@ -2563,15 +2695,17 @@ // Shows the highest buy order price on the market listings. // The 'histogram.highest_buy_order' is not reliable as Steam is caching this value, but it gives some idea for older titles/listings. - var highestBuyOrderPrice = (histogram == null || histogram.highest_buy_order == null ? - '-' : - formatPrice(histogram.highest_buy_order)); - $('.market_table_value > span:nth-child(1) > span:nth-child(1) > span:nth-child(1)', - listingUI).append(' ➤ ' + - highestBuyOrderPrice + - ''); - - logConsole('============================') + const highestBuyOrderPrice = histogram == null || histogram.highest_buy_order == null + ? '-' + : formatPrice(histogram.highest_buy_order); + $( + '.market_table_value > span:nth-child(1) > span:nth-child(1) > span:nth-child(1)', + listingUI + ).append(' ➤ ' + + highestBuyOrderPrice + + ''); + + logConsole('============================'); logConsole(JSON.stringify(listing)); logConsole(game_name + ': ' + asset.name); logConsole('Current price: ' + price / 100.0); @@ -2580,35 +2714,41 @@ // The price without the offset is required to not relist the item constantly when you have the lowest price (i.e., with a negative offset). // The price with the offset should be used for relisting so it will still apply the user-set offset. - var sellPriceWithoutOffset = calculateSellPriceBeforeFees(history, + const sellPriceWithoutOffset = calculateSellPriceBeforeFees( + history, histogram, false, priceInfo.minPriceBeforeFees, - priceInfo.maxPriceBeforeFees); - var sellPriceWithOffset = calculateSellPriceBeforeFees(history, + priceInfo.maxPriceBeforeFees + ); + const sellPriceWithOffset = calculateSellPriceBeforeFees( + history, histogram, true, priceInfo.minPriceBeforeFees, - priceInfo.maxPriceBeforeFees); + priceInfo.maxPriceBeforeFees + ); - var sellPriceWithoutOffsetWithFees = market.getPriceIncludingFees(sellPriceWithoutOffset); + const sellPriceWithoutOffsetWithFees = market.getPriceIncludingFees(sellPriceWithoutOffset); logConsole('Calculated price: ' + - sellPriceWithoutOffsetWithFees / 100.0 + - ' (' + - sellPriceWithoutOffset / 100.0 + - ')'); + sellPriceWithoutOffsetWithFees / 100.0 + + ' (' + + sellPriceWithoutOffset / 100.0 + + ')'); listingUI.addClass('price_' + sellPriceWithOffset); - $('.market_listing_my_price', listingUI).last().prop('title', - 'The best price is ' + formatPrice(sellPriceWithoutOffsetWithFees) + '.'); + $('.market_listing_my_price', listingUI).last().prop( + 'title', + 'The best price is ' + formatPrice(sellPriceWithoutOffsetWithFees) + '.' + ); if (sellPriceWithoutOffsetWithFees < price) { logConsole('Sell price is too high.'); - $('.market_listing_my_price', listingUI).last() - .css('background', COLOR_PRICE_EXPENSIVE); + $('.market_listing_my_price', listingUI).last(). + css('background', COLOR_PRICE_EXPENSIVE); listingUI.addClass('overpriced'); if (getSettingWithDefault(SETTING_RELIST_AUTOMATICALLY) == 1) { @@ -2627,55 +2767,68 @@ } return callback(true, cachedHistory && cachedListings); - }); - }); + } + ); + } + ); } - var marketOverpricedQueue = async.queue(function(item, next) { - marketOverpricedQueueWorker(item, + const marketOverpricedQueue = async.queue( + (item, next) => { + marketOverpricedQueueWorker( + item, false, - function(success) { + (success) => { if (success) { - setTimeout(function() { - increaseMarketProgress(); - next(); - }, - getRandomInt(1000, 1500)); + setTimeout( + () => { + increaseMarketProgress(); + next(); + }, + getRandomInt(1000, 1500) + ); } else { - setTimeout(function() { - marketOverpricedQueueWorker(item, - true, - function(success) { - increaseMarketProgress(); - next(); // Go to the next queue item, regardless of success. - }); - }, - getRandomInt(30000, 45000)); + setTimeout( + () => { + marketOverpricedQueueWorker( + item, + true, + () => { + increaseMarketProgress(); + next(); // Go to the next queue item, regardless of success. + } + ); + }, + getRandomInt(30000, 45000) + ); } - }); + } + ); }, - 1); + 1 + ); function marketOverpricedQueueWorker(item, ignoreErrors, callback) { - var listingUI = getListingFromLists(item.listing).elm; + const listingUI = getListingFromLists(item.listing).elm; - market.removeListing(item.listing, false, - function(errorRemove, data) { + market.removeListing( + item.listing, false, + (errorRemove) => { if (!errorRemove) { $('.actual_content', listingUI).css('background', COLOR_PENDING); - setTimeout(function() { - var itemName = $('.market_listing_item_name_link', listingUI).first().attr('href'); - var marketHashNameIndex = itemName.lastIndexOf('/') + 1; - var marketHashName = itemName.substring(marketHashNameIndex); - var decodedMarketHashName = decodeURIComponent(itemName.substring(marketHashNameIndex)); - var newAssetId = -1; + setTimeout(() => { + const itemName = $('.market_listing_item_name_link', listingUI).first().attr('href'); + const marketHashNameIndex = itemName.lastIndexOf('/') + 1; + const marketHashName = itemName.substring(marketHashNameIndex); + const decodedMarketHashName = decodeURIComponent(itemName.substring(marketHashNameIndex)); + let newAssetId = -1; - unsafeWindow.RequestFullInventory(market.inventoryUrl + item.appid + "/" + item.contextid + "/", {}, null, null, function(transport) { + unsafeWindow.RequestFullInventory(market.inventoryUrl + item.appid + '/' + item.contextid + '/', {}, null, null, (transport) => { if (transport.responseJSON && transport.responseJSON.success) { - var inventory = transport.responseJSON.rgInventory; + const inventory = transport.responseJSON.rgInventory; - for (var child in inventory) { + for (const child in inventory) { if (marketListingsRelistedAssets.indexOf(child) == -1 && inventory[child].appid == item.appid && (inventory[child].market_hash_name == decodedMarketHashName || inventory[child].market_hash_name == marketHashName)) { newAssetId = child; break; @@ -2690,14 +2843,15 @@ item.assetid = newAssetId; marketListingsRelistedAssets.push(newAssetId); - market.sellItem(item, + market.sellItem( + item, item.sellPrice, - function(errorSell) { + (errorSell) => { if (!errorSell) { $('.actual_content', listingUI).css('background', COLOR_SUCCESS); - setTimeout(function() { - removeListingFromLists(item.listing) + setTimeout(() => { + removeListingFromLists(item.listing); }, 3000); return callback(true); @@ -2705,7 +2859,8 @@ $('.actual_content', listingUI).css('background', COLOR_ERROR); return callback(false); } - }); + } + ); } else { $('.actual_content', listingUI).css('background', COLOR_ERROR); @@ -2717,19 +2872,21 @@ $('.actual_content', listingUI).css('background', COLOR_ERROR); return callback(false); } - }); + } + ); } // Queue an overpriced item listing to be relisted. function queueOverpricedItemListing(listingid) { - var assetInfo = getAssetInfoFromListingId(listingid); - var listingUI = $(getListingFromLists(listingid).elm); - var price = -1; + const assetInfo = getAssetInfoFromListingId(listingid); + const listingUI = $(getListingFromLists(listingid).elm); + let price = -1; - var items = $(listingUI).attr('class').split(' '); - for (var i in items) { - if (items[i].toString().includes('price_')) + const items = $(listingUI).attr('class').split(' '); + for (const i in items) { + if (items[i].toString().includes('price_')) { price = parseInt(items[i].toString().replace('price_', '')); + } } if (price > 0) { @@ -2744,52 +2901,65 @@ } } - var marketRemoveQueue = async.queue(function(listingid, next) { - marketRemoveQueueWorker(listingid, + const marketRemoveQueue = async.queue( + (listingid, next) => { + marketRemoveQueueWorker( + listingid, false, - function(success) { + (success) => { if (success) { - setTimeout(function() { - increaseMarketProgress(); - next(); - }, - getRandomInt(50, 100)); + setTimeout( + () => { + increaseMarketProgress(); + next(); + }, + getRandomInt(50, 100) + ); } else { - setTimeout(function() { - marketRemoveQueueWorker(listingid, - true, - function(success) { - increaseMarketProgress(); - next(); // Go to the next queue item, regardless of success. - }); - }, - getRandomInt(30000, 45000)); + setTimeout( + () => { + marketRemoveQueueWorker( + listingid, + true, + () => { + increaseMarketProgress(); + next(); // Go to the next queue item, regardless of success. + } + ); + }, + getRandomInt(30000, 45000) + ); } - }); + } + ); }, - 10); + 10 + ); function marketRemoveQueueWorker(listingid, ignoreErrors, callback) { - var listingUI = getListingFromLists(listingid).elm; - var isBuyOrder = listingUI.id.startsWith('mybuyorder_'); + const listingUI = getListingFromLists(listingid).elm; + const isBuyOrder = listingUI.id.startsWith('mybuyorder_'); - market.removeListing(listingid, isBuyOrder, - function(errorRemove, data) { + market.removeListing( + listingid, isBuyOrder, + (errorRemove) => { if (!errorRemove) { $('.actual_content', listingUI).css('background', COLOR_SUCCESS); - setTimeout(function() { + setTimeout( + () => { removeListingFromLists(listingid); - var numberOfListings = marketLists[0].size; + const numberOfListings = marketLists[0].size; if (numberOfListings > 0) { - $('#my_market_selllistings_number').text((numberOfListings).toString()); + $('#my_market_selllistings_number').text(numberOfListings.toString()); // This seems identical to the number of sell listings. - $('#my_market_activelistings_number').text((numberOfListings).toString()); + $('#my_market_activelistings_number').text(numberOfListings.toString()); } }, - 3000); + 3000 + ); return callback(true); } else { @@ -2797,61 +2967,69 @@ return callback(false); } - }); + } + ); } - var marketListingsItemsQueue = async.queue(function(listing, next) { - $.get(window.location.origin + '/market/mylistings?count=100&start=' + listing, - function(data) { - if (!data || !data.success) { - increaseMarketProgress(); - next(); - return; - } + const marketListingsItemsQueue = async.queue( + (listing, next) => { + $.get( + window.location.origin + '/market/mylistings?count=100&start=' + listing, + (data) => { + if (!data || !data.success) { + increaseMarketProgress(); + next(); + return; + } - var myMarketListings = $('#tabContentsMyActiveMarketListingsRows'); + const myMarketListings = $('#tabContentsMyActiveMarketListingsRows'); - var nodes = $.parseHTML(data.results_html); - var rows = $('.market_listing_row', nodes); - myMarketListings.append(rows); + const nodes = $.parseHTML(data.results_html); + const rows = $('.market_listing_row', nodes); + myMarketListings.append(rows); - // g_rgAssets - unsafeWindow.MergeWithAssetArray(data.assets); // This is a method from Steam. + // g_rgAssets + unsafeWindow.MergeWithAssetArray(data.assets); // This is a method from Steam. - increaseMarketProgress(); - next(); - }, - 'json') - .fail(function(data) { + increaseMarketProgress(); + next(); + }, + 'json' + ). + fail(() => { increaseMarketProgress(); next(); return; }); }, - 1); + 1 + ); marketListingsItemsQueue.drain = function() { - var myMarketListings = $('#tabContentsMyActiveMarketListingsRows'); + const myMarketListings = $('#tabContentsMyActiveMarketListingsRows'); myMarketListings.checkboxes('range', true); // Sometimes the Steam API is returning duplicate entries (especially during item listing), filter these. - var seen = {}; + const seen = {}; $('.market_listing_row', myMarketListings).each(function() { - var item_id = $(this).attr('id'); - if (seen[item_id]) + const item_id = $(this).attr('id'); + if (seen[item_id]) { $(this).remove(); - else + } else { seen[item_id] = true; + } // Remove listings awaiting confirmations, they are already listed separately. - if ($('.item_market_action_button', this).attr('href').toLowerCase() - .includes('CancelMarketListingConfirmation'.toLowerCase())) + if ($('.item_market_action_button', this).attr('href').toLowerCase(). + includes('CancelMarketListingConfirmation'.toLowerCase())) { $(this).remove(); + } // Remove buy order listings, they are already listed separately. - if ($('.item_market_action_button', this).attr('href').toLowerCase() - .includes('CancelMarketBuyOrder'.toLowerCase())) + if ($('.item_market_action_button', this).attr('href').toLowerCase(). + includes('CancelMarketBuyOrder'.toLowerCase())) { $(this).remove(); + } }); // Now add the market checkboxes. @@ -2869,35 +3047,38 @@ $('.market_home_listing_table').each(function(e) { // Not for popular / new / recently sold items (bottom of page). - if ($('.my_market_header', $(this)).length == 0) + if ($('.my_market_header', $(this)).length == 0) { return; + } // Buy orders and listings confirmations are not grouped like the sell listings, add this so pagination works there as well. if (!$(this).attr('id')) { $(this).attr('id', 'market-listing-' + e); - $(this).append('
') + $(this).append('
'); $('.market_listing_row', $(this)).appendTo($('#market-listing-container-' + e)); } else { - $(this).children().last().addClass("market_listing_see"); + $(this).children().last().addClass('market_listing_see'); } addMarketPagination($('.market_listing_see', this).last()); sortMarketListings($(this), false, false, true); }); - var totalPriceBuyer = 0; - var totalPriceSeller = 0; + let totalPriceBuyer = 0; + let totalPriceSeller = 0; // Add the listings to the queue to be checked for the price. - for (var i = 0; i < marketLists.length; i++) { - for (var j = 0; j < marketLists[i].items.length; j++) { - var listingid = replaceNonNumbers(marketLists[i].items[j].values().market_listing_item_name); - var assetInfo = getAssetInfoFromListingId(listingid); + for (let i = 0; i < marketLists.length; i++) { + for (let j = 0; j < marketLists[i].items.length; j++) { + const listingid = replaceNonNumbers(marketLists[i].items[j].values().market_listing_item_name); + const assetInfo = getAssetInfoFromListingId(listingid); - if (!isNaN(assetInfo.priceBuyer)) + if (!isNaN(assetInfo.priceBuyer)) { totalPriceBuyer += assetInfo.priceBuyer; - if (!isNaN(assetInfo.priceSeller)) + } + if (!isNaN(assetInfo.priceSeller)) { totalPriceSeller += assetInfo.priceSeller; + } marketListingsQueue.push({ listingid, @@ -2915,22 +3096,23 @@ // Gets the asset info (appid/contextid/assetid) based on a listingid. function getAssetInfoFromListingId(listingid) { - var listing = getListingFromLists(listingid); + const listing = getListingFromLists(listingid); if (listing == null) { return {}; } - var actionButton = $('.item_market_action_button', listing.elm).attr('href'); + const actionButton = $('.item_market_action_button', listing.elm).attr('href'); // Market buy orders have no asset info. - if (actionButton == null || actionButton.toLowerCase().includes('cancelmarketbuyorder')) + if (actionButton == null || actionButton.toLowerCase().includes('cancelmarketbuyorder')) { return {}; + } - var priceBuyer = getPriceFromMarketListing($('.market_listing_price > span:nth-child(1) > span:nth-child(1)', listing.elm).text()); - var priceSeller = getPriceFromMarketListing($('.market_listing_price > span:nth-child(1) > span:nth-child(3)', listing.elm).text()); - var itemIds = actionButton.split(','); - var appid = replaceNonNumbers(itemIds[2]); - var contextid = replaceNonNumbers(itemIds[3]); - var assetid = replaceNonNumbers(itemIds[4]); + const priceBuyer = getPriceFromMarketListing($('.market_listing_price > span:nth-child(1) > span:nth-child(1)', listing.elm).text()); + const priceSeller = getPriceFromMarketListing($('.market_listing_price > span:nth-child(1) > span:nth-child(3)', listing.elm).text()); + const itemIds = actionButton.split(','); + const appid = replaceNonNumbers(itemIds[2]); + const contextid = replaceNonNumbers(itemIds[3]); + const assetid = replaceNonNumbers(itemIds[4]); return { appid, contextid, @@ -2947,8 +3129,8 @@ market_listing_see.before(''); market_listing_see.after(''); - $('.market_listing_table_header', market_listing_see.parent()) - .append(''); + $('.market_listing_table_header', market_listing_see.parent()). + append(''); let pageSize = parseInt(getSettingWithDefault(SETTING_MARKET_PAGE_COUNT), 10); @@ -2956,34 +3138,40 @@ pageSize = settingDefaults[SETTING_MARKET_PAGE_COUNT]; } - var options = { + const options = { valueNames: [ - 'market_listing_game_name', 'market_listing_item_name_link', 'market_listing_price', - 'market_listing_listed_date', { + 'market_listing_game_name', + 'market_listing_item_name_link', + 'market_listing_price', + 'market_listing_listed_date', + { name: 'market_listing_item_name', attr: 'id' } ], - pagination: [{ - name: "paginationTop", - paginationClass: "paginationTop", - innerWindow: 100, - outerWindow: 100, - left: 100, - right: 100 - }, { - name: "paginationBottom", - paginationClass: "paginationBottom", - innerWindow: 100, - outerWindow: 100, - left: 100, - right: 100 - }], - page: pageSize, + pagination: [ + { + name: 'paginationTop', + paginationClass: 'paginationTop', + innerWindow: 100, + outerWindow: 100, + left: 100, + right: 100 + }, + { + name: 'paginationBottom', + paginationClass: 'paginationBottom', + innerWindow: 100, + outerWindow: 100, + left: 100, + right: 100 + } + ], + page: pageSize }; try { - var list = new List(market_listing_see.parent().get(0), options); + const list = new List(market_listing_see.parent().get(0), options); list.on('searchComplete', updateMarketSelectAllButton); marketLists.push(list); } catch (e) { @@ -2997,10 +3185,10 @@ // Don't add it again, one time is enough. if ($('.market_listing_select', this).length == 0) { $('.market_listing_cancel_button', $(this)).append('
' + - '' + - '
'); + '' + + ''); - $('.market_select_item', this).change(function(e) { + $('.market_select_item', this).change(() => { updateMarketSelectAllButton(); }); } @@ -3013,12 +3201,12 @@ if (currentPage == PAGE_MARKET) { // Load the market listings. - var currentCount = 0; - var totalCount = 0; + let currentCount = 0; + let totalCount = 0; - if (typeof unsafeWindow.g_oMyListings !== 'undefined' && unsafeWindow.g_oMyListings != null && unsafeWindow.g_oMyListings.m_cTotalCount != null) + if (typeof unsafeWindow.g_oMyListings !== 'undefined' && unsafeWindow.g_oMyListings != null && unsafeWindow.g_oMyListings.m_cTotalCount != null) { totalCount = unsafeWindow.g_oMyListings.m_cTotalCount; - else { + } else { totalCount = parseInt($('#my_market_selllistings_number').text()); } @@ -3036,9 +3224,9 @@ // Show the spinner so the user knows that something is going on. $('.my_market_header').eq(0).append('
' + - spinnerBlock + - '
Loading market listings
' + - '
'); + spinnerBlock + + '
Loading market listings
' + + ''); while (currentCount < totalCount) { marketListingsItemsQueue.push(currentCount); @@ -3047,26 +3235,27 @@ } } else { // This is on a market item page. - $('.market_home_listing_table').each(function(e) { + $('.market_home_listing_table').each(function() { // Not on 'x requests to buy at y,yy or lower'. - if ($('#market_buyorder_info_show_details', $(this)).length > 0) + if ($('#market_buyorder_info_show_details', $(this)).length > 0) { return; + } - $(this).children().last().addClass("market_listing_see"); + $(this).children().last().addClass('market_listing_see'); addMarketPagination($('.market_listing_see', this).last()); sortMarketListings($(this), false, false, true); }); $('#tabContentsMyActiveMarketListingsRows > .market_listing_row').each(function() { - var listingid = $(this).attr('id').replace('mylisting_', '').replace('mybuyorder_', '').replace('mbuyorder_', ''); - var assetInfo = getAssetInfoFromListingId(listingid); + const listingid = $(this).attr('id').replace('mylisting_', '').replace('mybuyorder_', '').replace('mbuyorder_', ''); + const assetInfo = getAssetInfoFromListingId(listingid); // There's only one item in the g_rgAssets on a market listing page. - var existingAsset = null; - for (var appid in unsafeWindow.g_rgAssets) { - for (var contextid in unsafeWindow.g_rgAssets[appid]) { - for (var assetid in unsafeWindow.g_rgAssets[appid][contextid]) { + let existingAsset = null; + for (const appid in unsafeWindow.g_rgAssets) { + for (const contextid in unsafeWindow.g_rgAssets[appid]) { + for (const assetid in unsafeWindow.g_rgAssets[appid][contextid]) { existingAsset = unsafeWindow.g_rgAssets[appid][contextid][assetid]; break; } @@ -3082,48 +3271,50 @@ assetid: assetInfo.assetid }); increaseMarketProgressMax(); - }) + }); } } // Update the select/deselect all button on the market. function updateMarketSelectAllButton() { $('.market_listing_buttons').each(function() { - var selectionGroup = $(this).parent().parent(); - var invert = $('.market_select_item:checked', selectionGroup).length == $('.market_select_item', selectionGroup).length; - if ($('.market_select_item', selectionGroup).length == 0) // If there are no items to select, keep it at Select all. + const selectionGroup = $(this).parent().parent(); + let invert = $('.market_select_item:checked', selectionGroup).length == $('.market_select_item', selectionGroup).length; + if ($('.market_select_item', selectionGroup).length == 0) { // If there are no items to select, keep it at Select all. invert = false; + } $('.select_all > span', selectionGroup).text(invert ? 'Deselect all' : 'Select all'); }); } // Sort the market listings. function sortMarketListings(elem, isPrice, isDate, isName) { - var list = getListFromContainer(elem); + const list = getListFromContainer(elem); if (list == null) { console.log('Invalid parameter, could not find a list matching elem.'); return; } // Change sort order (asc/desc). - var nextSort = isPrice ? 1 : (isDate ? 2 : 3); - var asc = true; + let asc = true; // (Re)set the asc/desc arrows. const arrow_down = '🡻'; const arrow_up = '🡹'; $('.market_listing_table_header > span', elem).each(function() { - if ($(this).hasClass('market_listing_edit_buttons')) + if ($(this).hasClass('market_listing_edit_buttons')) { return; + } - if ($(this).text().includes(arrow_up)) + if ($(this).text().includes(arrow_up)) { asc = false; + } $(this).text($(this).text().replace(' ' + arrow_down, '').replace(' ' + arrow_up, '')); - }) + }); - var market_listing_selector; + let market_listing_selector; if (isPrice) { market_listing_selector = $('.market_listing_table_header', elem).children().eq(1); } else if (isDate) { @@ -3133,85 +3324,91 @@ } market_listing_selector.text(market_listing_selector.text() + ' ' + (asc ? arrow_up : arrow_down)); - if (list.sort == null) + if (list.sort == null) { return; + } if (isName) { list.sort('', { - order: asc ? "asc" : "desc", + order: asc ? 'asc' : 'desc', sortFunction: function(a, b) { - if (a.values().market_listing_game_name.toLowerCase() - .localeCompare(b.values().market_listing_game_name.toLowerCase()) == + if (a.values().market_listing_game_name.toLowerCase(). + localeCompare(b.values().market_listing_game_name.toLowerCase()) == 0) { - return a.values().market_listing_item_name_link.toLowerCase() - .localeCompare(b.values().market_listing_item_name_link.toLowerCase()); + return a.values().market_listing_item_name_link.toLowerCase(). + localeCompare(b.values().market_listing_item_name_link.toLowerCase()); } - return a.values().market_listing_game_name.toLowerCase() - .localeCompare(b.values().market_listing_game_name.toLowerCase()); + return a.values().market_listing_game_name.toLowerCase(). + localeCompare(b.values().market_listing_game_name.toLowerCase()); } }); } else if (isDate) { - var currentMonth = DateTime.local().month; + const currentMonth = luxon.DateTime.local().month; list.sort('market_listing_listed_date', { - order: asc ? "asc" : "desc", + order: asc ? 'asc' : 'desc', sortFunction: function(a, b) { - var firstDate = DateTime.fromString((a.values().market_listing_listed_date).trim(), 'd MMM'); - var secondDate = DateTime.fromString((b.values().market_listing_listed_date).trim(), 'd MMM'); + let firstDate = luxon.DateTime.fromString(a.values().market_listing_listed_date.trim(), 'd MMM'); + let secondDate = luxon.DateTime.fromString(b.values().market_listing_listed_date.trim(), 'd MMM'); if (firstDate == null || secondDate == null) { return 0; } - if (firstDate.month > currentMonth) - firstDate = firstDate.plus({ years: -1}); - if (secondDate.month > currentMonth) - secondDate = secondDate.plus({ years: -1}); + if (firstDate.month > currentMonth) { + firstDate = firstDate.plus({years: -1}); + } + if (secondDate.month > currentMonth) { + secondDate = secondDate.plus({years: -1}); + } - if (firstDate > secondDate) + if (firstDate > secondDate) { return 1; - if (firstDate === secondDate) + } + if (firstDate === secondDate) { return 0; + } return -1; } - }) + }); } else if (isPrice) { list.sort('market_listing_price', { - order: asc ? "asc" : "desc", + order: asc ? 'asc' : 'desc', sortFunction: function(a, b) { - var listingPriceA = $(a.values().market_listing_price).text(); + let listingPriceA = $(a.values().market_listing_price).text(); listingPriceA = listingPriceA.substr(0, listingPriceA.indexOf('(')); listingPriceA = listingPriceA.replace('--', '00'); - var listingPriceB = $(b.values().market_listing_price).text(); + let listingPriceB = $(b.values().market_listing_price).text(); listingPriceB = listingPriceB.substr(0, listingPriceB.indexOf('(')); listingPriceB = listingPriceB.replace('--', '00'); - var firstPrice = parseInt(replaceNonNumbers(listingPriceA)); - var secondPrice = parseInt(replaceNonNumbers(listingPriceB)); + const firstPrice = parseInt(replaceNonNumbers(listingPriceA)); + const secondPrice = parseInt(replaceNonNumbers(listingPriceB)); return firstPrice - secondPrice; } - }) + }); } } function getListFromContainer(group) { - for (var i = 0; i < marketLists.length; i++) { - if (group.attr('id') == $(marketLists[i].listContainer).attr('id')) + for (let i = 0; i < marketLists.length; i++) { + if (group.attr('id') == $(marketLists[i].listContainer).attr('id')) { return marketLists[i]; + } } } function getListingFromLists(listingid) { // Sometimes listing ids are contained in multiple lists (?), use the last one available as this is the one we're most likely interested in. - for (var i = marketLists.length - 1; i >= 0; i--) { - var values = marketLists[i].get("market_listing_item_name", 'mylisting_' + listingid + '_name'); + for (let i = marketLists.length - 1; i >= 0; i--) { + let values = marketLists[i].get('market_listing_item_name', 'mylisting_' + listingid + '_name'); if (values != null && values.length > 0) { return values[0]; } - values = marketLists[i].get("market_listing_item_name", 'mbuyorder_' + listingid + '_name'); + values = marketLists[i].get('market_listing_item_name', 'mbuyorder_' + listingid + '_name'); if (values != null && values.length > 0) { return values[0]; } @@ -3221,85 +3418,84 @@ } function removeListingFromLists(listingid) { - for (var i = 0; i < marketLists.length; i++) { - marketLists[i].remove("market_listing_item_name", 'mylisting_' + listingid + '_name'); - marketLists[i].remove("market_listing_item_name", 'mbuyorder_' + listingid + '_name'); + for (let i = 0; i < marketLists.length; i++) { + marketLists[i].remove('market_listing_item_name', 'mylisting_' + listingid + '_name'); + marketLists[i].remove('market_listing_item_name', 'mbuyorder_' + listingid + '_name'); } } // Initialize the market UI. - function initializeMarketUI() { + function initializeMarketUI() { $('.market_header_text').append('