diff --git a/components/helpers.js b/components/helpers.js index 1da5443..b354da5 100644 --- a/components/helpers.js +++ b/components/helpers.js @@ -1,4 +1,6 @@ const EResult = require('../resources/EResult.js'); +const request = require('request'); +const xml2js = require('xml2js'); exports.isSteamID = function(input) { var keys = Object.keys(input); @@ -54,3 +56,41 @@ exports.eresultError = function(eresult) { err.eresult = eresult; return err; }; + +/** + * Resolves a Steam profile URL to get steamID64 and vanityURL + * @param {String} url - Full steamcommunity profile URL or only the vanity part. + * @param {Object} callback - First argument is null/Error, second is object containing vanityURL (String) and steamID (String) + */ +exports.resolveVanityURL = function(url, callback) { + // Precede url param if only the vanity was provided + if (!url.includes("steamcommunity.com")) { + url = "https://steamcommunity.com/id/" + url; + } + + // Make request to get XML data + request(url + "/?xml=1", function(err, response, body) { + if (err) { + callback(err); + return; + } + + // Parse XML data returned from Steam into an object + new xml2js.Parser().parseString(body, (err, parsed) => { + if (err) { + callback(new Error("Couldn't parse XML response")); + return; + } + + if (parsed.response && parsed.response.error) { + callback(new Error("Couldn't find Steam ID")); + return; + } + + let steamID64 = parsed.profile.steamID64; + let vanityURL = parsed.profile.customURL; + + callback(null, {"vanityURL": vanityURL, "steamID": steamID64}); + }); + }); +}; \ No newline at end of file diff --git a/components/inventoryhistory.js b/components/inventoryhistory.js index fd7c522..961d9c1 100644 --- a/components/inventoryhistory.js +++ b/components/inventoryhistory.js @@ -1,5 +1,6 @@ var SteamCommunity = require('../index.js'); var CEconItem = require('../classes/CEconItem.js'); +var Helpers = require('./helpers.js'); var SteamID = require('steamid'); var request = require('request'); var Cheerio = require('cheerio'); @@ -142,7 +143,7 @@ SteamCommunity.prototype.getInventoryHistory = function(options, callback) { } if (options.resolveVanityURLs) { - Async.map(vanityURLs, resolveVanityURL, function(err, results) { + Async.map(vanityURLs, Helpers.resolveVanityURL, function(err, results) { if (err) { callback(err); return; @@ -170,19 +171,3 @@ SteamCommunity.prototype.getInventoryHistory = function(options, callback) { }, "steamcommunity"); }; -function resolveVanityURL(vanityURL, callback) { - request("https://steamcommunity.com/id/" + vanityURL + "/?xml=1", function(err, response, body) { - if (err) { - callback(err); - return; - } - - var match = body.match(/(\d+)<\/steamID64>/); - if (!match || !match[1]) { - callback(new Error("Couldn't find Steam ID")); - return; - } - - callback(null, {"vanityURL": vanityURL, "steamID": match[1]}); - }); -}