diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml index 1c13055..a69dc01 100644 --- a/.idea/inspectionProfiles/Project_Default.xml +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -8,5 +8,6 @@ + \ No newline at end of file diff --git a/classes/CConfirmation.js b/classes/CConfirmation.js index 8585474..80172c4 100644 --- a/classes/CConfirmation.js +++ b/classes/CConfirmation.js @@ -3,7 +3,7 @@ const SteamCommunity = require('../index.js'); module.exports = CConfirmation; function CConfirmation(community, data) { - Object.defineProperty(this, "_community", {"value": community}); + Object.defineProperty(this, '_community', {value: community}); this.id = data.id.toString(); this.type = data.type; @@ -19,7 +19,7 @@ function CConfirmation(community, data) { CConfirmation.prototype.getOfferID = function(time, key, callback) { if (this.type && this.creator) { if (this.type != SteamCommunity.ConfirmationType.Trade) { - callback(new Error("Not a trade confirmation")); + callback(new Error('Not a trade confirmation')); return; } diff --git a/classes/CEconItem.js b/classes/CEconItem.js index 4ccfc9b..49eebd5 100644 --- a/classes/CEconItem.js +++ b/classes/CEconItem.js @@ -1,14 +1,11 @@ module.exports = CEconItem; function CEconItem(item, description, contextID) { - var thing; - for (thing in item) { - if (item.hasOwnProperty(thing)) { - this[thing] = item[thing]; - } + for (let thing in item) { + this[thing] = item[thing]; } - var isCurrency = !!(this.is_currency || this.currency) || typeof this.currencyid !== 'undefined'; // I don't want to put this on the object yet; it's nice to have the ids at the top of printed output + let isCurrency = !!(this.is_currency || this.currency) || typeof this.currencyid !== 'undefined'; // I don't want to put this on the object yet; it's nice to have the ids at the top of printed output if (isCurrency) { this.currencyid = this.id = (this.id || this.currencyid); @@ -27,10 +24,8 @@ function CEconItem(item, description, contextID) { description = description[this.classid + '_' + this.instanceid]; } - for (thing in description) { - if (description.hasOwnProperty(thing)) { - this[thing] = description[thing]; - } + for (let thing in description) { + this[thing] = description[thing]; } } @@ -51,18 +46,18 @@ function CEconItem(item, description, contextID) { if (this.tags) { this.tags = this.tags.map(function(tag) { return { - "internal_name": tag.internal_name, - "name": tag.localized_tag_name || tag.name, - "category": tag.category, - "color": tag.color || "", - "category_name": tag.localized_category_name || tag.category_name + internal_name: tag.internal_name, + name: tag.localized_tag_name || tag.name, + category: tag.category, + color: tag.color || '', + category_name: tag.localized_category_name || tag.category_name }; }); } // Restore market_fee_app, if applicable - var match; - if (this.appid == 753 && this.contextid == 6 && this.market_hash_name && (match = this.market_hash_name.match(/^(\d+)\-/))) { + let match; + if (this.appid == 753 && this.contextid == 6 && this.market_hash_name && (match = this.market_hash_name.match(/^(\d+)-/))) { this.market_fee_app = parseInt(match[1], 10); } @@ -82,7 +77,7 @@ function CEconItem(item, description, contextID) { this.cache_expiration = this.item_expiration; } - if (this.actions === "") { + if (this.actions === '') { this.actions = []; } @@ -94,15 +89,15 @@ function CEconItem(item, description, contextID) { } CEconItem.prototype.getImageURL = function() { - return "https://steamcommunity-a.akamaihd.net/economy/image/" + this.icon_url + "/"; + return 'https://steamcommunity-a.akamaihd.net/economy/image/' + this.icon_url + '/'; }; CEconItem.prototype.getLargeImageURL = function() { - if(!this.icon_url_large) { + if (!this.icon_url_large) { return this.getImageURL(); } - return "https://steamcommunity-a.akamaihd.net/economy/image/" + this.icon_url_large + "/"; + return 'https://steamcommunity-a.akamaihd.net/economy/image/' + this.icon_url_large + '/'; }; CEconItem.prototype.getTag = function(category) { @@ -110,7 +105,7 @@ CEconItem.prototype.getTag = function(category) { return null; } - for (var i = 0; i < this.tags.length; i++) { + for (let i = 0; i < this.tags.length; i++) { if (this.tags[i].category == category) { return this.tags[i]; } diff --git a/classes/CMarketItem.js b/classes/CMarketItem.js index b031d34..c489cb4 100644 --- a/classes/CMarketItem.js +++ b/classes/CMarketItem.js @@ -3,32 +3,33 @@ const Cheerio = require('cheerio'); const SteamCommunity = require('../index.js'); SteamCommunity.prototype.getMarketItem = function(appid, hashName, currency, callback) { - if (typeof currency == "function") { + if (typeof currency == 'function') { callback = currency; currency = 1; } - var self = this; - this.httpRequest("https://steamcommunity.com/market/listings/" + appid + "/" + encodeURIComponent(hashName), function(err, response, body) { + + this.httpRequest('https://steamcommunity.com/market/listings/' + appid + '/' + encodeURIComponent(hashName), (err, response, body) => { if (err) { callback(err); return; } - var $ = Cheerio.load(body); - if($('.market_listing_table_message') && $('.market_listing_table_message').text().trim() == 'There are no listings for this item.') { - callback(new Error("There are no listings for this item.")); + let $ = Cheerio.load(body); + let $listingTableMessage = $('.market_listing_table_message'); + if ($listingTableMessage && $listingTableMessage.text().trim() == 'There are no listings for this item.') { + callback(new Error('There are no listings for this item.')); return; } - var item = new CMarketItem(appid, hashName, self, body, $); + let item = new CMarketItem(appid, hashName, this, body, $); item.updatePrice(currency, function(err) { - if(err) { + if (err) { callback(err); } else { callback(null, item); } }); - }, "steamcommunity"); + }, 'steamcommunity'); }; function CMarketItem(appid, hashName, community, body, $) { @@ -37,38 +38,38 @@ function CMarketItem(appid, hashName, community, body, $) { this._community = community; this._$ = $; - this._country = "US"; - var match = body.match(/var g_strCountryCode = "([^"]+)";/); - if(match) { + this._country = 'US'; + let match = body.match(/var g_strCountryCode = "([^"]+)";/); + if (match) { this._country = match[1]; } - this._language = "english"; + this._language = 'english'; match = body.match(/var g_strLanguage = "([^"]+)";/); - if(match) { + if (match) { this._language = match[1]; } this.commodity = false; match = body.match(/Market_LoadOrderSpread\(\s*(\d+)\s*\);/); - if(match) { + if (match) { this.commodity = true; this.commodityID = parseInt(match[1], 10); } this.medianSalePrices = null; match = body.match(/var line1=([^;]+);/); - if(match) { + if (match) { try { this.medianSalePrices = JSON.parse(match[1]); this.medianSalePrices = this.medianSalePrices.map(function(item) { return { - "hour": new Date(item[0]), - "price": item[1], - "quantity": parseInt(item[2], 10) + hour: new Date(item[0]), + price: item[1], + quantity: parseInt(item[2], 10) }; }); - } catch(e) { + } catch (e) { // ignore } } @@ -101,90 +102,88 @@ CMarketItem.prototype.updatePrice = function (currency, callback) { }; CMarketItem.prototype.updatePriceForCommodity = function(currency, callback) { - if(!this.commodity) { - throw new Error("Cannot update price for non-commodity item"); + if (!this.commodity) { + throw new Error('Cannot update price for non-commodity item'); } - var self = this; this._community.httpRequest({ - "uri": "https://steamcommunity.com/market/itemordershistogram?country=US&language=english¤cy=" + currency + "&item_nameid=" + this.commodityID, - "json": true - }, function(err, response, body) { - if (err) { - callback(err); - return; - } - - if(body.success != 1) { - if(callback) { - callback(new Error("Error " + body.success)); - } - - return; - } - - var match = (body.sell_order_summary || '').match(/(\d+)<\/span>/); - if(match) { - self.quantity = parseInt(match[1], 10); - } - - self.buyQuantity = 0; - match = (body.buy_order_summary || '').match(/(\d+)<\/span>/); - if(match) { - self.buyQuantity = parseInt(match[1], 10); - } - - self.lowestPrice = parseInt(body.lowest_sell_order, 10); - self.highestBuyOrder = parseInt(body.highest_buy_order, 10); - - // TODO: The tables? - if(callback) { - callback(null); - } - }, "steamcommunity"); -}; - -CMarketItem.prototype.updatePriceForNonCommodity = function (currency, callback) { - if(this.commodity) { - throw new Error("Cannot update price for commodity item"); - } - - var self = this; - this._community.httpRequest({ - "uri": "https://steamcommunity.com/market/listings/" + - this._appid + "/" + - encodeURIComponent(this._hashName) + - "/render/?query=&start=0&count=10&country=US&language=english¤cy=" + currency, - "json": true - }, function(err, response, body) { + uri: 'https://steamcommunity.com/market/itemordershistogram?country=US&language=english¤cy=' + currency + '&item_nameid=' + this.commodityID, + json: true + }, (err, response, body) => { if (err) { callback(err); return; } if (body.success != 1) { - callback && callback(new Error("Error " + body.success)); + if (callback) { + callback(new Error('Error ' + body.success)); + } + return; } - var match = body.total_count; + let match = (body.sell_order_summary || '').match(/(\d+)<\/span>/); if (match) { - self.quantity = parseInt(match, 10); + this.quantity = parseInt(match[1], 10); } - var lowestPrice; - var $ = Cheerio.load(body.results_html); - match = $(".market_listing_price.market_listing_price_with_fee"); + this.buyQuantity = 0; + match = (body.buy_order_summary || '').match(/(\d+)<\/span>/); if (match) { - for (var i = 0; i < match.length; i++) { - lowestPrice = parseFloat($(match[i]).text().replace(",", ".").replace(/[^\d.]/g, '')); + this.buyQuantity = parseInt(match[1], 10); + } + + this.lowestPrice = parseInt(body.lowest_sell_order, 10); + this.highestBuyOrder = parseInt(body.highest_buy_order, 10); + + // TODO: The tables? + if (callback) { + callback(null); + } + }, 'steamcommunity'); +}; + +CMarketItem.prototype.updatePriceForNonCommodity = function (currency, callback) { + if (this.commodity) { + throw new Error('Cannot update price for commodity item'); + } + + this._community.httpRequest({ + uri: 'https://steamcommunity.com/market/listings/' + + this._appid + '/' + + encodeURIComponent(this._hashName) + + '/render/?query=&start=0&count=10&country=US&language=english¤cy=' + currency, + json: true + }, (err, response, body) => { + if (err) { + callback(err); + return; + } + + if (body.success != 1) { + callback && callback(new Error('Error ' + body.success)); + return; + } + + let match = body.total_count; + if (match) { + this.quantity = parseInt(match, 10); + } + + let lowestPrice; + let $ = Cheerio.load(body.results_html); + match = $('.market_listing_price.market_listing_price_with_fee'); + if (match) { + for (let i = 0; i < match.length; i++) { + lowestPrice = parseFloat($(match[i]).text().replace(',', '.').replace(/[^\d.]/g, '')); if (!isNaN(lowestPrice)) { - self.lowestPrice = lowestPrice; + this.lowestPrice = lowestPrice; break; } } } callback && callback(null); - }, "steamcommunity"); + }, 'steamcommunity'); }; diff --git a/classes/CMarketSearchResult.js b/classes/CMarketSearchResult.js index 8d1c888..3affa66 100644 --- a/classes/CMarketSearchResult.js +++ b/classes/CMarketSearchResult.js @@ -3,18 +3,18 @@ const Cheerio = require('cheerio'); const SteamCommunity = require('../index.js'); SteamCommunity.prototype.marketSearch = function(options, callback) { - var qs = {}; + let qs = {}; - if(typeof options === 'string') { + if (typeof options === 'string') { qs.query = options; } else { qs.query = options.query || ''; qs.appid = options.appid; qs.search_descriptions = options.searchDescriptions ? 1 : 0; - if(qs.appid) { - for(var i in options) { - if(['query', 'appid', 'searchDescriptions'].indexOf(i) != -1) { + if (qs.appid) { + for (let i in options) { + if (['query', 'appid', 'searchDescriptions'].indexOf(i) != -1) { continue; } @@ -29,62 +29,61 @@ SteamCommunity.prototype.marketSearch = function(options, callback) { qs.sort_column = 'price'; qs.sort_dir = 'asc'; - var self = this; - var results = []; - performSearch(); - - function performSearch() { - self.httpRequest({ - "uri": "https://steamcommunity.com/market/search/render/", - "qs": qs, - "headers": { - "referer": "https://steamcommunity.com/market/search" + let results = []; + const performSearch = () => { + this.httpRequest({ + uri: 'https://steamcommunity.com/market/search/render/', + qs: qs, + headers: { + referer: 'https://steamcommunity.com/market/search' }, - "json": true + json: true }, function(err, response, body) { if (err) { callback(err); return; } - if(!body.success) { - callback(new Error("Success is not true")); + if (!body.success) { + callback(new Error('Success is not true')); return; } - if(!body.results_html) { - callback(new Error("No results_html in response")); + if (!body.results_html) { + callback(new Error('No results_html in response')); return; } - var $ = Cheerio.load(body.results_html); - var $errorMsg = $('.market_listing_table_message'); - if($errorMsg.length > 0) { + let $ = Cheerio.load(body.results_html); + let $errorMsg = $('.market_listing_table_message'); + if ($errorMsg.length > 0) { callback(new Error($errorMsg.text())); return; } - var rows = $('.market_listing_row_link'); - for(var i = 0; i < rows.length; i++) { + let rows = $('.market_listing_row_link'); + for (let i = 0; i < rows.length; i++) { results.push(new CMarketSearchResult($(rows[i]))); } - if(body.start + body.pagesize >= body.total_count) { + if (body.start + body.pagesize >= body.total_count) { callback(null, results); } else { qs.start += body.pagesize; performSearch(); } - }, "steamcommunity"); - } + }, 'steamcommunity'); + }; + + performSearch(); }; function CMarketSearchResult(row) { - var match = row.attr('href').match(/\/market\/listings\/(\d+)\/([^\?\/]+)/); + let match = row.attr('href').match(/\/market\/listings\/(\d+)\/([^?/]+)/); this.appid = parseInt(match[1], 10); this.market_hash_name = decodeURIComponent(match[2]); - this.image = ((row.find('.market_listing_item_img').attr('src') || "").match(/^https?:\/\/[^\/]+\/economy\/image\/[^\/]+\//) || [])[0]; + this.image = ((row.find('.market_listing_item_img').attr('src') || '').match(/^https?:\/\/[^/]+\/economy\/image\/[^/]+\//) || [])[0]; this.price = parseInt(row.find('.market_listing_their_price .market_table_value span.normal_price').text().replace(/[^\d]+/g, ''), 10); this.quantity = parseInt(row.find('.market_listing_num_listings_qty').text().replace(/[^\d]+/g, ''), 10); } diff --git a/classes/CSteamGroup.js b/classes/CSteamGroup.js index d93acfc..b1a3139 100644 --- a/classes/CSteamGroup.js +++ b/classes/CSteamGroup.js @@ -5,30 +5,29 @@ const Helpers = require('../components/helpers.js'); const SteamCommunity = require('../index.js'); SteamCommunity.prototype.getSteamGroup = function(id, callback) { - if(typeof id !== 'string' && !Helpers.isSteamID(id)) { - throw new Error("id parameter should be a group URL string or a SteamID object"); + if (typeof id !== 'string' && !Helpers.isSteamID(id)) { + throw new Error('id parameter should be a group URL string or a SteamID object'); } - if(typeof id === 'object' && (id.universe != SteamID.Universe.PUBLIC || id.type != SteamID.Type.CLAN)) { - throw new Error("SteamID must stand for a clan account in the public universe"); + if (typeof id === 'object' && (id.universe != SteamID.Universe.PUBLIC || id.type != SteamID.Type.CLAN)) { + throw new Error('SteamID must stand for a clan account in the public universe'); } - var self = this; - this.httpRequest("https://steamcommunity.com/" + (typeof id === 'string' ? "groups/" + id : "gid/" + id.toString()) + "/memberslistxml/?xml=1", function(err, response, body) { + this.httpRequest('https://steamcommunity.com/' + (typeof id === 'string' ? 'groups/' + id : 'gid/' + id.toString()) + '/memberslistxml/?xml=1', (err, response, body) => { if (err) { callback(err); return; } XML2JS.parseString(body, function(err, result) { - if(err) { + if (err) { callback(err); return; } - callback(null, new CSteamGroup(self, result.memberList)); + callback(null, new CSteamGroup(this, result.memberList)); }); - }, "steamcommunity"); + }, 'steamcommunity'); }; function CSteamGroup(community, groupData) { @@ -50,16 +49,16 @@ CSteamGroup.prototype.getAvatarURL = function(size, protocol) { size = size || ''; protocol = protocol || 'http://'; - var url = protocol + "steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/" + this.avatarHash.substring(0, 2) + "/" + this.avatarHash; - if(size == 'full' || size == 'medium') { - return url + "_" + size + ".jpg"; + let url = protocol + 'steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/' + this.avatarHash.substring(0, 2) + '/' + this.avatarHash; + if (size == 'full' || size == 'medium') { + return url + '_' + size + '.jpg'; } else { - return url + ".jpg"; + return url + '.jpg'; } }; CSteamGroup.prototype.getMembers = function(addresses, callback) { - if(typeof addresses === 'function') { + if (typeof addresses === 'function') { callback = addresses; addresses = null; } @@ -84,11 +83,11 @@ CSteamGroup.prototype.postAnnouncement = function(headline, content, hidden, cal }; CSteamGroup.prototype.editAnnouncement = function(annoucementID, headline, content, callback) { - this._community.editGroupAnnouncement(this.steamID, annoucementID, headline, content, callback) + this._community.editGroupAnnouncement(this.steamID, annoucementID, headline, content, callback); }; CSteamGroup.prototype.deleteAnnouncement = function(annoucementID, callback) { - this._community.deleteGroupAnnouncement(this.steamID, annoucementID, callback) + this._community.deleteGroupAnnouncement(this.steamID, annoucementID, callback); }; CSteamGroup.prototype.scheduleEvent = function(name, type, description, time, server, callback) { diff --git a/classes/CSteamUser.js b/classes/CSteamUser.js index 7ee6ce4..5ba68d3 100644 --- a/classes/CSteamUser.js +++ b/classes/CSteamUser.js @@ -5,49 +5,48 @@ const Helpers = require('../components/helpers.js'); const SteamCommunity = require('../index.js'); SteamCommunity.prototype.getSteamUser = function(id, callback) { - if(typeof id !== 'string' && !Helpers.isSteamID(id)) { - throw new Error("id parameter should be a user URL string or a SteamID object"); + if (typeof id !== 'string' && !Helpers.isSteamID(id)) { + throw new Error('id parameter should be a user URL string or a SteamID object'); } - if(typeof id === 'object' && (id.universe != SteamID.Universe.PUBLIC || id.type != SteamID.Type.INDIVIDUAL)) { - throw new Error("SteamID must stand for an individual account in the public universe"); + if (typeof id === 'object' && (id.universe != SteamID.Universe.PUBLIC || id.type != SteamID.Type.INDIVIDUAL)) { + throw new Error('SteamID must stand for an individual account in the public universe'); } - var self = this; - this.httpRequest("http://steamcommunity.com/" + (typeof id === 'string' ? "id/" + id : "profiles/" + id.toString()) + "/?xml=1", function(err, response, body) { + this.httpRequest('http://steamcommunity.com/' + (typeof id === 'string' ? 'id/' + id : 'profiles/' + id.toString()) + '/?xml=1', (err, response, body) => { if (err) { callback(err); return; } XML2JS.parseString(body, function(err, result) { - if(err || (!result.response && !result.profile)) { - callback(err || new Error("No valid response")); + if (err || (!result.response && !result.profile)) { + callback(err || new Error('No valid response')); return; } - if(result.response && result.response.error && result.response.error.length) { + if (result.response && result.response.error && result.response.error.length) { callback(new Error(result.response.error[0])); return; } // Try and find custom URL from redirect - var customurl = null; - if(response.request.redirects && response.request.redirects.length) { - var match = response.request.redirects[0].redirectUri.match(/https?:\/\/steamcommunity\.com\/id\/([^/])+\/\?xml=1/); - if(match) { + let customurl = null; + if (response.request.redirects && response.request.redirects.length) { + let match = response.request.redirects[0].redirectUri.match(/https?:\/\/steamcommunity\.com\/id\/([^/])+\/\?xml=1/); + if (match) { customurl = match[1]; } } - if(!result.profile.steamID64) { - callback(new Error("No valid response")); + if (!result.profile.steamID64) { + callback(new Error('No valid response')); return; } - callback(null, new CSteamUser(self, result.profile, customurl)); + callback(null, new CSteamUser(this, result.profile, customurl)); }); - }, "steamcommunity"); + }, 'steamcommunity'); }; function CSteamUser(community, userData, customurl) { @@ -60,7 +59,7 @@ function CSteamUser(community, userData, customurl) { this.privacyState = processItem('privacyState', 'uncreated'); this.visibilityState = processItem('visibilityState'); this.avatarHash = processItem('avatarIcon', '').match(/([0-9a-f]+)\.[a-z]+$/); - if(this.avatarHash) { + if (this.avatarHash) { this.avatarHash = this.avatarHash[1]; } @@ -69,8 +68,8 @@ function CSteamUser(community, userData, customurl) { this.isLimitedAccount = processItem('isLimitedAccount') == 1; this.customURL = processItem('customURL', customurl); - if(this.visibilityState == 3) { - let memberSinceValue = processItem('memberSince', '0').replace(/(\d{1,2})(st|nd|th)/, "$1"); + if (this.visibilityState == 3) { + let memberSinceValue = processItem('memberSince', '0').replace(/(\d{1,2})(st|nd|th)/, '$1'); if (memberSinceValue.indexOf(',') === -1) { memberSinceValue += ', ' + new Date().getFullYear(); @@ -92,11 +91,10 @@ function CSteamUser(community, userData, customurl) { this.groups = null; this.primaryGroup = null; - var self = this; - if(userData.groups && userData.groups[0] && userData.groups[0].group) { - this.groups = userData.groups[0].group.map(function(group) { - if(group['$'] && group['$'].isPrimary === "1") { - self.primaryGroup = new SteamID(group.groupID64[0]); + if (userData.groups && userData.groups[0] && userData.groups[0].group) { + this.groups = userData.groups[0].group.map((group) => { + if (group['$'] && group['$'].isPrimary === '1') { + this.primaryGroup = new SteamID(group.groupID64[0]); } return new SteamID(group.groupID64[0]); @@ -104,7 +102,7 @@ function CSteamUser(community, userData, customurl) { } function processItem(name, defaultVal) { - if(!userData[name]) { + if (!userData[name]) { return defaultVal; } @@ -116,13 +114,13 @@ CSteamUser.getAvatarURL = function(hash, size, protocol) { size = size || ''; protocol = protocol || 'http://'; - hash = hash || "72f78b4c8cc1f62323f8a33f6d53e27db57c2252"; // The default "?" avatar + hash = hash || '72f78b4c8cc1f62323f8a33f6d53e27db57c2252'; // The default "?" avatar - var url = protocol + "steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/" + hash.substring(0, 2) + "/" + hash; - if(size == 'full' || size == 'medium') { - return url + "_" + size + ".jpg"; + let url = protocol + 'steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/' + hash.substring(0, 2) + '/' + hash; + if (size == 'full' || size == 'medium') { + return url + '_' + size + '.jpg'; } else { - return url + ".jpg"; + return url + '.jpg'; } }; diff --git a/components/groups.js b/components/groups.js index 6a1c1ba..40d4f04 100644 --- a/components/groups.js +++ b/components/groups.js @@ -143,7 +143,7 @@ SteamCommunity.prototype.getAllGroupAnnouncements = function(gid, time, callback date: new Date(announcement.pubDate[0]), author: (typeof announcement.author === 'undefined') ? null : announcement.author[0], aid: splitLink[splitLink.length - 1] - } + }; }).filter(announcement => announcement.date > time); return callback(null, announcements); @@ -171,7 +171,7 @@ SteamCommunity.prototype.postGroupAnnouncement = function(gid, headline, content }; if (hidden) { - form.is_hidden = 'is_hidden' + form.is_hidden = 'is_hidden'; } this.httpRequestPost({ @@ -251,7 +251,7 @@ SteamCommunity.prototype.scheduleGroupEvent = function(gid, name, type, descript break; default: - if (typeof server != object) { + if (typeof server != 'object') { server = {ip: '', password: ''}; } } @@ -314,7 +314,7 @@ SteamCommunity.prototype.editGroupEvent = function(gid, id, name, type, descript break; default: - if (typeof server != object) { + if (typeof server != 'object') { server = {ip: '', password: ''}; } } diff --git a/components/help.js b/components/help.js index 881e361..c0d6a86 100644 --- a/components/help.js +++ b/components/help.js @@ -1,7 +1,5 @@ const SteamCommunity = require('../index.js'); -const Helpers = require('./helpers.js'); - const HELP_SITE_DOMAIN = 'https://help.steampowered.com'; /** diff --git a/components/helpers.js b/components/helpers.js index e493b62..64d1ddc 100644 --- a/components/helpers.js +++ b/components/helpers.js @@ -38,7 +38,7 @@ exports.decodeSteamTime = function(time) { /** * Get an Error object for a particular EResult - * @param {int} eresult + * @param {int|EResult} eresult * @param {string} [message] - If eresult is a failure code and message exists, this message will be used in the Error object instead * @returns {null|Error} */ @@ -48,7 +48,7 @@ exports.eresultError = function(eresult, message) { return null; } - let err = new Error(message || EResult[eresult] || ("Error " + eresult)); + let err = new Error(message || EResult[eresult] || `Error ${eresult}`); err.eresult = eresult; return err; }; diff --git a/components/market.js b/components/market.js index 25049a4..c786eeb 100644 --- a/components/market.js +++ b/components/market.js @@ -103,7 +103,7 @@ SteamCommunity.prototype.turnItemIntoGems = function(appid, assetid, expectedGem } callback(null, {gemsReceived: parseInt(body['goo_value_received '], 10), totalGems: parseInt(body.goo_value_total, 10)}); - }) + }); }; /** @@ -138,7 +138,7 @@ SteamCommunity.prototype.openBoosterPack = function(appid, assetid, callback) { } callback(null, body.rgItems); - }) + }); }; /** diff --git a/components/profile.js b/components/profile.js index 793af24..7f837c1 100644 --- a/components/profile.js +++ b/components/profile.js @@ -1,6 +1,5 @@ const Cheerio = require('cheerio'); const FS = require('fs'); -const SteamID = require('steamid'); const Helpers = require('./helpers.js'); const SteamCommunity = require('../index.js'); @@ -12,9 +11,9 @@ SteamCommunity.PrivacyState = { }; const CommentPrivacyState = { - '1': 2, // private - '2': 0, // friends only - '3': 1 // anyone + 1: 2, // private + 2: 0, // friends only + 3: 1 // anyone }; /** @@ -80,11 +79,7 @@ SteamCommunity.prototype.editProfile = function(settings, callback) { }; for (let i in settings) { - if(!settings.hasOwnProperty(i)) { - continue; - } - - switch(i) { + switch (i) { case 'name': values.personaName = settings[i]; break; @@ -193,10 +188,6 @@ SteamCommunity.prototype.profileSettings = function(settings, callback) { let commentPermission = existingSettings.Privacy.eCommentPermission; for (let i in settings) { - if (!settings.hasOwnProperty(i)) { - continue; - } - switch (i) { case 'profile': privacy.PrivacyProfile = settings[i]; @@ -260,7 +251,7 @@ SteamCommunity.prototype.profileSettings = function(settings, callback) { }; SteamCommunity.prototype.uploadAvatar = function(image, format, callback) { - if(typeof format === 'function') { + if (typeof format === 'function') { callback = format; format = null; } @@ -346,7 +337,7 @@ SteamCommunity.prototype.uploadAvatar = function(image, format, callback) { return; } - if(!body || !body.success) { + if (!body || !body.success) { callback && callback(new Error('Malformed response')); return; } @@ -394,7 +385,7 @@ SteamCommunity.prototype.uploadAvatar = function(image, format, callback) { } doUpload(file); - }) + }); } }; diff --git a/components/twofactor.js b/components/twofactor.js index 0bcbb86..b6d5d7d 100644 --- a/components/twofactor.js +++ b/components/twofactor.js @@ -86,7 +86,11 @@ SteamCommunity.prototype.finalizeTwoFactor = function(secret, activationCode, ca if (body.status == SteamCommunity.EResult.TwoFactorActivationCodeMismatch) { callback(new Error('Invalid activation code')); } else if (body.want_more) { - attemptsLeft--; + if (--attemptsLeft <= 0) { + // We made more than 30 attempts, something must be wrong + return callback(Helpers.eresultError(SteamCommunity.EResult.Fail)); + } + diff += 30; finalize(); @@ -96,7 +100,7 @@ SteamCommunity.prototype.finalizeTwoFactor = function(secret, activationCode, ca callback(null); } }, 'steamcommunity'); - } + }; SteamTotp.getTimeOffset((err, offset, latency) => { if (err) { diff --git a/components/users.js b/components/users.js index 464e954..d8bc2f9 100644 --- a/components/users.js +++ b/components/users.js @@ -241,7 +241,7 @@ SteamCommunity.prototype.getUserComments = function(userID, options, callback) { date: new Date($elem.find('.commentthread_comment_timestamp').data('timestamp') * 1000), text: $commentContent.text().trim(), html: $commentContent.html().trim() - } + }; }).get(); callback(null, comments, body.total_count); @@ -444,25 +444,16 @@ SteamCommunity.prototype.getUserInventory = function(userID, appID, contextID, t return; } - let i; - for (i in body.rgInventory) { - if (!body.rgInventory.hasOwnProperty(i)) { - continue; - } - + for (let i in body.rgInventory) { inventory.push(new CEconItem(body.rgInventory[i], body.rgDescriptions, contextID)); } - for (i in body.rgCurrency) { - if (!body.rgCurrency.hasOwnProperty(i)) { - continue; - } - + for (let i in body.rgCurrency) { currency.push(new CEconItem(body.rgInventory[i], body.rgDescriptions, contextID)); } if (body.more) { - let match = response.request.uri.href.match(/\/(profiles|id)\/([^\/]+)\//); + let match = response.request.uri.href.match(/\/(profiles|id)\/([^/]+)\//); if (match) { endpoint = `/${match[1]}/${match[2]}`; } diff --git a/examples/edit-group-announcement.js b/examples/edit-group-announcement.js index 9fe8fd7..4a20c1f 100644 --- a/examples/edit-group-announcement.js +++ b/examples/edit-group-announcement.js @@ -1,47 +1,47 @@ -var SteamCommunity = require('../index.js'); -var ReadLine = require('readline'); +let SteamCommunity = require('../index.js'); +let ReadLine = require('readline'); -var community = new SteamCommunity(); -var rl = ReadLine.createInterface({ - "input": process.stdin, - "output": process.stdout +let community = new SteamCommunity(); +let rl = ReadLine.createInterface({ + input: process.stdin, + output: process.stdout }); -rl.question("Username: ", function(accountName) { - rl.question("Password: ", function(password) { +rl.question('Username: ', function(accountName) { + rl.question('Password: ', function(password) { doLogin(accountName, password); }); }); function doLogin(accountName, password, authCode, twoFactorCode, captcha) { community.login({ - "accountName": accountName, - "password": password, - "authCode": authCode, - "twoFactorCode": twoFactorCode, - "captcha": captcha + accountName: accountName, + password: password, + authCode: authCode, + twoFactorCode: twoFactorCode, + captcha: captcha }, function(err, sessionID, cookies, steamguard) { - if(err) { - if(err.message == 'SteamGuardMobile') { - rl.question("Steam Authenticator Code: ", function(code) { + if (err) { + if (err.message == 'SteamGuardMobile') { + rl.question('Steam Authenticator Code: ', function(code) { doLogin(accountName, password, null, code); }); return; } - if(err.message == 'SteamGuard') { - console.log("An email has been sent to your address at " + err.emaildomain); - rl.question("Steam Guard Code: ", function(code) { + if (err.message == 'SteamGuard') { + console.log('An email has been sent to your address at ' + err.emaildomain); + rl.question('Steam Guard Code: ', function(code) { doLogin(accountName, password, code); }); return; } - if(err.message == 'CAPTCHA') { + if (err.message == 'CAPTCHA') { console.log(err.captchaurl); - rl.question("CAPTCHA: ", function(captchaInput) { + rl.question('CAPTCHA: ', function(captchaInput) { doLogin(accountName, password, authCode, twoFactorCode, captchaInput); }); @@ -53,9 +53,9 @@ function doLogin(accountName, password, authCode, twoFactorCode, captcha) { return; } - console.log("Logged on!"); + console.log('Logged on!'); - rl.question("Group ID: ", function(gid) { + rl.question('Group ID: ', function(gid) { community.getSteamGroup(gid, function(err, group) { if (err) { console.log(err); @@ -64,19 +64,19 @@ function doLogin(accountName, password, authCode, twoFactorCode, captcha) { group.getAllAnnouncements(function(err, announcements) { - if(announcements.length === 0) { - return console.log("This group has no announcements"); + if (announcements.length === 0) { + return console.log('This group has no announcements'); } - for (var i = announcements.length - 1; i >= 0; i--) { - console.log("[%s] %s %s: %s", announcements[i].date, announcements[i].aid, announcements[i].author, announcements[i].content); - }; + for (let i = announcements.length - 1; i >= 0; i--) { + console.log('[%s] %s %s: %s', announcements[i].date, announcements[i].aid, announcements[i].author, announcements[i].content); + } - rl.question("Would you like to delete delete or edit an annoucement? (Type edit/delete): ", function(choice) { - rl.question("Annoucement ID: ", function(aid) { - if(choice === 'edit') { - rl.question("New title: ", function(header) { - rl.question("New body: ", function(content) { + rl.question('Would you like to delete delete or edit an annoucement? (Type edit/delete): ', function(choice) { + rl.question('Annoucement ID: ', function(aid) { + if (choice === 'edit') { + rl.question('New title: ', function(header) { + rl.question('New body: ', function(content) { // EW THE PYRAMID! // Try replace this with delete! editAnnouncement(group, aid, header, content); @@ -96,10 +96,10 @@ function doLogin(accountName, password, authCode, twoFactorCode, captcha) { function editAnnouncement(group, aid, header, content) { // Actual community method. group.editAnnouncement(aid, header, content, function(error) { - if(!error) { - console.log("Annoucement edited!"); + if (!error) { + console.log('Annoucement edited!'); } else { - console.log("Unable to edit annoucement! %j", error); + console.log('Unable to edit annoucement! %j', error); process.exit(1); } }); @@ -109,10 +109,10 @@ function deleteAnnouncement(group, aid) { // group.deleteAnnouncement(aid); // Or group.deleteAnnouncement(aid, function(err) { - if(!err) { - console.log("Deleted"); + if (!err) { + console.log('Deleted'); } else { - console.log("Error deleting announcement."); + console.log('Error deleting announcement.'); } - }) + }); } diff --git a/index.js b/index.js index 434c743..e0e0dd3 100644 --- a/index.js +++ b/index.js @@ -68,10 +68,8 @@ SteamCommunity.prototype.login = function(details, callback) { let disableMobile = details.disableMobile; - let self = this; - // Delete the cache - delete self._profileURL; + delete this._profileURL; // headers required to convince steam that we're logging in from a mobile device so that we can get the oAuth data let mobileHeaders = {}; @@ -89,11 +87,21 @@ SteamCommunity.prototype.login = function(details, callback) { mobileHeaders = {Referer: 'https://steamcommunity.com/login'}; } + const deleteMobileCookies = () => { + let cookie = Request.cookie('mobileClientVersion='); + cookie.expires = new Date(0); + this._setCookie(cookie); + + cookie = Request.cookie('mobileClient='); + cookie.expires = new Date(0); + this._setCookie(cookie); + }; + this.httpRequestPost('https://steamcommunity.com/login/getrsakey/', { form: {username: details.accountName}, headers: mobileHeaders, json: true - }, function(err, response, body) { + }, (err, response, body) => { // Remove the mobile cookies if (err) { deleteMobileCookies(); @@ -112,7 +120,7 @@ SteamCommunity.prototype.login = function(details, callback) { let formObj = { captcha_text: details.captcha || '', - captchagid: self._captchaGid, + captchagid: this._captchaGid, emailauth: details.authCode || '', emailsteamid: '', password: hex2b64(key.encrypt(details.password)), @@ -130,12 +138,12 @@ SteamCommunity.prototype.login = function(details, callback) { formObj.loginfriendlyname = '#login_emailauth_friendlyname_mobile'; } - self.httpRequestPost({ + this.httpRequestPost({ uri: 'https://steamcommunity.com/login/dologin/', json: true, form: formObj, headers: mobileHeaders - }, function(err, response, body) { + }, (err, response, body) => { deleteMobileCookies(); if (err) { @@ -157,7 +165,7 @@ SteamCommunity.prototype.login = function(details, callback) { error = new Error('CAPTCHA'); error.captchaurl = 'https://steamcommunity.com/login/rendercaptcha/?gid=' + body.captcha_gid; - self._captchaGid = body.captcha_gid; + this._captchaGid = body.captcha_gid; callback(error); } else if (!body.success) { @@ -167,68 +175,53 @@ SteamCommunity.prototype.login = function(details, callback) { } else { let sessionID = generateSessionID(); let oAuth; - self._setCookie(Request.cookie('sessionid=' + sessionID)); + this._setCookie(Request.cookie('sessionid=' + sessionID)); - let cookies = self._jar.getCookieString('https://steamcommunity.com').split(';').map(function(cookie) { - return cookie.trim(); - }); + let cookies = this._jar.getCookieString('https://steamcommunity.com').split(';').map(cookie => cookie.trim()); if (!disableMobile){ oAuth = JSON.parse(body.oauth); - self.steamID = new SteamID(oAuth.steamid); - self.oAuthToken = oAuth.oauth_token; + this.steamID = new SteamID(oAuth.steamid); + this.oAuthToken = oAuth.oauth_token; } else { for (let i = 0; i < cookies.length; i++) { let parts = cookies[i].split('='); if (parts[0] == 'steamLogin') { - self.steamID = new SteamID(decodeURIComponent(parts[1]).split('||')[0]); + this.steamID = new SteamID(decodeURIComponent(parts[1]).split('||')[0]); break; } } - self.oAuthToken = null; + this.oAuthToken = null; } // Find the Steam Guard cookie let steamguard = null; for (let i = 0; i < cookies.length; i++) { let parts = cookies[i].split('='); - if (parts[0] == 'steamMachineAuth' + self.steamID) { - steamguard = self.steamID.toString() + '||' + decodeURIComponent(parts[1]); + if (parts[0] == 'steamMachineAuth' + this.steamID) { + steamguard = this.steamID.toString() + '||' + decodeURIComponent(parts[1]); break; } } - self.setCookies(cookies); + this.setCookies(cookies); callback(null, sessionID, cookies, steamguard, disableMobile ? null : oAuth.oauth_token); } }, 'steamcommunity'); }, 'steamcommunity'); - - function deleteMobileCookies() { - let cookie = Request.cookie('mobileClientVersion='); - cookie.expires = new Date(0); - self._setCookie(cookie); - - cookie = Request.cookie('mobileClient='); - cookie.expires = new Date(0); - self._setCookie(cookie); - } }; SteamCommunity.prototype.oAuthLogin = function(steamguard, token, callback) { steamguard = steamguard.split('||'); let steamID = new SteamID(steamguard[0]); - let self = this; this.httpRequestPost({ uri: 'https://api.steampowered.com/IMobileAuthService/GetWGToken/v1/', - form: { - access_token: token - }, + form: {access_token: token}, json: true - }, function(err, response, body) { + }, (err, response, body) => { if (err) { callback(err); return; @@ -243,11 +236,11 @@ SteamCommunity.prototype.oAuthLogin = function(steamguard, token, callback) { 'steamLogin=' + encodeURIComponent(steamID.getSteamID64() + '||' + body.response.token), 'steamLoginSecure=' + encodeURIComponent(steamID.getSteamID64() + '||' + body.response.token_secure), 'steamMachineAuth' + steamID.getSteamID64() + '=' + steamguard[1], - 'sessionid=' + self.getSessionID() + 'sessionid=' + this.getSessionID() ]; - self.setCookies(cookies); - callback(null, self.getSessionID(), cookies); + this.setCookies(cookies); + callback(null, this.getSessionID(), cookies); }, 'steamcommunity'); }; @@ -324,8 +317,7 @@ function generateSessionID() { } SteamCommunity.prototype.parentalUnlock = function(pin, callback) { - let self = this; - let sessionID = self.getSessionID(); + let sessionID = this.getSessionID(); this.httpRequestPost('https://steamcommunity.com/parental/ajaxunlock', { json: true, @@ -333,7 +325,7 @@ SteamCommunity.prototype.parentalUnlock = function(pin, callback) { pin: pin, sessionid: sessionID } - }, function(err, response, body) { + }, (err, response, body) => { if (!callback) { return; } @@ -366,7 +358,7 @@ SteamCommunity.prototype.parentalUnlock = function(pin, callback) { } callback(); - }.bind(this), 'steamcommunity'); + }, 'steamcommunity'); }; SteamCommunity.prototype.getNotifications = function(callback) { @@ -493,33 +485,7 @@ SteamCommunity.prototype.clearPersonaNameHistory = function(callback) { }; SteamCommunity.prototype._myProfile = function(endpoint, form, callback) { - let self = this; - - if (this._profileURL) { - completeRequest(this._profileURL); - } else { - this.httpRequest('https://steamcommunity.com/my', {followRedirect: false}, function(err, response, body) { - if (err || response.statusCode != 302) { - callback(err || 'HTTP error ' + response.statusCode); - return; - } - - let match = response.headers.location.match(/steamcommunity\.com(\/(id|profiles)\/[^/]+)\/?/); - if (!match) { - callback(new Error('Can\'t get profile URL')); - return; - } - - self._profileURL = match[1]; - setTimeout(function () { - delete self._profileURL; // delete the cache - }, 60000).unref(); - - completeRequest(match[1]); - }, 'steamcommunity'); - } - - function completeRequest(url) { + const completeRequest = (url) => { let options = endpoint.endpoint ? endpoint : {}; options.uri = 'https://steamcommunity.com' + url + '/' + (endpoint.endpoint || endpoint); @@ -531,7 +497,31 @@ SteamCommunity.prototype._myProfile = function(endpoint, form, callback) { options.method = 'GET'; } - self.httpRequest(options, callback, 'steamcommunity'); + this.httpRequest(options, callback, 'steamcommunity'); + }; + + if (this._profileURL) { + completeRequest(this._profileURL); + } else { + this.httpRequest('https://steamcommunity.com/my', {followRedirect: false}, (err, response, body) => { + if (err || response.statusCode != 302) { + callback(err || 'HTTP error ' + response.statusCode); + return; + } + + let match = response.headers.location.match(/steamcommunity\.com(\/(id|profiles)\/[^/]+)\/?/); + if (!match) { + callback(new Error('Can\'t get profile URL')); + return; + } + + this._profileURL = match[1]; + setTimeout(() => { + delete this._profileURL; // delete the cache + }, 60000).unref(); + + completeRequest(match[1]); + }, 'steamcommunity'); } };