Refactor all files

This commit is contained in:
Alex Corn 2021-07-29 02:55:56 -04:00
parent 4c59309eb4
commit 600a41143b
No known key found for this signature in database
GPG Key ID: E51989A3E7A27FDF
16 changed files with 299 additions and 334 deletions

View File

@ -8,5 +8,6 @@
<inspection_tool class="JSEqualityComparisonWithCoercion" enabled="false" level="WARNING" enabled_by_default="false" /> <inspection_tool class="JSEqualityComparisonWithCoercion" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="JSFunctionExpressionToArrowFunction" enabled="false" level="INFORMATION" enabled_by_default="false" /> <inspection_tool class="JSFunctionExpressionToArrowFunction" enabled="false" level="INFORMATION" enabled_by_default="false" />
<inspection_tool class="JSStringConcatenationToES6Template" enabled="false" level="INFORMATION" enabled_by_default="false" /> <inspection_tool class="JSStringConcatenationToES6Template" enabled="false" level="INFORMATION" enabled_by_default="false" />
<inspection_tool class="JSUnfilteredForInLoop" enabled="false" level="WARNING" enabled_by_default="false" />
</profile> </profile>
</component> </component>

View File

@ -3,7 +3,7 @@ const SteamCommunity = require('../index.js');
module.exports = CConfirmation; module.exports = CConfirmation;
function CConfirmation(community, data) { function CConfirmation(community, data) {
Object.defineProperty(this, "_community", {"value": community}); Object.defineProperty(this, '_community', {value: community});
this.id = data.id.toString(); this.id = data.id.toString();
this.type = data.type; this.type = data.type;
@ -19,7 +19,7 @@ function CConfirmation(community, data) {
CConfirmation.prototype.getOfferID = function(time, key, callback) { CConfirmation.prototype.getOfferID = function(time, key, callback) {
if (this.type && this.creator) { if (this.type && this.creator) {
if (this.type != SteamCommunity.ConfirmationType.Trade) { if (this.type != SteamCommunity.ConfirmationType.Trade) {
callback(new Error("Not a trade confirmation")); callback(new Error('Not a trade confirmation'));
return; return;
} }

View File

@ -1,14 +1,11 @@
module.exports = CEconItem; module.exports = CEconItem;
function CEconItem(item, description, contextID) { function CEconItem(item, description, contextID) {
var thing; for (let thing in item) {
for (thing in item) { this[thing] = item[thing];
if (item.hasOwnProperty(thing)) {
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) { if (isCurrency) {
this.currencyid = this.id = (this.id || this.currencyid); this.currencyid = this.id = (this.id || this.currencyid);
@ -27,10 +24,8 @@ function CEconItem(item, description, contextID) {
description = description[this.classid + '_' + this.instanceid]; description = description[this.classid + '_' + this.instanceid];
} }
for (thing in description) { for (let thing in description) {
if (description.hasOwnProperty(thing)) { this[thing] = description[thing];
this[thing] = description[thing];
}
} }
} }
@ -51,18 +46,18 @@ function CEconItem(item, description, contextID) {
if (this.tags) { if (this.tags) {
this.tags = this.tags.map(function(tag) { this.tags = this.tags.map(function(tag) {
return { return {
"internal_name": tag.internal_name, internal_name: tag.internal_name,
"name": tag.localized_tag_name || tag.name, name: tag.localized_tag_name || tag.name,
"category": tag.category, category: tag.category,
"color": tag.color || "", color: tag.color || '',
"category_name": tag.localized_category_name || tag.category_name category_name: tag.localized_category_name || tag.category_name
}; };
}); });
} }
// Restore market_fee_app, if applicable // Restore market_fee_app, if applicable
var match; let match;
if (this.appid == 753 && this.contextid == 6 && this.market_hash_name && (match = this.market_hash_name.match(/^(\d+)\-/))) { 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); this.market_fee_app = parseInt(match[1], 10);
} }
@ -82,7 +77,7 @@ function CEconItem(item, description, contextID) {
this.cache_expiration = this.item_expiration; this.cache_expiration = this.item_expiration;
} }
if (this.actions === "") { if (this.actions === '') {
this.actions = []; this.actions = [];
} }
@ -94,15 +89,15 @@ function CEconItem(item, description, contextID) {
} }
CEconItem.prototype.getImageURL = function() { 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() { CEconItem.prototype.getLargeImageURL = function() {
if(!this.icon_url_large) { if (!this.icon_url_large) {
return this.getImageURL(); 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) { CEconItem.prototype.getTag = function(category) {
@ -110,7 +105,7 @@ CEconItem.prototype.getTag = function(category) {
return null; 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) { if (this.tags[i].category == category) {
return this.tags[i]; return this.tags[i];
} }

View File

@ -3,32 +3,33 @@ const Cheerio = require('cheerio');
const SteamCommunity = require('../index.js'); const SteamCommunity = require('../index.js');
SteamCommunity.prototype.getMarketItem = function(appid, hashName, currency, callback) { SteamCommunity.prototype.getMarketItem = function(appid, hashName, currency, callback) {
if (typeof currency == "function") { if (typeof currency == 'function') {
callback = currency; callback = currency;
currency = 1; 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) { if (err) {
callback(err); callback(err);
return; return;
} }
var $ = Cheerio.load(body); let $ = Cheerio.load(body);
if($('.market_listing_table_message') && $('.market_listing_table_message').text().trim() == 'There are no listings for this item.') { let $listingTableMessage = $('.market_listing_table_message');
callback(new Error("There are no listings for this item.")); if ($listingTableMessage && $listingTableMessage.text().trim() == 'There are no listings for this item.') {
callback(new Error('There are no listings for this item.'));
return; return;
} }
var item = new CMarketItem(appid, hashName, self, body, $); let item = new CMarketItem(appid, hashName, this, body, $);
item.updatePrice(currency, function(err) { item.updatePrice(currency, function(err) {
if(err) { if (err) {
callback(err); callback(err);
} else { } else {
callback(null, item); callback(null, item);
} }
}); });
}, "steamcommunity"); }, 'steamcommunity');
}; };
function CMarketItem(appid, hashName, community, body, $) { function CMarketItem(appid, hashName, community, body, $) {
@ -37,38 +38,38 @@ function CMarketItem(appid, hashName, community, body, $) {
this._community = community; this._community = community;
this._$ = $; this._$ = $;
this._country = "US"; this._country = 'US';
var match = body.match(/var g_strCountryCode = "([^"]+)";/); let match = body.match(/var g_strCountryCode = "([^"]+)";/);
if(match) { if (match) {
this._country = match[1]; this._country = match[1];
} }
this._language = "english"; this._language = 'english';
match = body.match(/var g_strLanguage = "([^"]+)";/); match = body.match(/var g_strLanguage = "([^"]+)";/);
if(match) { if (match) {
this._language = match[1]; this._language = match[1];
} }
this.commodity = false; this.commodity = false;
match = body.match(/Market_LoadOrderSpread\(\s*(\d+)\s*\);/); match = body.match(/Market_LoadOrderSpread\(\s*(\d+)\s*\);/);
if(match) { if (match) {
this.commodity = true; this.commodity = true;
this.commodityID = parseInt(match[1], 10); this.commodityID = parseInt(match[1], 10);
} }
this.medianSalePrices = null; this.medianSalePrices = null;
match = body.match(/var line1=([^;]+);/); match = body.match(/var line1=([^;]+);/);
if(match) { if (match) {
try { try {
this.medianSalePrices = JSON.parse(match[1]); this.medianSalePrices = JSON.parse(match[1]);
this.medianSalePrices = this.medianSalePrices.map(function(item) { this.medianSalePrices = this.medianSalePrices.map(function(item) {
return { return {
"hour": new Date(item[0]), hour: new Date(item[0]),
"price": item[1], price: item[1],
"quantity": parseInt(item[2], 10) quantity: parseInt(item[2], 10)
}; };
}); });
} catch(e) { } catch (e) {
// ignore // ignore
} }
} }
@ -101,90 +102,88 @@ CMarketItem.prototype.updatePrice = function (currency, callback) {
}; };
CMarketItem.prototype.updatePriceForCommodity = function(currency, callback) { CMarketItem.prototype.updatePriceForCommodity = function(currency, callback) {
if(!this.commodity) { if (!this.commodity) {
throw new Error("Cannot update price for non-commodity item"); throw new Error('Cannot update price for non-commodity item');
} }
var self = this;
this._community.httpRequest({ this._community.httpRequest({
"uri": "https://steamcommunity.com/market/itemordershistogram?country=US&language=english&currency=" + currency + "&item_nameid=" + this.commodityID, uri: 'https://steamcommunity.com/market/itemordershistogram?country=US&language=english&currency=' + currency + '&item_nameid=' + this.commodityID,
"json": true json: true
}, function(err, response, body) { }, (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(/<span class="market_commodity_orders_header_promote">(\d+)<\/span>/);
if(match) {
self.quantity = parseInt(match[1], 10);
}
self.buyQuantity = 0;
match = (body.buy_order_summary || '').match(/<span class="market_commodity_orders_header_promote">(\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&currency=" + currency,
"json": true
}, function(err, response, body) {
if (err) { if (err) {
callback(err); callback(err);
return; return;
} }
if (body.success != 1) { if (body.success != 1) {
callback && callback(new Error("Error " + body.success)); if (callback) {
callback(new Error('Error ' + body.success));
}
return; return;
} }
var match = body.total_count; let match = (body.sell_order_summary || '').match(/<span class="market_commodity_orders_header_promote">(\d+)<\/span>/);
if (match) { if (match) {
self.quantity = parseInt(match, 10); this.quantity = parseInt(match[1], 10);
} }
var lowestPrice; this.buyQuantity = 0;
var $ = Cheerio.load(body.results_html); match = (body.buy_order_summary || '').match(/<span class="market_commodity_orders_header_promote">(\d+)<\/span>/);
match = $(".market_listing_price.market_listing_price_with_fee");
if (match) { if (match) {
for (var i = 0; i < match.length; i++) { this.buyQuantity = parseInt(match[1], 10);
lowestPrice = parseFloat($(match[i]).text().replace(",", ".").replace(/[^\d.]/g, '')); }
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&currency=' + 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)) { if (!isNaN(lowestPrice)) {
self.lowestPrice = lowestPrice; this.lowestPrice = lowestPrice;
break; break;
} }
} }
} }
callback && callback(null); callback && callback(null);
}, "steamcommunity"); }, 'steamcommunity');
}; };

View File

@ -3,18 +3,18 @@ const Cheerio = require('cheerio');
const SteamCommunity = require('../index.js'); const SteamCommunity = require('../index.js');
SteamCommunity.prototype.marketSearch = function(options, callback) { SteamCommunity.prototype.marketSearch = function(options, callback) {
var qs = {}; let qs = {};
if(typeof options === 'string') { if (typeof options === 'string') {
qs.query = options; qs.query = options;
} else { } else {
qs.query = options.query || ''; qs.query = options.query || '';
qs.appid = options.appid; qs.appid = options.appid;
qs.search_descriptions = options.searchDescriptions ? 1 : 0; qs.search_descriptions = options.searchDescriptions ? 1 : 0;
if(qs.appid) { if (qs.appid) {
for(var i in options) { for (let i in options) {
if(['query', 'appid', 'searchDescriptions'].indexOf(i) != -1) { if (['query', 'appid', 'searchDescriptions'].indexOf(i) != -1) {
continue; continue;
} }
@ -29,62 +29,61 @@ SteamCommunity.prototype.marketSearch = function(options, callback) {
qs.sort_column = 'price'; qs.sort_column = 'price';
qs.sort_dir = 'asc'; qs.sort_dir = 'asc';
var self = this; let results = [];
var results = []; const performSearch = () => {
performSearch(); this.httpRequest({
uri: 'https://steamcommunity.com/market/search/render/',
function performSearch() { qs: qs,
self.httpRequest({ headers: {
"uri": "https://steamcommunity.com/market/search/render/", referer: 'https://steamcommunity.com/market/search'
"qs": qs,
"headers": {
"referer": "https://steamcommunity.com/market/search"
}, },
"json": true json: true
}, function(err, response, body) { }, function(err, response, body) {
if (err) { if (err) {
callback(err); callback(err);
return; return;
} }
if(!body.success) { if (!body.success) {
callback(new Error("Success is not true")); callback(new Error('Success is not true'));
return; return;
} }
if(!body.results_html) { if (!body.results_html) {
callback(new Error("No results_html in response")); callback(new Error('No results_html in response'));
return; return;
} }
var $ = Cheerio.load(body.results_html); let $ = Cheerio.load(body.results_html);
var $errorMsg = $('.market_listing_table_message'); let $errorMsg = $('.market_listing_table_message');
if($errorMsg.length > 0) { if ($errorMsg.length > 0) {
callback(new Error($errorMsg.text())); callback(new Error($errorMsg.text()));
return; return;
} }
var rows = $('.market_listing_row_link'); let rows = $('.market_listing_row_link');
for(var i = 0; i < rows.length; i++) { for (let i = 0; i < rows.length; i++) {
results.push(new CMarketSearchResult($(rows[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); callback(null, results);
} else { } else {
qs.start += body.pagesize; qs.start += body.pagesize;
performSearch(); performSearch();
} }
}, "steamcommunity"); }, 'steamcommunity');
} };
performSearch();
}; };
function CMarketSearchResult(row) { 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.appid = parseInt(match[1], 10);
this.market_hash_name = decodeURIComponent(match[2]); 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.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); this.quantity = parseInt(row.find('.market_listing_num_listings_qty').text().replace(/[^\d]+/g, ''), 10);
} }

View File

@ -5,30 +5,29 @@ const Helpers = require('../components/helpers.js');
const SteamCommunity = require('../index.js'); const SteamCommunity = require('../index.js');
SteamCommunity.prototype.getSteamGroup = function(id, callback) { SteamCommunity.prototype.getSteamGroup = function(id, callback) {
if(typeof id !== 'string' && !Helpers.isSteamID(id)) { if (typeof id !== 'string' && !Helpers.isSteamID(id)) {
throw new Error("id parameter should be a group URL string or a SteamID object"); 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)) { 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"); 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', (err, response, body) => {
this.httpRequest("https://steamcommunity.com/" + (typeof id === 'string' ? "groups/" + id : "gid/" + id.toString()) + "/memberslistxml/?xml=1", function(err, response, body) {
if (err) { if (err) {
callback(err); callback(err);
return; return;
} }
XML2JS.parseString(body, function(err, result) { XML2JS.parseString(body, function(err, result) {
if(err) { if (err) {
callback(err); callback(err);
return; return;
} }
callback(null, new CSteamGroup(self, result.memberList)); callback(null, new CSteamGroup(this, result.memberList));
}); });
}, "steamcommunity"); }, 'steamcommunity');
}; };
function CSteamGroup(community, groupData) { function CSteamGroup(community, groupData) {
@ -50,16 +49,16 @@ CSteamGroup.prototype.getAvatarURL = function(size, protocol) {
size = size || ''; size = size || '';
protocol = protocol || 'http://'; protocol = protocol || 'http://';
var url = protocol + "steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/" + this.avatarHash.substring(0, 2) + "/" + this.avatarHash; let url = protocol + 'steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/' + this.avatarHash.substring(0, 2) + '/' + this.avatarHash;
if(size == 'full' || size == 'medium') { if (size == 'full' || size == 'medium') {
return url + "_" + size + ".jpg"; return url + '_' + size + '.jpg';
} else { } else {
return url + ".jpg"; return url + '.jpg';
} }
}; };
CSteamGroup.prototype.getMembers = function(addresses, callback) { CSteamGroup.prototype.getMembers = function(addresses, callback) {
if(typeof addresses === 'function') { if (typeof addresses === 'function') {
callback = addresses; callback = addresses;
addresses = null; addresses = null;
} }
@ -84,11 +83,11 @@ CSteamGroup.prototype.postAnnouncement = function(headline, content, hidden, cal
}; };
CSteamGroup.prototype.editAnnouncement = function(annoucementID, headline, content, callback) { 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) { 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) { CSteamGroup.prototype.scheduleEvent = function(name, type, description, time, server, callback) {

View File

@ -5,49 +5,48 @@ const Helpers = require('../components/helpers.js');
const SteamCommunity = require('../index.js'); const SteamCommunity = require('../index.js');
SteamCommunity.prototype.getSteamUser = function(id, callback) { SteamCommunity.prototype.getSteamUser = function(id, callback) {
if(typeof id !== 'string' && !Helpers.isSteamID(id)) { if (typeof id !== 'string' && !Helpers.isSteamID(id)) {
throw new Error("id parameter should be a user URL string or a SteamID object"); 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)) { 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"); 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', (err, response, body) => {
this.httpRequest("http://steamcommunity.com/" + (typeof id === 'string' ? "id/" + id : "profiles/" + id.toString()) + "/?xml=1", function(err, response, body) {
if (err) { if (err) {
callback(err); callback(err);
return; return;
} }
XML2JS.parseString(body, function(err, result) { XML2JS.parseString(body, function(err, result) {
if(err || (!result.response && !result.profile)) { if (err || (!result.response && !result.profile)) {
callback(err || new Error("No valid response")); callback(err || new Error('No valid response'));
return; 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])); callback(new Error(result.response.error[0]));
return; return;
} }
// Try and find custom URL from redirect // Try and find custom URL from redirect
var customurl = null; let customurl = null;
if(response.request.redirects && response.request.redirects.length) { if (response.request.redirects && response.request.redirects.length) {
var match = response.request.redirects[0].redirectUri.match(/https?:\/\/steamcommunity\.com\/id\/([^/])+\/\?xml=1/); let match = response.request.redirects[0].redirectUri.match(/https?:\/\/steamcommunity\.com\/id\/([^/])+\/\?xml=1/);
if(match) { if (match) {
customurl = match[1]; customurl = match[1];
} }
} }
if(!result.profile.steamID64) { if (!result.profile.steamID64) {
callback(new Error("No valid response")); callback(new Error('No valid response'));
return; return;
} }
callback(null, new CSteamUser(self, result.profile, customurl)); callback(null, new CSteamUser(this, result.profile, customurl));
}); });
}, "steamcommunity"); }, 'steamcommunity');
}; };
function CSteamUser(community, userData, customurl) { function CSteamUser(community, userData, customurl) {
@ -60,7 +59,7 @@ function CSteamUser(community, userData, customurl) {
this.privacyState = processItem('privacyState', 'uncreated'); this.privacyState = processItem('privacyState', 'uncreated');
this.visibilityState = processItem('visibilityState'); this.visibilityState = processItem('visibilityState');
this.avatarHash = processItem('avatarIcon', '').match(/([0-9a-f]+)\.[a-z]+$/); this.avatarHash = processItem('avatarIcon', '').match(/([0-9a-f]+)\.[a-z]+$/);
if(this.avatarHash) { if (this.avatarHash) {
this.avatarHash = this.avatarHash[1]; this.avatarHash = this.avatarHash[1];
} }
@ -69,8 +68,8 @@ function CSteamUser(community, userData, customurl) {
this.isLimitedAccount = processItem('isLimitedAccount') == 1; this.isLimitedAccount = processItem('isLimitedAccount') == 1;
this.customURL = processItem('customURL', customurl); this.customURL = processItem('customURL', customurl);
if(this.visibilityState == 3) { if (this.visibilityState == 3) {
let memberSinceValue = processItem('memberSince', '0').replace(/(\d{1,2})(st|nd|th)/, "$1"); let memberSinceValue = processItem('memberSince', '0').replace(/(\d{1,2})(st|nd|th)/, '$1');
if (memberSinceValue.indexOf(',') === -1) { if (memberSinceValue.indexOf(',') === -1) {
memberSinceValue += ', ' + new Date().getFullYear(); memberSinceValue += ', ' + new Date().getFullYear();
@ -92,11 +91,10 @@ function CSteamUser(community, userData, customurl) {
this.groups = null; this.groups = null;
this.primaryGroup = null; this.primaryGroup = null;
var self = this; if (userData.groups && userData.groups[0] && userData.groups[0].group) {
if(userData.groups && userData.groups[0] && userData.groups[0].group) { this.groups = userData.groups[0].group.map((group) => {
this.groups = userData.groups[0].group.map(function(group) { if (group['$'] && group['$'].isPrimary === '1') {
if(group['$'] && group['$'].isPrimary === "1") { this.primaryGroup = new SteamID(group.groupID64[0]);
self.primaryGroup = new SteamID(group.groupID64[0]);
} }
return new SteamID(group.groupID64[0]); return new SteamID(group.groupID64[0]);
@ -104,7 +102,7 @@ function CSteamUser(community, userData, customurl) {
} }
function processItem(name, defaultVal) { function processItem(name, defaultVal) {
if(!userData[name]) { if (!userData[name]) {
return defaultVal; return defaultVal;
} }
@ -116,13 +114,13 @@ CSteamUser.getAvatarURL = function(hash, size, protocol) {
size = size || ''; size = size || '';
protocol = protocol || 'http://'; 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; let url = protocol + 'steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/' + hash.substring(0, 2) + '/' + hash;
if(size == 'full' || size == 'medium') { if (size == 'full' || size == 'medium') {
return url + "_" + size + ".jpg"; return url + '_' + size + '.jpg';
} else { } else {
return url + ".jpg"; return url + '.jpg';
} }
}; };

View File

@ -143,7 +143,7 @@ SteamCommunity.prototype.getAllGroupAnnouncements = function(gid, time, callback
date: new Date(announcement.pubDate[0]), date: new Date(announcement.pubDate[0]),
author: (typeof announcement.author === 'undefined') ? null : announcement.author[0], author: (typeof announcement.author === 'undefined') ? null : announcement.author[0],
aid: splitLink[splitLink.length - 1] aid: splitLink[splitLink.length - 1]
} };
}).filter(announcement => announcement.date > time); }).filter(announcement => announcement.date > time);
return callback(null, announcements); return callback(null, announcements);
@ -171,7 +171,7 @@ SteamCommunity.prototype.postGroupAnnouncement = function(gid, headline, content
}; };
if (hidden) { if (hidden) {
form.is_hidden = 'is_hidden' form.is_hidden = 'is_hidden';
} }
this.httpRequestPost({ this.httpRequestPost({
@ -251,7 +251,7 @@ SteamCommunity.prototype.scheduleGroupEvent = function(gid, name, type, descript
break; break;
default: default:
if (typeof server != object) { if (typeof server != 'object') {
server = {ip: '', password: ''}; server = {ip: '', password: ''};
} }
} }
@ -314,7 +314,7 @@ SteamCommunity.prototype.editGroupEvent = function(gid, id, name, type, descript
break; break;
default: default:
if (typeof server != object) { if (typeof server != 'object') {
server = {ip: '', password: ''}; server = {ip: '', password: ''};
} }
} }

View File

@ -1,7 +1,5 @@
const SteamCommunity = require('../index.js'); const SteamCommunity = require('../index.js');
const Helpers = require('./helpers.js');
const HELP_SITE_DOMAIN = 'https://help.steampowered.com'; const HELP_SITE_DOMAIN = 'https://help.steampowered.com';
/** /**

View File

@ -38,7 +38,7 @@ exports.decodeSteamTime = function(time) {
/** /**
* Get an Error object for a particular EResult * 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 * @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} * @returns {null|Error}
*/ */
@ -48,7 +48,7 @@ exports.eresultError = function(eresult, message) {
return null; return null;
} }
let err = new Error(message || EResult[eresult] || ("Error " + eresult)); let err = new Error(message || EResult[eresult] || `Error ${eresult}`);
err.eresult = eresult; err.eresult = eresult;
return err; return err;
}; };

View File

@ -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)}); 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); callback(null, body.rgItems);
}) });
}; };
/** /**

View File

@ -1,6 +1,5 @@
const Cheerio = require('cheerio'); const Cheerio = require('cheerio');
const FS = require('fs'); const FS = require('fs');
const SteamID = require('steamid');
const Helpers = require('./helpers.js'); const Helpers = require('./helpers.js');
const SteamCommunity = require('../index.js'); const SteamCommunity = require('../index.js');
@ -12,9 +11,9 @@ SteamCommunity.PrivacyState = {
}; };
const CommentPrivacyState = { const CommentPrivacyState = {
'1': 2, // private 1: 2, // private
'2': 0, // friends only 2: 0, // friends only
'3': 1 // anyone 3: 1 // anyone
}; };
/** /**
@ -80,11 +79,7 @@ SteamCommunity.prototype.editProfile = function(settings, callback) {
}; };
for (let i in settings) { for (let i in settings) {
if(!settings.hasOwnProperty(i)) { switch (i) {
continue;
}
switch(i) {
case 'name': case 'name':
values.personaName = settings[i]; values.personaName = settings[i];
break; break;
@ -193,10 +188,6 @@ SteamCommunity.prototype.profileSettings = function(settings, callback) {
let commentPermission = existingSettings.Privacy.eCommentPermission; let commentPermission = existingSettings.Privacy.eCommentPermission;
for (let i in settings) { for (let i in settings) {
if (!settings.hasOwnProperty(i)) {
continue;
}
switch (i) { switch (i) {
case 'profile': case 'profile':
privacy.PrivacyProfile = settings[i]; privacy.PrivacyProfile = settings[i];
@ -260,7 +251,7 @@ SteamCommunity.prototype.profileSettings = function(settings, callback) {
}; };
SteamCommunity.prototype.uploadAvatar = function(image, format, callback) { SteamCommunity.prototype.uploadAvatar = function(image, format, callback) {
if(typeof format === 'function') { if (typeof format === 'function') {
callback = format; callback = format;
format = null; format = null;
} }
@ -346,7 +337,7 @@ SteamCommunity.prototype.uploadAvatar = function(image, format, callback) {
return; return;
} }
if(!body || !body.success) { if (!body || !body.success) {
callback && callback(new Error('Malformed response')); callback && callback(new Error('Malformed response'));
return; return;
} }
@ -394,7 +385,7 @@ SteamCommunity.prototype.uploadAvatar = function(image, format, callback) {
} }
doUpload(file); doUpload(file);
}) });
} }
}; };

View File

@ -86,7 +86,11 @@ SteamCommunity.prototype.finalizeTwoFactor = function(secret, activationCode, ca
if (body.status == SteamCommunity.EResult.TwoFactorActivationCodeMismatch) { if (body.status == SteamCommunity.EResult.TwoFactorActivationCodeMismatch) {
callback(new Error('Invalid activation code')); callback(new Error('Invalid activation code'));
} else if (body.want_more) { } 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; diff += 30;
finalize(); finalize();
@ -96,7 +100,7 @@ SteamCommunity.prototype.finalizeTwoFactor = function(secret, activationCode, ca
callback(null); callback(null);
} }
}, 'steamcommunity'); }, 'steamcommunity');
} };
SteamTotp.getTimeOffset((err, offset, latency) => { SteamTotp.getTimeOffset((err, offset, latency) => {
if (err) { if (err) {

View File

@ -241,7 +241,7 @@ SteamCommunity.prototype.getUserComments = function(userID, options, callback) {
date: new Date($elem.find('.commentthread_comment_timestamp').data('timestamp') * 1000), date: new Date($elem.find('.commentthread_comment_timestamp').data('timestamp') * 1000),
text: $commentContent.text().trim(), text: $commentContent.text().trim(),
html: $commentContent.html().trim() html: $commentContent.html().trim()
} };
}).get(); }).get();
callback(null, comments, body.total_count); callback(null, comments, body.total_count);
@ -444,25 +444,16 @@ SteamCommunity.prototype.getUserInventory = function(userID, appID, contextID, t
return; return;
} }
let i; for (let i in body.rgInventory) {
for (i in body.rgInventory) {
if (!body.rgInventory.hasOwnProperty(i)) {
continue;
}
inventory.push(new CEconItem(body.rgInventory[i], body.rgDescriptions, contextID)); inventory.push(new CEconItem(body.rgInventory[i], body.rgDescriptions, contextID));
} }
for (i in body.rgCurrency) { for (let i in body.rgCurrency) {
if (!body.rgCurrency.hasOwnProperty(i)) {
continue;
}
currency.push(new CEconItem(body.rgInventory[i], body.rgDescriptions, contextID)); currency.push(new CEconItem(body.rgInventory[i], body.rgDescriptions, contextID));
} }
if (body.more) { if (body.more) {
let match = response.request.uri.href.match(/\/(profiles|id)\/([^\/]+)\//); let match = response.request.uri.href.match(/\/(profiles|id)\/([^/]+)\//);
if (match) { if (match) {
endpoint = `/${match[1]}/${match[2]}`; endpoint = `/${match[1]}/${match[2]}`;
} }

View File

@ -1,47 +1,47 @@
var SteamCommunity = require('../index.js'); let SteamCommunity = require('../index.js');
var ReadLine = require('readline'); let ReadLine = require('readline');
var community = new SteamCommunity(); let community = new SteamCommunity();
var rl = ReadLine.createInterface({ let rl = ReadLine.createInterface({
"input": process.stdin, input: process.stdin,
"output": process.stdout output: process.stdout
}); });
rl.question("Username: ", function(accountName) { rl.question('Username: ', function(accountName) {
rl.question("Password: ", function(password) { rl.question('Password: ', function(password) {
doLogin(accountName, password); doLogin(accountName, password);
}); });
}); });
function doLogin(accountName, password, authCode, twoFactorCode, captcha) { function doLogin(accountName, password, authCode, twoFactorCode, captcha) {
community.login({ community.login({
"accountName": accountName, accountName: accountName,
"password": password, password: password,
"authCode": authCode, authCode: authCode,
"twoFactorCode": twoFactorCode, twoFactorCode: twoFactorCode,
"captcha": captcha captcha: captcha
}, function(err, sessionID, cookies, steamguard) { }, function(err, sessionID, cookies, steamguard) {
if(err) { if (err) {
if(err.message == 'SteamGuardMobile') { if (err.message == 'SteamGuardMobile') {
rl.question("Steam Authenticator Code: ", function(code) { rl.question('Steam Authenticator Code: ', function(code) {
doLogin(accountName, password, null, code); doLogin(accountName, password, null, code);
}); });
return; return;
} }
if(err.message == 'SteamGuard') { if (err.message == 'SteamGuard') {
console.log("An email has been sent to your address at " + err.emaildomain); console.log('An email has been sent to your address at ' + err.emaildomain);
rl.question("Steam Guard Code: ", function(code) { rl.question('Steam Guard Code: ', function(code) {
doLogin(accountName, password, code); doLogin(accountName, password, code);
}); });
return; return;
} }
if(err.message == 'CAPTCHA') { if (err.message == 'CAPTCHA') {
console.log(err.captchaurl); console.log(err.captchaurl);
rl.question("CAPTCHA: ", function(captchaInput) { rl.question('CAPTCHA: ', function(captchaInput) {
doLogin(accountName, password, authCode, twoFactorCode, captchaInput); doLogin(accountName, password, authCode, twoFactorCode, captchaInput);
}); });
@ -53,9 +53,9 @@ function doLogin(accountName, password, authCode, twoFactorCode, captcha) {
return; 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) { community.getSteamGroup(gid, function(err, group) {
if (err) { if (err) {
console.log(err); console.log(err);
@ -64,19 +64,19 @@ function doLogin(accountName, password, authCode, twoFactorCode, captcha) {
group.getAllAnnouncements(function(err, announcements) { group.getAllAnnouncements(function(err, announcements) {
if(announcements.length === 0) { if (announcements.length === 0) {
return console.log("This group has no announcements"); return console.log('This group has no announcements');
} }
for (var i = announcements.length - 1; i >= 0; i--) { 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); 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('Would you like to delete delete or edit an annoucement? (Type edit/delete): ', function(choice) {
rl.question("Annoucement ID: ", function(aid) { rl.question('Annoucement ID: ', function(aid) {
if(choice === 'edit') { if (choice === 'edit') {
rl.question("New title: ", function(header) { rl.question('New title: ', function(header) {
rl.question("New body: ", function(content) { rl.question('New body: ', function(content) {
// EW THE PYRAMID! // EW THE PYRAMID!
// Try replace this with delete! // Try replace this with delete!
editAnnouncement(group, aid, header, content); editAnnouncement(group, aid, header, content);
@ -96,10 +96,10 @@ function doLogin(accountName, password, authCode, twoFactorCode, captcha) {
function editAnnouncement(group, aid, header, content) { function editAnnouncement(group, aid, header, content) {
// Actual community method. // Actual community method.
group.editAnnouncement(aid, header, content, function(error) { group.editAnnouncement(aid, header, content, function(error) {
if(!error) { if (!error) {
console.log("Annoucement edited!"); console.log('Annoucement edited!');
} else { } else {
console.log("Unable to edit annoucement! %j", error); console.log('Unable to edit annoucement! %j', error);
process.exit(1); process.exit(1);
} }
}); });
@ -109,10 +109,10 @@ function deleteAnnouncement(group, aid) {
// group.deleteAnnouncement(aid); // group.deleteAnnouncement(aid);
// Or // Or
group.deleteAnnouncement(aid, function(err) { group.deleteAnnouncement(aid, function(err) {
if(!err) { if (!err) {
console.log("Deleted"); console.log('Deleted');
} else { } else {
console.log("Error deleting announcement."); console.log('Error deleting announcement.');
} }
}) });
} }

128
index.js
View File

@ -68,10 +68,8 @@ SteamCommunity.prototype.login = function(details, callback) {
let disableMobile = details.disableMobile; let disableMobile = details.disableMobile;
let self = this;
// Delete the cache // 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 // headers required to convince steam that we're logging in from a mobile device so that we can get the oAuth data
let mobileHeaders = {}; let mobileHeaders = {};
@ -89,11 +87,21 @@ SteamCommunity.prototype.login = function(details, callback) {
mobileHeaders = {Referer: 'https://steamcommunity.com/login'}; 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/', { this.httpRequestPost('https://steamcommunity.com/login/getrsakey/', {
form: {username: details.accountName}, form: {username: details.accountName},
headers: mobileHeaders, headers: mobileHeaders,
json: true json: true
}, function(err, response, body) { }, (err, response, body) => {
// Remove the mobile cookies // Remove the mobile cookies
if (err) { if (err) {
deleteMobileCookies(); deleteMobileCookies();
@ -112,7 +120,7 @@ SteamCommunity.prototype.login = function(details, callback) {
let formObj = { let formObj = {
captcha_text: details.captcha || '', captcha_text: details.captcha || '',
captchagid: self._captchaGid, captchagid: this._captchaGid,
emailauth: details.authCode || '', emailauth: details.authCode || '',
emailsteamid: '', emailsteamid: '',
password: hex2b64(key.encrypt(details.password)), password: hex2b64(key.encrypt(details.password)),
@ -130,12 +138,12 @@ SteamCommunity.prototype.login = function(details, callback) {
formObj.loginfriendlyname = '#login_emailauth_friendlyname_mobile'; formObj.loginfriendlyname = '#login_emailauth_friendlyname_mobile';
} }
self.httpRequestPost({ this.httpRequestPost({
uri: 'https://steamcommunity.com/login/dologin/', uri: 'https://steamcommunity.com/login/dologin/',
json: true, json: true,
form: formObj, form: formObj,
headers: mobileHeaders headers: mobileHeaders
}, function(err, response, body) { }, (err, response, body) => {
deleteMobileCookies(); deleteMobileCookies();
if (err) { if (err) {
@ -157,7 +165,7 @@ SteamCommunity.prototype.login = function(details, callback) {
error = new Error('CAPTCHA'); error = new Error('CAPTCHA');
error.captchaurl = 'https://steamcommunity.com/login/rendercaptcha/?gid=' + body.captcha_gid; error.captchaurl = 'https://steamcommunity.com/login/rendercaptcha/?gid=' + body.captcha_gid;
self._captchaGid = body.captcha_gid; this._captchaGid = body.captcha_gid;
callback(error); callback(error);
} else if (!body.success) { } else if (!body.success) {
@ -167,68 +175,53 @@ SteamCommunity.prototype.login = function(details, callback) {
} else { } else {
let sessionID = generateSessionID(); let sessionID = generateSessionID();
let oAuth; 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) { let cookies = this._jar.getCookieString('https://steamcommunity.com').split(';').map(cookie => cookie.trim());
return cookie.trim();
});
if (!disableMobile){ if (!disableMobile){
oAuth = JSON.parse(body.oauth); oAuth = JSON.parse(body.oauth);
self.steamID = new SteamID(oAuth.steamid); this.steamID = new SteamID(oAuth.steamid);
self.oAuthToken = oAuth.oauth_token; this.oAuthToken = oAuth.oauth_token;
} else { } else {
for (let i = 0; i < cookies.length; i++) { for (let i = 0; i < cookies.length; i++) {
let parts = cookies[i].split('='); let parts = cookies[i].split('=');
if (parts[0] == 'steamLogin') { if (parts[0] == 'steamLogin') {
self.steamID = new SteamID(decodeURIComponent(parts[1]).split('||')[0]); this.steamID = new SteamID(decodeURIComponent(parts[1]).split('||')[0]);
break; break;
} }
} }
self.oAuthToken = null; this.oAuthToken = null;
} }
// Find the Steam Guard cookie // Find the Steam Guard cookie
let steamguard = null; let steamguard = null;
for (let i = 0; i < cookies.length; i++) { for (let i = 0; i < cookies.length; i++) {
let parts = cookies[i].split('='); let parts = cookies[i].split('=');
if (parts[0] == 'steamMachineAuth' + self.steamID) { if (parts[0] == 'steamMachineAuth' + this.steamID) {
steamguard = self.steamID.toString() + '||' + decodeURIComponent(parts[1]); steamguard = this.steamID.toString() + '||' + decodeURIComponent(parts[1]);
break; break;
} }
} }
self.setCookies(cookies); this.setCookies(cookies);
callback(null, sessionID, cookies, steamguard, disableMobile ? null : oAuth.oauth_token); callback(null, sessionID, cookies, steamguard, disableMobile ? null : oAuth.oauth_token);
} }
}, 'steamcommunity'); }, 'steamcommunity');
}, '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) { SteamCommunity.prototype.oAuthLogin = function(steamguard, token, callback) {
steamguard = steamguard.split('||'); steamguard = steamguard.split('||');
let steamID = new SteamID(steamguard[0]); let steamID = new SteamID(steamguard[0]);
let self = this;
this.httpRequestPost({ this.httpRequestPost({
uri: 'https://api.steampowered.com/IMobileAuthService/GetWGToken/v1/', uri: 'https://api.steampowered.com/IMobileAuthService/GetWGToken/v1/',
form: { form: {access_token: token},
access_token: token
},
json: true json: true
}, function(err, response, body) { }, (err, response, body) => {
if (err) { if (err) {
callback(err); callback(err);
return; return;
@ -243,11 +236,11 @@ SteamCommunity.prototype.oAuthLogin = function(steamguard, token, callback) {
'steamLogin=' + encodeURIComponent(steamID.getSteamID64() + '||' + body.response.token), 'steamLogin=' + encodeURIComponent(steamID.getSteamID64() + '||' + body.response.token),
'steamLoginSecure=' + encodeURIComponent(steamID.getSteamID64() + '||' + body.response.token_secure), 'steamLoginSecure=' + encodeURIComponent(steamID.getSteamID64() + '||' + body.response.token_secure),
'steamMachineAuth' + steamID.getSteamID64() + '=' + steamguard[1], 'steamMachineAuth' + steamID.getSteamID64() + '=' + steamguard[1],
'sessionid=' + self.getSessionID() 'sessionid=' + this.getSessionID()
]; ];
self.setCookies(cookies); this.setCookies(cookies);
callback(null, self.getSessionID(), cookies); callback(null, this.getSessionID(), cookies);
}, 'steamcommunity'); }, 'steamcommunity');
}; };
@ -324,8 +317,7 @@ function generateSessionID() {
} }
SteamCommunity.prototype.parentalUnlock = function(pin, callback) { SteamCommunity.prototype.parentalUnlock = function(pin, callback) {
let self = this; let sessionID = this.getSessionID();
let sessionID = self.getSessionID();
this.httpRequestPost('https://steamcommunity.com/parental/ajaxunlock', { this.httpRequestPost('https://steamcommunity.com/parental/ajaxunlock', {
json: true, json: true,
@ -333,7 +325,7 @@ SteamCommunity.prototype.parentalUnlock = function(pin, callback) {
pin: pin, pin: pin,
sessionid: sessionID sessionid: sessionID
} }
}, function(err, response, body) { }, (err, response, body) => {
if (!callback) { if (!callback) {
return; return;
} }
@ -366,7 +358,7 @@ SteamCommunity.prototype.parentalUnlock = function(pin, callback) {
} }
callback(); callback();
}.bind(this), 'steamcommunity'); }, 'steamcommunity');
}; };
SteamCommunity.prototype.getNotifications = function(callback) { SteamCommunity.prototype.getNotifications = function(callback) {
@ -493,33 +485,7 @@ SteamCommunity.prototype.clearPersonaNameHistory = function(callback) {
}; };
SteamCommunity.prototype._myProfile = function(endpoint, form, callback) { SteamCommunity.prototype._myProfile = function(endpoint, form, callback) {
let self = this; const completeRequest = (url) => {
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) {
let options = endpoint.endpoint ? endpoint : {}; let options = endpoint.endpoint ? endpoint : {};
options.uri = 'https://steamcommunity.com' + url + '/' + (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'; 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');
} }
}; };