Compare commits

...

137 Commits

Author SHA1 Message Date
Alexander Corn
d91e74d02a 3.30.0 2016-12-13 01:53:57 -05:00
Alexander Corn
d120d09970 Fixed tag data to be identical to old endpoint 2016-12-13 01:53:30 -05:00
Alexander Corn
84ce979a78 Fixed new inventory loading not working properly 2016-12-13 01:52:52 -05:00
Alexander Corn
88b0495386 Renamed getUserInventory, added back old one and marked it as deprecated 2016-12-13 01:32:17 -05:00
Alexander Corn
d367e8eae4 Added better paging controls for new inventory endpoint 2016-12-13 01:29:06 -05:00
Alexander Corn
9a3cf927c0 Fixed some more currency detection 2016-12-13 01:28:48 -05:00
Alexander Corn
56cdfff672 3.29.1 2016-12-13 01:07:12 -05:00
Alexander Corn
35e6dd16e7 Re-add "pos" property to inventory items for backwards compatibility 2016-12-13 01:07:00 -05:00
Alexander Corn
d0af8584c1 Send referer when fetching inventories 2016-12-13 00:50:29 -05:00
Alexander Corn
f1afcd1962 3.29.0 2016-12-13 00:46:23 -05:00
Alexander Corn
513b0bff1c Added some optimizations and backwards-compatibility for inv fetching 2016-12-13 00:46:02 -05:00
Alexander Corn
ab037b1931 Pass response body back to caller for inventory fetching 2016-12-13 00:45:38 -05:00
Alexander Corn
06df0ecd42 Handle currencies with new endpoint's data in CEconItem 2016-12-13 00:45:23 -05:00
João Silva
b789e13a70 Update inventory loading endpoint (#148)
* Update inventory loading endpoint

Should fix 429s :)

* Fix missing contextID parameter at CEconItem class

* Revert "Fix missing contextID parameter at CEconItem class"

This reverts commit 416321105b.

* Revert "Revert "Fix missing contextID parameter at CEconItem class""

This reverts commit 49ecd46954.

* Update #1
2016-12-13 00:23:02 -05:00
Alexander Corn
95a36b00c1 Remember time offset for purposes of acceptConfirmationForObject
Closes #147
2016-12-08 17:57:01 -05:00
Alexander Corn
41c87501c4 3.28.0 2016-10-28 19:24:05 -04:00
Alexander Corn
4f3ddcc787 Merge pull request #134 from Aareksio/confirmations
Emit `confirmationAccepted` after accepting the confirmation using `confirmationChecker`
2016-10-27 17:07:41 -04:00
Arkadiusz Sygulski
d10fa9983d Emit confirmationAccepted after accepting the confirmation 2016-10-27 22:30:58 +02:00
Arkadiusz Sygulski
666226731e Remove unused function: handleNewConfirmation 2016-10-27 22:18:31 +02:00
Alexander Corn
d096f47cac 3.27.2 2016-10-10 00:55:36 -04:00
Alexander Corn
a8eedb3067 Make it possible to skip json error check 2016-10-10 00:55:19 -04:00
Alexander Corn
ed12a54e81 3.27.1 2016-10-04 09:16:08 -04:00
Alexander Corn
eb341314ef Merge pull request #130 from Pavelas/master
Delete the profile URL cache after log in.
2016-10-04 09:15:03 -04:00
Pavelas
33cd9474ab Delete the profile URL cache after log in. 2016-10-04 10:26:20 +02:00
Alexander Corn
e8a43734be 3.27.0 2016-09-16 19:30:32 -04:00
Alexander Corn
8a27147f5c Added accountAlerts to getNotifications 2016-09-16 19:30:19 -04:00
Alexander Corn
d00d07f828 Added acceptConfirmationForObject convenience method 2016-09-16 19:03:49 -04:00
Alexander Corn
471c11d406 Merge pull request #128 from SzymonLisowiec/patch-1
Problem when search "Key:" in polish language.
2016-09-16 18:21:17 -04:00
Alexander Corn
dd3a9254aa 3.26.1 2016-09-12 11:22:29 -04:00
Alexander Corn
71a3893636 Fixed cookies not being set for non-community domains after logging in
Also fixed secure flag not working for cookies
2016-09-12 11:22:18 -04:00
Alexander Corn
5928c3b76a 3.26.0 2016-09-12 01:33:30 -04:00
Alexander Corn
1b60712b8b Updated getNotifications to use the new JSON endpoint 2016-09-12 01:33:11 -04:00
Alexander Corn
335a955abd Fixed cookies not being set 2016-09-12 01:24:39 -04:00
Alexander Corn
6d534df8ba Set cookies on all Steam domains, and properly flag as secure 2016-09-12 01:17:00 -04:00
Alexander Corn
9022a9a45e 3.25.0 2016-09-08 19:45:05 -04:00
Alexander Corn
ce4d7ae026 Pull trade offer ID directly from listing page 2016-09-08 19:23:15 -04:00
Kysune
b863377c87 Problem when search "Key:" in polish language. 2016-09-01 21:05:46 +02:00
Alexander Corn
20785ee92b 3.24.0 2016-08-31 22:20:49 -04:00
Alexander Corn
3afb393f58 Updated getInventoryHistory for new pagination scheme 2016-08-31 22:20:36 -04:00
Alexander Corn
79543187f0 Fixed timezones being incorrect in trade history entries 2016-08-31 22:20:24 -04:00
Alexander Corn
3139aec463 Reformat inventoryhistory.js 2016-08-31 21:48:17 -04:00
Alexander Corn
bb917af86e 3.23.3 2016-08-10 18:55:36 -04:00
Alexander Corn
17f51b9caa Fixed double callbacks on some json errors (fixes #123) 2016-08-10 18:55:23 -04:00
Alexander Corn
dd638df118 3.23.2 2016-08-09 15:45:32 -04:00
Alexander Corn
b937a05442 Make sure we actually get json back when we want it (fixes #122) 2016-08-09 15:45:21 -04:00
Alexander Corn
9c34d18cd9 3.23.1 2016-08-07 00:04:56 -04:00
Alexander Corn
02e3798124 Handle some cases where the session expires while we're using webchat 2016-08-07 00:04:30 -04:00
Alexander Corn
5d9922cc33 3.23.0 2016-07-13 13:12:39 -04:00
Alexander Corn
153011e1c9 Make _community non-enumerable on CConfirmation 2016-07-13 13:11:56 -04:00
Alexander Corn
575c196cb7 Added acceptAllConfirmations method 2016-07-13 13:11:44 -04:00
Alexander Corn
47a24d19cf Added ability to act on multiple confirmations 2016-07-13 13:11:36 -04:00
Alexander Corn
0eac19b71c 3.22.0 2016-07-10 01:02:48 -04:00
Alexander Corn
ca73ecc786 Parse times in getUserAliases into Date objects 2016-07-10 01:02:36 -04:00
Alexander Corn
e8733613d7 Merge pull request #117 from andrewda/master
Add ability to get user aliases
2016-07-10 00:52:13 -04:00
Andrew Dassonville
89a1df67ec Add ability to get user aliases 2016-07-06 16:20:42 -07:00
Alexander Corn
3ba0a8592e 3.21.2 2016-07-01 18:30:32 -04:00
Alexander Corn
57fa7a679f Fixed market search results including query string (fixes #113) 2016-07-01 18:29:56 -04:00
Alexander Corn
446e315183 Fixed market search result prices being horribly wrong 2016-07-01 18:27:39 -04:00
Alexander Corn
c6a9b74471 3.21.1 2016-06-29 23:08:54 -04:00
Alexander Corn
018e18cb5d Give "Family View Restricted" error if access denied due to Family View 2016-06-29 23:08:40 -04:00
Alexander Corn
303ce10e73 3.21.0 2016-06-27 16:57:12 -04:00
Alexander Corn
60e0e63a92 Fixed marketSearch (fixes #112) 2016-06-27 16:56:16 -04:00
Luke
17e5b94782 Added deleting events in CSteamGroup (#109)
* Added deleteEvent()

* Added deleteGroupEvent()
2016-06-21 22:39:23 -04:00
Alexander Corn
beaf012846 3.20.0 2016-06-15 15:07:45 -04:00
Alexander Corn
38c20a342c Merge pull request #105 from luop90/master
Added editing events to CSteamGroup
2016-06-15 14:17:41 -04:00
Luke
a406cfbfe2 Fixed a valid server object being overwritten 2016-06-15 11:25:44 -06:00
Luke Henke
c970eee9d3 Added editing events to CSteamGroup 2016-06-14 20:29:11 -06:00
Alexander Corn
38e3eefb33 3.19.10 2016-06-14 16:08:03 -04:00
Alexander Corn
a2e26459d9 Emit chatLogOnFailed on error, and handle fatal errors (fixes #104) 2016-06-14 16:07:46 -04:00
Alexander Corn
c1b04ee743 Fixed crash if chat poll returns no response
https://dev.doctormckay.com/topic/383-error-in-node-steamcommunity/
2016-06-14 16:02:04 -04:00
Alexander Corn
542eb8d47e 3.19.9 2016-06-03 20:11:56 -04:00
Alexander Corn
9081528f72 Fixed "Error: Error:" in trade errors 2016-06-03 20:10:33 -04:00
Alexander Corn
8be8e395b6 3.19.8 2016-05-05 16:12:35 -04:00
Alexander Corn
4b7ea80fcf Fixed profile URL cache always being deleted when editing profile 2016-05-05 16:12:27 -04:00
Alexander Corn
7f945afbca 3.19.7 2016-05-05 16:00:38 -04:00
Alexander Corn
3b241ba24f Cache profile URL so we don't need to request it all the time 2016-05-05 16:00:28 -04:00
Alexander Corn
fddd74cf24 Fixed crash if response to login is malformed 2016-04-04 21:42:46 -04:00
Alexander Corn
9a3138aa35 3.19.6 2016-04-02 16:15:35 -04:00
Alexander Corn
839d8b51e3 Automatically handle time offset when enabling 2FA (fixes #98) 2016-04-02 16:14:34 -04:00
Alexander Corn
ddf0221489 Added disable_twofactor example 2016-04-02 16:14:17 -04:00
Alexander Corn
64aaca66be 3.19.5 2016-03-31 14:34:27 -04:00
Alexander Corn
aac26212d7 Fixed sessionExpired event always being emitted for confirmation errors 2016-03-23 19:03:55 -04:00
Alexander Corn
d8d99a804f 3.19.4 2016-03-23 14:33:28 -04:00
Alexander Corn
f47afae1ea Pin cheerio version to 0.19.0
https://github.com/DoctorMcKay/node-steam-tradeoffer-manager/issues/120#issuecomment-200179648
2016-03-23 14:33:08 -04:00
Alexander Corn
8d90aac203 Use SteamID v1.0.0 2016-03-22 01:20:02 -04:00
Alexander Corn
f1bfd8b3af 3.19.3 2016-03-18 23:33:41 -04:00
Alexander Corn
579fc04c1c Prompt for CAPTCHA input in examples if needed (fixes #88) 2016-03-18 23:33:30 -04:00
Alexander Corn
58927dc937 Fixed fake error when removing 2FA (fixes #96) 2016-03-18 23:29:17 -04:00
Alexander Corn
018cacac59 Added CONTRIBUTING.md 2016-03-15 15:06:08 -04:00
Alexander Corn
26effb27fe 3.19.2 2016-03-14 21:39:55 -04:00
Alexander Corn
5880e922ab Fixed crashes when checking non-string HTTP responses (fixes #94) 2016-03-14 21:39:45 -04:00
Alexander Corn
fe007811a5 Bumped cheerio version 2016-03-08 01:56:31 -05:00
Alexander Corn
7b882c8439 Updated readme 2016-03-08 01:53:45 -05:00
Alexander Corn
6c4cb9e62f 3.19.1 2016-03-08 01:37:29 -05:00
Alexander Corn
2300081d43 Only fire the callback for blocked requests if one was provided 2016-03-08 01:37:20 -05:00
Alexander Corn
0f20f918be 3.19.0 2016-03-08 01:23:46 -05:00
Alexander Corn
b761b8108b Check properties instead of SteamID proto (fixes #90) 2016-03-08 01:23:31 -05:00
Alexander Corn
46e16cc0b6 Fixed loggedIn method 2016-03-07 01:32:27 -05:00
Alexander Corn
237d3786a2 Properly handle steammobile: protocol error meaning we're not logged in 2016-03-07 01:32:20 -05:00
Alexander Corn
1884ceb7d9 Emit sessionExpired when we detect that we aren't logged in 2016-03-07 01:32:02 -05:00
Alexander Corn
893c4df06b 3.19.0-beta6 2016-03-05 19:38:44 -05:00
Alexander Corn
593ed6b9ef Detect when we aren't logged in and should be 2016-03-05 18:58:39 -05:00
Alexander Corn
840e9548ed 3.19.0-beta5 2016-03-05 00:40:56 -05:00
Alexander Corn
dee6b7964b Fixed crash under specific conditions 2016-03-05 00:40:45 -05:00
Alexander Corn
2fc434d475 3.19.0-beta4 2016-03-05 00:27:13 -05:00
Alexander Corn
42ebbda00d Fixed typo 2016-03-05 00:27:04 -05:00
Alexander Corn
eed791acbd Added ability to delay HTTP requests 2016-03-05 00:14:36 -05:00
Alexander Corn
54b83016af 3.19.0-beta3 2016-03-05 00:01:47 -05:00
Alexander Corn
1032b1f832 Removed now-unnecessary _checkHttpError and _checkCommunityError calls 2016-03-04 23:59:49 -05:00
Alexander Corn
fce2560abe Handle calls to httpRequest with URI and no options 2016-03-04 23:50:49 -05:00
Alexander Corn
0069bb36ef 3.19.0-beta2 2016-03-04 19:36:42 -05:00
Alexander Corn
1028c4193f Added HTTP source 2016-03-04 19:35:04 -05:00
Alexander Corn
991b11e0f4 3.19.0-beta1 2016-03-04 18:51:39 -05:00
Alexander Corn
72c01468da Want node v4.0.0 or later 2016-03-04 18:27:50 -05:00
Alexander Corn
eecd682033 Added unified interface for HTTP requests with pre/post hooks 2016-03-04 18:26:47 -05:00
Alexander Corn
574a3127cb 3.18.7 2016-03-04 00:19:31 -05:00
Alexander Corn
55027f7b1f Merge pull request #87 from andrewda/patch-1
Fixed crash when handling an inventory issue
2016-03-04 00:18:17 -05:00
Andrew Dassonville
70ffc5559d Renamed body.error to body.Error 2016-03-03 19:22:05 -08:00
Andrew Dassonville
f4be134f71 Fixed crash when handling an inventory issue
```
/bots/node_modules/steamcommunity/components/users.js:265
                                callback(new Error(body.Error || "Malformed response"));
                                                       ^

TypeError: Cannot read property 'Error' of undefined
    at Request._callback (/bots/node_modules/steamcommunity/components/users.js:265:28)
    at Request.self.callback (/bots/node_modules/steamcommunity/node_modules/request/request.js:199:22)
    at emitTwo (events.js:100:13)
    at Request.emit (events.js:185:7)
    at Request.<anonymous> (/bots/node_modules/steamcommunity/node_modules/request/request.js:1036:10)
    at emitOne (events.js:95:20)
    at Request.emit (events.js:182:7)
    at IncomingMessage.<anonymous> (/bots/node_modules/steamcommunity/node_modules/request/request.js:963:12)
    at emitNone (events.js:85:20)
    at IncomingMessage.emit (events.js:179:7)
```
2016-03-03 13:42:05 -08:00
Alexander Corn
7792969cae Merge pull request #54 from Mikxail/bugfix-market-item-price
bugfix market-item price
2016-02-29 16:44:17 -05:00
Alexander Corn
57a3532860 3.18.6 2016-02-29 16:42:00 -05:00
Alexander Corn
facf335f0e Fixed captcha overriding more important errors (fixes #56) 2016-02-29 16:41:37 -05:00
Alexander Corn
1c3817b797 Fixed captcha URL (fixes #83) 2016-02-29 16:24:29 -05:00
Alexander Corn
74efd50f72 Added more informative error messages for RSA key retrieval failure 2016-02-06 23:48:26 -05:00
Alexander Corn
87e3665b01 Revised JSDoc language (#80) 2016-02-04 21:49:54 -05:00
Alexander Corn
0b94419de4 Merge pull request #76 from Aareksio/patch-1
Fix for issue #75
2016-01-25 11:47:34 -05:00
Arkadiusz Sygulski
defbd347cc Fix for issue #75
In received XML there's `isPrimary="0"`, which mostly likely causes the problem, which results the last group in xml to be set as primary. 
This should fix it.
2016-01-25 11:35:22 +01:00
Alexander Corn
7efc1f2fd0 3.18.5 2016-01-21 01:15:00 -05:00
Alexander Corn
05c2da89da Fixed crash when unable to check confirmations 2016-01-21 01:14:52 -05:00
Alexander Corn
b83c40419c 3.18.4 2016-01-20 23:05:07 -05:00
Alexander Corn
fb0097499d Added some more debug output to confirmation checker 2016-01-20 23:04:54 -05:00
Alexander Corn
c2983e3bcd RIP market and trade confirmation opt-out 2016-01-20 13:47:14 -05:00
Alexander Corn
80b3cc52d2 3.18.3 2016-01-19 11:30:02 -05:00
Alexander Corn
fa59b188a5 Use the standard device ID when enabling 2FA 2016-01-19 11:29:26 -05:00
mikxail
26f27e2698 remove unused price calculating block
and fix lowestPrice value
2016-01-05 21:58:49 +03:00
Mikhail Konovalov
eae78aab93 remove options argument for updatePrice method 2015-12-28 15:58:31 +03:00
Mikhail Konovalov
5c2894a7d4 bugfix market-item price
and add currency option for .getMarketItem(appid, hashName, currency, cb)
2015-12-27 16:51:11 +03:00
24 changed files with 1332 additions and 595 deletions

35
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,35 @@
# Contributing to SteamCommunity
Thanks for your interest in making `SteamCommunity` better! I'd appreciate it if you read over this document quickly
before you submit your issue or pull request. It'll make things go much smoother.
# Issues
Submitting an issue?
- If you're **reporting a bug**, please include all relevant details.
- A descriptive title helps for one. Titles of just "Error" or "It doesn't work" really don't help.
- Please describe what you're trying to do, what actually happens, and what you can do to reproduce the problem.
- If you have an error message or a crash, please include the full text of the error message and the stack trace.
- Include the relevant snippet of your code. Wrap it in \`\`\`js /* code */ \`\`\` and GitHub [will format it nicely for you](https://help.github.com/articles/github-flavored-markdown/#syntax-highlighting).
- If you're **requesting a feature**, please be descriptive and understanding.
- A good title makes a difference. Please briefly describe what you're requesting in the title.
- Be descriptive in the issue body, too. Say what you want to do, and ideally what the method should be named.
- Be understanding if I don't think that your feature request falls within the scope of this module.
- If you're **asking a question** or **requesting support**, please don't submit a GitHub issue.
- Issues are only for problems directly relating to the module's code.
- Please [post a thread in the dedicated forum](https://dev.doctormckay.com/forum/8-node-steamcommunity/) instead.
# Pull Requests
Submitting a pull request? Great! Thanks for contributing your time and code! Please keep the following in mind.
- Please follow the existing code style.
- Tabs for indentation
- camelCase for variables and functions
- Opening braces on the same line as the if/for/while statement
- etc.
- Please avoid breaking changes. If you make a breaking change that can be done in a backwards-compatible manner, I won't accept it.
- Please don't increment the version number in `package.json`. I'll do that myself when I publish it to npm.
- Please include a brief description of your change in the pull request if it's not immediately apparent from the code.
- Be understanding if I don't think that your change falls within the scope of this module.

View File

@@ -9,12 +9,15 @@ This module provides an easy interface for the Steam Community website. This mod
It supports Steam Guard and CAPTCHAs.
# Installation
Install it from npm:
$ npm install steamcommunity
**Have a question about the module or coding in general? *Do not create a GitHub issue.* GitHub issues are for feature
requests and bug reports. Instead, post in the [dedicated forum](https://dev.doctormckay.com/forum/8-node-steamcommunity/).
Such issues may be ignored!**
# Documentation
As of version 1.0.0, documentation is on the [GitHub wiki](https://github.com/DoctorMcKay/node-steamcommunity/wiki).
Documentation is available on the [GitHub wiki](https://github.com/DoctorMcKay/node-steamcommunity/wiki).
# Support
Report bugs on the [issue tracker](https://github.com/DoctorMcKay/node-steamcommunity/issues) or ask questions
on the [dedicated forum](https://dev.doctormckay.com/forum/8-node-steamcommunity/).

View File

@@ -1,17 +1,32 @@
var SteamCommunity = require('../index.js');
module.exports = CConfirmation;
function CConfirmation(community, data) {
this._community = community;
Object.defineProperty(this, "_community", {"value": community});
this.id = data.id;
this.type = data.type;
this.creator = data.creator;
this.key = data.key;
this.title = data.title;
this.receiving = data.receiving;
this.time = data.time;
this.icon = data.icon;
this.offerID = this.type == SteamCommunity.ConfirmationType.Trade ? this.creator : null;
}
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"));
return;
}
callback(null, this.creator);
return;
}
this._community.getConfirmationOfferID(this.id, time, key, callback);
};

View File

@@ -1,31 +1,40 @@
module.exports = CEconItem;
function CEconItem(item, descriptions, contextID) {
function CEconItem(item, description, contextID) {
var thing;
for(thing in item) {
if(item.hasOwnProperty(thing)) {
for (thing in item) {
if (item.hasOwnProperty(thing)) {
this[thing] = item[thing];
}
}
this.assetid = this.id = (this.id || this.assetid);
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
if (isCurrency) {
this.currencyid = this.id = (this.id || this.currencyid);
} else {
this.assetid = this.id = (this.id || this.assetid);
}
this.instanceid = this.instanceid || '0';
this.amount = parseInt(this.amount, 10);
this.contextid = this.contextid || contextID.toString();
// Merge the description
if(descriptions) {
var description = descriptions[this.classid + '_' + this.instanceid];
if(description) {
for(thing in description) {
if(description.hasOwnProperty(thing)) {
this[thing] = description[thing];
}
if (description) {
// Is this a listing of descriptions?
if (description[this.classid + '_' + this.instanceid]) {
description = description[this.classid + '_' + this.instanceid];
}
for (thing in description) {
if (description.hasOwnProperty(thing)) {
this[thing] = description[thing];
}
}
}
this.is_currency = !!this.is_currency;
this.is_currency = isCurrency;
this.tradable = !!this.tradable;
this.marketable = !!this.marketable;
this.commodity = !!this.commodity;
@@ -34,9 +43,28 @@ function CEconItem(item, descriptions, contextID) {
this.fraudwarnings = this.fraudwarnings || [];
this.descriptions = this.descriptions || [];
if(this.owner && JSON.stringify(this.owner) == '{}') {
if (this.owner && JSON.stringify(this.owner) == '{}') {
this.owner = null;
}
// Restore old property names of tags
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
};
});
}
if (this.actions === "") {
this.actions = [];
}
delete this.currency;
}
CEconItem.prototype.getImageURL = function() {
@@ -52,12 +80,12 @@ CEconItem.prototype.getLargeImageURL = function() {
};
CEconItem.prototype.getTag = function(category) {
if(!this.tags) {
if (!this.tags) {
return null;
}
for(var i = 0; i < this.tags.length; i++) {
if(this.tags[i].category == category) {
for (var i = 0; i < this.tags.length; i++) {
if (this.tags[i].category == category) {
return this.tags[i];
}
}

View File

@@ -1,10 +1,15 @@
var SteamCommunity = require('../index.js');
var Cheerio = require('cheerio');
SteamCommunity.prototype.getMarketItem = function(appid, hashName, callback) {
SteamCommunity.prototype.getMarketItem = function(appid, hashName, currency, callback) {
if (typeof currency == "function") {
callback = currency;
currency = 1;
}
var self = this;
this.request("https://steamcommunity.com/market/listings/" + appid + "/" + encodeURIComponent(hashName), function(err, response, body) {
if(self._checkHttpError(err, response, callback)) {
this.httpRequest("https://steamcommunity.com/market/listings/" + appid + "/" + encodeURIComponent(hashName), function(err, response, body) {
if (err) {
callback(err);
return;
}
@@ -13,23 +18,21 @@ SteamCommunity.prototype.getMarketItem = function(appid, hashName, callback) {
callback(new Error("There are no listings for this item."));
return;
}
var item = new CMarketItem(self, body, $);
if(item.commodity) {
item.updatePrice(function(err) {
if(err) {
callback(err);
} else {
callback(null, item);
}
});
} else {
callback(null, item);
}
});
var item = new CMarketItem(appid, hashName, self, body, $);
item.updatePrice(currency, function(err) {
if(err) {
callback(err);
} else {
callback(null, item);
}
});
}, "steamcommunity");
};
function CMarketItem(community, body, $) {
function CMarketItem(appid, hashName, community, body, $) {
this._appid = appid;
this._hashName = hashName;
this._community = community;
this._$ = $;
@@ -38,6 +41,12 @@ function CMarketItem(community, body, $) {
if(match) {
this._country = match[1];
}
this._language = "english";
match = body.match(/var g_strLanguage = "([^"]+)";/);
if(match) {
this._language = match[1];
}
this.commodity = false;
var match = body.match(/Market_LoadOrderSpread\(\s*(\d+)\s*\);/);
@@ -62,37 +71,45 @@ function CMarketItem(community, body, $) {
// ignore
}
}
this.quantity = 0;
this.lowestPrice = 0;
if(!this.commodity) {
var total = $('#searchResults_total');
if(total) {
this.quantity = parseInt(total.text().replace(/[^\d]/g, '').trim(), 10);
}
var lowest = $('.market_listing_price.market_listing_price_with_fee');
if(lowest[0]) {
this.lowestPrice = parseInt($(lowest[0]).text().replace(/[^\d]/g, '').trim(), 10);
this.firstAsset = null;
this.assets = null;
match = body.match(/var g_rgAssets = (.*);/);
if (match) {
try {
this.assets = JSON.parse(match[1]);
this.assets = this.assets['730']['2'];
this.firstAsset = this.assets[Object.keys(this.assets)[0]];
} catch (e) {
// ignore
}
}
this.quantity = 0;
this.lowestPrice = 0;
// TODO: Buying listings and placing buy orders
}
CMarketItem.prototype.updatePrice = function(callback) {
CMarketItem.prototype.updatePrice = function (currency, callback) {
if (this.commodity) {
this.updatePriceForCommodity(currency, callback);
} else {
this.updatePriceForNonCommodity(currency, callback);
}
};
CMarketItem.prototype.updatePriceForCommodity = function(currency, callback) {
if(!this.commodity) {
throw new Error("Cannot update price for non-commodity item");
}
// TODO: Currency option maybe?
var self = this;
this._community.request({
"uri": "https://steamcommunity.com/market/itemordershistogram?country=US&language=english&currency=1&item_nameid=" + this.commodityID,
"json": true,
this._community.httpRequest({
"uri": "https://steamcommunity.com/market/itemordershistogram?country=US&language=english&currency=" + currency + "&item_nameid=" + this.commodityID,
"json": true
}, function(err, response, body) {
if(self._community._checkHttpError(err, response, callback)) {
if (err) {
callback(err);
return;
}
@@ -122,5 +139,50 @@ CMarketItem.prototype.updatePrice = function(callback) {
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) {
callback(err);
return;
}
if (body.success != 1) {
callback && callback(new Error("Error " + body.success));
return;
}
var match = body.total_count;
if (match) {
self.quantity = parseInt(match, 10);
}
var lowestPrice;
var $ = Cheerio.load(body.results_html);
match = $(".market_listing_price.market_listing_price_with_fee");
if (match) {
for (var i = 0; i < match.length; i++) {
lowestPrice = parseFloat($(match[i]).text().replace(",", ".").replace(/[^\d.]/g, ''));
if (!isNaN(lowestPrice)) {
self.lowestPrice = lowestPrice;
break;
}
}
}
callback && callback(null);
}, "steamcommunity");
};

View File

@@ -27,59 +27,63 @@ SteamCommunity.prototype.marketSearch = function(options, callback) {
qs.count = 100;
qs.sort_column = 'price';
qs.sort_dir = 'asc';
performSearch.call(this, this.request, qs, [], callback);
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"
},
"json": true
}, function(err, response, body) {
if (err) {
callback(err);
return;
}
if(!body.success) {
callback(new Error("Success is not true"));
return;
}
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) {
callback(new Error($errorMsg.text()));
return;
}
var rows = $('.market_listing_row_link');
for(var i = 0; i < rows.length; i++) {
results.push(new CMarketSearchResult($(rows[i])));
}
if(body.start + body.pagesize >= body.total_count) {
callback(null, results);
} else {
qs.start += body.pagesize;
performSearch();
}
}, "steamcommunity");
}
};
function performSearch(request, qs, results, callback) {
var self = this;
request({
"uri": "https://steamcommunity.com/market/search/render/",
"qs": qs,
"headers": {
"referer": "https://steamcommunity.com/market/search"
},
"json": true
}, function(err, response, body) {
if(self._checkHttpError(err, response, callback)) {
return;
}
if(!body.success) {
callback(new Error("Success is not true"));
return;
}
if(!body.results_html) {
callback(new Error("No results_html in response"));
return;
}
var $ = Cheerio.load(body.results_html);
if($('.market_listing_table_message').length > 0) {
callback(new Error($('.market_listing_table_message').text()));
return;
}
var rows = $('.market_listing_row_link');
for(var i = 0; i < rows.length; i++) {
results.push(new CMarketSearchResult($(rows[i])));
}
if(body.start + body.pagesize >= body.total_count) {
callback(null, results);
} else {
qs.start += body.pagesize;
performSearch.call(self, request, qs, results, callback);
}
});
}
function CMarketSearchResult(row) {
var match = row.attr('href').match(/\/market\/listings\/(\d+)\/(.+)/);
var 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.price = parseInt(row.find('.market_listing_their_price .market_table_value span').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);
}

View File

@@ -1,40 +1,38 @@
var SteamCommunity = require('../index.js');
var Helpers = require('../components/helpers.js');
var SteamID = require('steamid');
var xml2js = require('xml2js');
SteamCommunity.prototype.getSteamGroup = function(id, callback) {
if(typeof id !== 'string' && !(typeof id === 'object' && id.__proto__ === SteamID.prototype)) {
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");
}
var self = this;
this.request("https://steamcommunity.com/" + (typeof id === 'string' ? "groups/" + id : "gid/" + id.toString()) + "/memberslistxml/?xml=1", function(err, response, body) {
if(self._checkHttpError(err, response, callback)) {
this.httpRequest("https://steamcommunity.com/" + (typeof id === 'string' ? "groups/" + id : "gid/" + id.toString()) + "/memberslistxml/?xml=1", function(err, response, body) {
if (err) {
callback(err);
return;
}
if(self._checkCommunityError(body, callback)) {
return;
}
xml2js.parseString(body, function(err, result) {
if(err) {
callback(err);
return;
}
callback(null, new CSteamGroup(self, result.memberList));
});
});
}, "steamcommunity");
};
function CSteamGroup(community, groupData) {
this._community = community;
this.steamID = new SteamID(groupData.groupID64[0]);
this.name = groupData.groupDetails[0].groupName[0];
this.url = groupData.groupDetails[0].groupURL[0];
@@ -50,7 +48,7 @@ function CSteamGroup(community, groupData) {
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";
@@ -64,7 +62,7 @@ CSteamGroup.prototype.getMembers = function(addresses, callback) {
callback = addresses;
addresses = null;
}
this._community.getGroupMembers(this.steamID, callback, null, null, addresses, 0);
};
@@ -96,6 +94,14 @@ CSteamGroup.prototype.scheduleEvent = function(name, type, description, time, se
this._community.scheduleGroupEvent(this.steamID, name, type, description, time, server, callback);
};
CSteamGroup.prototype.editEvent = function(id, name, type, description, time, server, callback) {
this._community.editGroupEvent(this.steamID, id, name, type, description, time, server, callback);
};
CSteamGroup.prototype.deleteEvent = function (id, callback) {
this._community.deleteGroupEvent(this.steamID, id, callback);
};
CSteamGroup.prototype.setPlayerOfTheWeek = function(steamID, callback) {
this._community.setGroupPlayerOfTheWeek(this.steamID, steamID, callback);
};

View File

@@ -1,9 +1,10 @@
var SteamCommunity = require('../index.js');
var Helpers = require('../components/helpers.js');
var SteamID = require('steamid');
var xml2js = require('xml2js');
SteamCommunity.prototype.getSteamUser = function(id, callback) {
if(typeof id !== 'string' && !(typeof id === 'object' && id.__proto__ === SteamID.prototype)) {
if(typeof id !== 'string' && !Helpers.isSteamID(id)) {
throw new Error("id parameter should be a user URL string or a SteamID object");
}
@@ -12,12 +13,9 @@ SteamCommunity.prototype.getSteamUser = function(id, callback) {
}
var self = this;
this.request("http://steamcommunity.com/" + (typeof id === 'string' ? "id/" + id : "profiles/" + id.toString()) + "/?xml=1", function(err, response, body) {
if(self._checkHttpError(err, response, callback)) {
return;
}
if(self._checkCommunityError(body, callback)) {
this.httpRequest("http://steamcommunity.com/" + (typeof id === 'string' ? "id/" + id : "profiles/" + id.toString()) + "/?xml=1", function(err, response, body) {
if (err) {
callback(err);
return;
}
@@ -48,7 +46,7 @@ SteamCommunity.prototype.getSteamUser = function(id, callback) {
callback(null, new CSteamUser(self, result.profile, customurl));
});
});
}, "steamcommunity");
};
function CSteamUser(community, userData, customurl) {
@@ -90,7 +88,7 @@ function CSteamUser(community, userData, customurl) {
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) {
if(group['$'] && group['$'].isPrimary === "1") {
self.primaryGroup = new SteamID(group.groupID64[0]);
}
@@ -152,10 +150,33 @@ CSteamUser.prototype.inviteToGroup = function(groupID, callback) {
this._community.inviteUserToGroup(this.steamID, groupID, callback);
};
CSteamUser.prototype.getAliases = function(callback) {
this._community.getUserAliases(this.steamID, callback);
};
CSteamUser.prototype.getInventoryContexts = function(callback) {
this._community.getUserInventoryContexts(this.steamID, callback);
};
/**
* Get the contents of a user's inventory context.
* @deprecated Use CSteamUser#getInventoryContents instead
* @param {int} appID - The Steam application ID of the game for which you want an inventory
* @param {int} contextID - The ID of the "context" within the game you want to retrieve
* @param {boolean} tradableOnly - true to get only tradable items and currencies
* @param callback
*/
CSteamUser.prototype.getInventory = function(appID, contextID, tradableOnly, callback) {
this._community.getUserInventory(this.steamID, appID, contextID, tradableOnly, callback);
};
/**
* Get the contents of a user's inventory context.
* @param {int} appID - The Steam application ID of the game for which you want an inventory
* @param {int} contextID - The ID of the "context" within the game you want to retrieve
* @param {boolean} tradableOnly - true to get only tradable items and currencies
* @param callback
*/
CSteamUser.prototype.getInventoryContents = function(appID, contextID, tradableOnly, callback) {
this._community.getUserInventoryContents(this.steamID, appID, contextID, tradableOnly, callback);
};

View File

@@ -42,13 +42,21 @@ SteamCommunity.prototype.chatLogon = function(interval, uiMode) {
var self = this;
this.getWebApiOauthToken(function(err, token) {
if(err) {
var fatal = err.message.indexOf('not authorized') != -1;
if (!fatal) {
self.chatState = SteamCommunity.ChatState.LogOnFailed;
setTimeout(self.chatLogon.bind(self), 5000);
} else {
self.chatState = SteamCommunity.ChatState.Offline;
}
self.emit('chatLogOnFailed', err, fatal);
self.emit('debug', "Cannot get oauth token: " + err.message);
self.chatState = SteamCommunity.ChatState.LogOnFailed;
setTimeout(self.chatLogon.bind(self), 5000);
return;
}
self.request.post({
self.httpRequestPost({
"uri": "https://api.steampowered.com/ISteamWebUserPresenceOAuth/Logon/v1",
"form": {
"ui_mode": uiMode,
@@ -57,15 +65,17 @@ SteamCommunity.prototype.chatLogon = function(interval, uiMode) {
"json": true
}, function(err, response, body) {
if(err || response.statusCode != 200) {
self.emit('debug', 'Error logging into webchat: ' + (err ? err.message : "HTTP error " + response.statusCode));
self.chatState = SteamCommunity.ChatState.LogOnFailed;
self.emit('chatLogOnFailed', err ? err : new Error("HTTP error " + response.statusCode), false);
self.emit('debug', 'Error logging into webchat: ' + (err ? err.message : "HTTP error " + response.statusCode));
setTimeout(self.chatLogon.bind(self), 5000);
return;
}
if(body.error != 'OK') {
self.emit('debug', 'Error logging into webchat: ' + body.error);
self.chatState = SteamCommunity.ChatState.LogOnFailed;
self.emit('chatLogOnFailed', new Error(body.error), false);
self.emit('debug', 'Error logging into webchat: ' + body.error);
setTimeout(self.chatLogon.bind(self), 5000);
return;
}
@@ -74,7 +84,8 @@ SteamCommunity.prototype.chatLogon = function(interval, uiMode) {
"umqid": body.umqid,
"message": body.message,
"accessToken": token,
"interval": interval
"interval": interval,
"uiMode": uiMode
};
self.chatFriends = {};
@@ -82,7 +93,7 @@ SteamCommunity.prototype.chatLogon = function(interval, uiMode) {
self.chatState = SteamCommunity.ChatState.LoggedOn;
self.emit('chatLoggedOn');
self._chatPoll();
});
}, "steamcommunity");
});
};
@@ -103,7 +114,7 @@ SteamCommunity.prototype.chatMessage = function(recipient, text, type, callback)
type = type || 'saytext';
var self = this;
this.request.post({
this.httpRequestPost({
"uri": "https://api.steampowered.com/ISteamWebUserPresenceOAuth/Message/v1",
"form": {
"access_token": this._chat.accessToken,
@@ -118,7 +129,8 @@ SteamCommunity.prototype.chatMessage = function(recipient, text, type, callback)
return;
}
if(self._checkHttpError(err, response, callback)) {
if (err) {
callback(err);
return;
}
@@ -127,12 +139,12 @@ SteamCommunity.prototype.chatMessage = function(recipient, text, type, callback)
} else {
callback(null);
}
});
}, "steamcommunity");
};
SteamCommunity.prototype.chatLogoff = function() {
var self = this;
this.request.post({
this.httpRequestPost({
"uri": "https://api.steampowered.com/ISteamWebUserPresenceOAuth/Logoff/v1",
"form": {
"access_token": this._chat.accessToken,
@@ -149,14 +161,14 @@ SteamCommunity.prototype.chatLogoff = function() {
delete self.chatFriends;
self.chatState = SteamCommunity.ChatState.Offline;
}
});
}, "steamcommunity");
};
SteamCommunity.prototype._chatPoll = function() {
this.emit('debug', 'Doing chat poll');
var self = this;
this.request.post({
this.httpRequestPost({
"uri": "https://api.steampowered.com/ISteamWebUserPresenceOAuth/Poll/v1",
"form": {
"umqid": self._chat.umqid,
@@ -177,11 +189,19 @@ SteamCommunity.prototype._chatPoll = function() {
if(err || response.statusCode != 200) {
self.emit('debug', 'Error in chat poll: ' + (err ? err.message : "HTTP error " + response.statusCode));
if (err.message == "Not Logged On") {
self._relogWebChat();
}
return;
}
if(body.error != 'OK') {
self.emit('debug', 'Error in chat poll: ' + body.error);
if(!body || body.error != 'OK') {
self.emit('debug', 'Error in chat poll: ' + (body && body.error ? body.error : "Malformed response"));
if (body && body.error && body.error == "Not Logged On") {
self._relogWebChat();
}
return;
}
@@ -211,13 +231,20 @@ SteamCommunity.prototype._chatPoll = function() {
self.emit('debug', 'Unhandled chat message type: ' + message.type);
}
});
});
}, "steamcommunity");
};
SteamCommunity.prototype._relogWebChat = function() {
this.emit('debug', "Relogging web chat");
clearTimeout(this._chat.timer);
this.chatState = SteamCommunity.ChatState.Offline;
this.chatLogon(this._chat.interval, this._chat.uiMode);
};
SteamCommunity.prototype._chatUpdatePersona = function(steamID) {
this.emit('debug', 'Updating persona data for ' + steamID);
var self = this;
this.request({
this.httpRequest({
"uri": "https://steamcommunity.com/chat/friendstate/" + steamID.accountid,
"json": true
}, function(err, response, body) {
@@ -242,5 +269,5 @@ SteamCommunity.prototype._chatUpdatePersona = function(steamID) {
self.emit('chatPersonaState', steamID, persona);
self.chatFriends[steamID.getSteamID64()] = persona;
});
}, "steamcommunity");
};

View File

@@ -16,6 +16,11 @@ SteamCommunity.prototype.getConfirmations = function(time, key, callback) {
request(this, "conf", key, time, "conf", null, false, function(err, body) {
if(err) {
if (err.message == "Invalid protocol: steammobile:") {
err.message = "Not Logged In";
self._notifySessionExpired(err);
}
callback(err);
return;
}
@@ -47,6 +52,8 @@ SteamCommunity.prototype.getConfirmations = function(time, key, callback) {
var img = conf.find('.mobileconf_list_entry_icon img');
confs.push(new CConfirmation(self, {
"id": conf.data('confid'),
"type": conf.data('type'),
"creator": conf.data('creator'),
"key": conf.data('key'),
"title": conf.find('.mobileconf_list_entry_description>div:nth-of-type(1)').text().trim(),
"receiving": conf.find('.mobileconf_list_entry_description>div:nth-of-type(2)').text().trim(),
@@ -103,15 +110,15 @@ SteamCommunity.prototype.getConfirmationOfferID = function(confID, time, key, ca
/**
* Confirm or cancel a given confirmation.
* @param {int} confID - The ID of the confirmation in question
* @param {string} confKey - The confirmation key associated with the confirmation in question (not a TOTP key, the `key` property of CConfirmation)
* @param {int|int[]} confID - The ID of the confirmation in question, or an array of confirmation IDs
* @param {string|string[]} confKey - The confirmation key associated with the confirmation in question (or an array of them) (not a TOTP key, the `key` property of CConfirmation)
* @param {int} time - The unix timestamp with which the following key was generated
* @param {string} key - The confirmation key that was generated using the preceeding time and the tag "allow" (if accepting) or "cancel" (if not accepting)
* @param {string} key - The confirmation key that was generated using the preceding time and the tag "allow" (if accepting) or "cancel" (if not accepting)
* @param {boolean} accept - true if you want to accept the confirmation, false if you want to cancel it
* @param {SteamCommunity~genericErrorCallback} callback - Called when the request is complete
*/
SteamCommunity.prototype.respondToConfirmation = function(confID, confKey, time, key, accept, callback) {
request(this, "ajaxop", key, time, accept ? "allow" : "cancel", {
request(this, (confID instanceof Array) ? "multiajaxop" : "ajaxop", key, time, accept ? "allow" : "cancel", {
"op": accept ? "allow" : "cancel",
"cid": confID,
"ck": confKey
@@ -139,6 +146,102 @@ SteamCommunity.prototype.respondToConfirmation = function(confID, confKey, time,
});
};
/**
* Accept a confirmation for a given object (trade offer or market listing) automatically.
* @param {string} identitySecret
* @param {number|string} objectID
* @param {SteamCommunity~genericErrorCallback} callback
*/
SteamCommunity.prototype.acceptConfirmationForObject = function(identitySecret, objectID, callback) {
var self = this;
this._usedConfTimes = this._usedConfTimes || [];
if (typeof this._timeOffset !== 'undefined') {
// time offset is already known and saved
doConfirmation();
} else {
SteamTotp.getTimeOffset(function(err, offset) {
if (err) {
callback(err);
return;
}
self._timeOffset = offset;
doConfirmation();
setTimeout(function() {
// Delete the saved time offset after 12 hours because why not
delete self._timeOffset;
}, 1000 * 60 * 60 * 12);
});
}
function doConfirmation() {
var offset = self._timeOffset;
var time = SteamTotp.time(offset);
self.getConfirmations(time, SteamTotp.getConfirmationKey(identitySecret, time, "conf"), function(err, confs) {
if (err) {
callback(err);
return;
}
var conf = confs.filter(function(conf) { return conf.creator == objectID; });
if (conf.length == 0) {
callback(new Error("Could not find confirmation for object " + objectID));
return;
}
conf = conf[0];
// make sure we don't reuse the same time
var localOffset = 0;
do {
time = SteamTotp.time(offset) + localOffset++;
} while (self._usedConfTimes.indexOf(time) != -1);
self._usedConfTimes.push(time);
if (self._usedConfTimes.length > 60) {
self._usedConfTimes.splice(0, self._usedConfTimes.length - 60); // we don't need to save more than 60 entries
}
conf.respond(time, SteamTotp.getConfirmationKey(identitySecret, time, "allow"), true, callback);
});
}
};
/**
* Send a single request to Steam to accept all outstanding confirmations (after loading the list). If one fails, the
* entire request will fail and there will be no way to know which failed without loading the list again.
* @param {number} time
* @param {string} confKey
* @param {string} allowKey
* @param {function} callback
*/
SteamCommunity.prototype.acceptAllConfirmations = function(time, confKey, allowKey, callback) {
var self = this;
this.getConfirmations(time, confKey, function(err, confs) {
if (err) {
callback(err);
return;
}
if (confs.length == 0) {
callback(null, []);
return;
}
self.respondToConfirmation(confs.map(function(conf) { return conf.id; }), confs.map(function(conf) { return conf.key; }), time, allowKey, true, function(err) {
if (err) {
callback(err);
return;
}
callback(err, confs);
});
});
};
function request(community, url, key, time, tag, params, json, callback) {
params = params || {};
params.p = SteamTotp.getDeviceID(community.steamID);
@@ -148,24 +251,33 @@ function request(community, url, key, time, tag, params, json, callback) {
params.m = "android";
params.tag = tag;
community.request.get({
var req = {
"method": url == 'multiajaxop' ? 'POST' : 'GET',
"uri": "https://steamcommunity.com/mobileconf/" + url,
"qs": params,
"json": !!json
}, function(err, response, body) {
if(community._checkHttpError(err, response, callback)) {
};
if (req.method == "GET") {
req.qs = params;
} else {
req.form = params;
}
community.httpRequest(req, function(err, response, body) {
if (err) {
callback(err);
return;
}
callback(null, body);
});
}, "steamcommunity");
}
// Confirmation checker
/**
* Start automatically polling our confirmations for new ones. The `confKeyNeeded` event will be emitted when we need a confirmation key, or `newConfirmation` when we get a new confirmation
* @param {int} pollInterval - The interval, in milliseconds, at which we will poll for confirmations. This shouldn't be any less than 10,000 probably.
* @param {int} pollInterval - The interval, in milliseconds, at which we will poll for confirmations. This should probably be at least 10,000 to avoid rate-limits.
* @param {Buffer|string|null} [identitySecret=null] - Your identity_secret. If passed, all confirmations will be automatically accepted and nothing will be emitted.
*/
SteamCommunity.prototype.startConfirmationChecker = function(pollInterval, identitySecret) {
@@ -217,8 +329,9 @@ SteamCommunity.prototype.checkConfirmations = function() {
// We should accept this
self.emit('debug', "Accepting confirmation #" + conf.id);
var time = Math.floor(Date.now() / 1000);
conf.respond(time, SteamTotp.getConfirmationKey(self._identitySecret, time, "allow"), true, function() {
conf.respond(time, SteamTotp.getConfirmationKey(self._identitySecret, time, "allow"), true, function(err) {
// If there was an error and it wasn't actually accepted, we'll pick it up again
if (!err) self.emit('confirmationAccepted', conf);
delete self._knownConfirmations[conf.id];
setTimeout(callback, 1000); // Call the callback in 1 second, to make sure the time changes
});
@@ -239,6 +352,7 @@ SteamCommunity.prototype.checkConfirmations = function() {
self.getConfirmations(key.time, key.key, function(err, confirmations) {
if(err) {
self.emit('debug', "Can't check confirmations: " + err.message);
resetTimer();
return;
}
@@ -254,24 +368,13 @@ SteamCommunity.prototype.checkConfirmations = function() {
return; // No new ones
}
// We have new confirmations! Grab a key to get details.
self._confirmationCheckerGetKey('details', function(err, key) {
newOnes.forEach(function(conf) {
self._knownConfirmations[conf.id] = conf; // Add it to our list of known confirmations
if(err) {
self._confirmationQueue.push(conf);
} else {
// Get its offer ID, if we can
conf.getOfferID(key.time, key.key, function(err, offerID) {
conf.offerID = offerID ? offerID : null;
self._confirmationQueue.push(conf);
});
}
});
resetTimer();
// We have new confirmations!
newOnes.forEach(function(conf) {
self._knownConfirmations[conf.id] = conf; // Add it to our list of known confirmations
self._confirmationQueue.push(conf);
});
resetTimer();
});
});
@@ -280,23 +383,6 @@ SteamCommunity.prototype.checkConfirmations = function() {
self._confirmationTimer = setTimeout(self.checkConfirmations.bind(self), self._confirmationPollInterval);
}
}
function handleNewConfirmation(conf, handleNumber) {
self._knownConfirmations[conf.id] = conf;
// Delay them by 1 second per new confirmation that we see, so that keys won't be the same.
setTimeout(function() {
if(self._identitySecret) {
self.emit('debug', 'Accepting confirmation ' + conf.id);
var time = Math.floor(Date.now() / 1000);
conf.respond(time, SteamTotp.getConfirmationKey(self._identitySecret, time, "allow"), true, function() {
delete self._knownConfirmations[conf.id];
});
} else {
self.emit('newConfirmation', conf);
}
}, handleNumber * 1000);
}
};
SteamCommunity.prototype._confirmationCheckerGetKey = function(tag, callback) {

View File

@@ -38,8 +38,9 @@ SteamCommunity.prototype.getGroupMembers = function(gid, callback, members, link
}
var self = this;
this.request(options, function(err, response, body) {
if (self._checkHttpError(err, response, callback)) {
this.httpRequest(options, function(err, response, body) {
if (err) {
callback(err);
return;
}
@@ -60,7 +61,7 @@ SteamCommunity.prototype.getGroupMembers = function(gid, callback, members, link
callback(null, members);
}
});
});
}, "steamcommunity");
};
SteamCommunity.prototype.getGroupMembersEx = function(gid, addresses, callback) {
@@ -73,7 +74,7 @@ SteamCommunity.prototype.joinGroup = function(gid, callback) {
}
var self = this;
this.request.post({
this.httpRequestPost({
"uri": "https://steamcommunity.com/gid/" + gid.getSteamID64(),
"form": {
"action": "join",
@@ -84,17 +85,8 @@ SteamCommunity.prototype.joinGroup = function(gid, callback) {
return;
}
if(err || response.statusCode >= 400) {
callback(err || new Error("HTTP error " + response.statusCode));
return;
}
if(self._checkCommunityError(body, callback)) {
return;
}
callback(null);
});
callback(err || null);
}, "steamcommunity");
};
SteamCommunity.prototype.leaveGroup = function(gid, callback) {
@@ -112,16 +104,7 @@ SteamCommunity.prototype.leaveGroup = function(gid, callback) {
return;
}
if(err || response.statusCode >= 400) {
callback(err || new Error("HTTP error " + response.statusCode));
return;
}
if(self._checkCommunityError(body, callback)) {
return;
}
callback(null);
callback(err || null);
});
};
@@ -136,15 +119,11 @@ SteamCommunity.prototype.getAllGroupAnnouncements = function(gid, time, callback
}
var self = this;
this.request({
"uri": "https://steamcommunity.com/gid/" + gid.getSteamID64() + "/rss/"
this.httpRequest({
"uri": "https://steamcommunity.com/gid/" + gid.getSteamID64() + "/rss/"
}, function(err, response, body) {
if(self._checkHttpError(err, response, callback)) {
return;
}
if(self._checkCommunityError(body, callback)) {
if (err) {
callback(err);
return;
}
@@ -172,7 +151,7 @@ SteamCommunity.prototype.getAllGroupAnnouncements = function(gid, time, callback
return callback(null, announcements);
});
});
}, "steamcommunity");
}
SteamCommunity.prototype.postGroupAnnouncement = function(gid, headline, content, callback) {
@@ -181,7 +160,7 @@ SteamCommunity.prototype.postGroupAnnouncement = function(gid, headline, content
}
var self = this;
this.request.post({
this.httpRequestPost({
"uri": "https://steamcommunity.com/gid/" + gid.getSteamID64() + "/announcements",
"form": {
"sessionID": this.getSessionID(),
@@ -196,16 +175,8 @@ SteamCommunity.prototype.postGroupAnnouncement = function(gid, headline, content
return;
}
if(self._checkHttpError(err, response, callback)) {
return;
}
if(self._checkCommunityError(body, callback)) {
return;
}
callback(null);
})
callback(err || null);
}, "steamcommunity");
};
SteamCommunity.prototype.editGroupAnnouncement = function(gid, aid, headline, content, callback) {
@@ -227,23 +198,15 @@ SteamCommunity.prototype.editGroupAnnouncement = function(gid, aid, headline, co
"languages[0][body]": content,
"languages[0][updated]": 1
}
}
};
this.request.post(submitData, function(err, response, body) {
this.httpRequestPost(submitData, function(err, response, body) {
if(!callback) {
return;
}
if(self._checkHttpError(err, response, callback)) {
return;
}
if(self._checkCommunityError(body, callback)) {
return;
}
callback(null);
})
callback(err || null);
}, "steamcommunity");
};
SteamCommunity.prototype.deleteGroupAnnouncement = function(gid, aid, callback) {
@@ -254,24 +217,16 @@ SteamCommunity.prototype.deleteGroupAnnouncement = function(gid, aid, callback)
var self = this;
var submitData = {
"uri": "https://steamcommunity.com/gid/" + gid.getSteamID64() + "/announcements/delete/" + aid + "?sessionID=" + this.getSessionID(),
}
"uri": "https://steamcommunity.com/gid/" + gid.getSteamID64() + "/announcements/delete/" + aid + "?sessionID=" + this.getSessionID()
};
this.request.get(submitData, function(err, response, body) {
this.httpRequestGet(submitData, function(err, response, body) {
if(!callback) {
return;
}
if(self._checkHttpError(err, response, callback)) {
return;
}
if(self._checkCommunityError(body, callback)) {
return;
}
callback(null);
})
callback(err || null);
}, "steamcommunity");
};
SteamCommunity.prototype.scheduleGroupEvent = function(gid, name, type, description, time, server, callback) {
@@ -287,7 +242,7 @@ SteamCommunity.prototype.scheduleGroupEvent = function(gid, name, type, descript
server = {"ip": "", "password": ""};
} else if(typeof server === 'string') {
server = {"ip": server, "password": ""};
} else {
} else if(typeof server !== 'object') {
server = {"ip": "", "password": ""};
}
@@ -319,7 +274,7 @@ SteamCommunity.prototype.scheduleGroupEvent = function(gid, name, type, descript
}
var self = this;
this.request.post({
this.httpRequestPost({
"uri": "https://steamcommunity.com/gid/" + gid.toString() + "/eventEdit",
"form": form
}, function(err, response, body) {
@@ -327,17 +282,90 @@ SteamCommunity.prototype.scheduleGroupEvent = function(gid, name, type, descript
return;
}
if(err || response.statusCode >= 400) {
callback(err || new Error("HTTP error " + response.statusCode));
callback(err || null);
}, "steamcommunity");
};
SteamCommunity.prototype.editGroupEvent = function (gid, id, name, type, description, time, server, callback) {
if (typeof gid === 'string') {
gid = new SteamID(gid);
}
// Event types: ChatEvent - Chat, OtherEvent - A lil somethin somethin, PartyEvent - Party!, MeetingEvent - Important meeting, SpecialCauseEvent - Special cause (charity ball?), MusicAndArtsEvent - Music or Art type thing, SportsEvent - Sporting endeavor, TripEvent - Out of town excursion
// Passing a number for type will make it a game event for that appid
if (typeof server === 'function') {
callback = server;
server = {"ip": "", "password": ""};
} else if (typeof server === 'string') {
server = {"ip": server, "password": ""};
} else if (typeof server !== 'object') {
server = {"ip": "", "password": ""};
}
var form = {
"sessionid": this.getSessionID(),
"action": "updateEvent",
"eventID": id,
"tzOffset": new Date().getTimezoneOffset() * -60,
"name": name,
"type": (typeof type === 'number' || !isNaN(parseInt(type, 10)) ? "GameEvent" : type),
"appID": (typeof type === 'number' || !isNaN(parseInt(type, 10)) ? type : ''),
"serverIP": server.ip,
"serverPassword": server.password,
"notes": description,
"eventQuickTime": "now"
};
if (time === null) {
form.startDate = 'MM/DD/YY';
form.startHour = '12';
form.startMinute = '00';
form.startAMPM = 'PM';
form.timeChoice = 'quick';
} else {
form.startDate = (time.getMonth() + 1 < 10 ? '0' : '') + (time.getMonth() + 1) + '/' + (time.getDate() < 10 ? '0' : '') + time.getDate() + '/' + time.getFullYear().toString().substring(2);
form.startHour = (time.getHours() === 0 ? '12' : (time.getHours() > 12 ? time.getHours() - 12 : time.getHours()));
form.startMinute = (time.getMinutes() < 10 ? '0' : '') + time.getMinutes();
form.startAMPM = (time.getHours() <= 12 ? 'AM' : 'PM');
form.timeChoice = 'specific';
}
var self = this;
this.httpRequestPost({
"uri": "https://steamcommunity.com/gid/" + gid.toString() + "/eventEdit",
"form": form
}, function(err, response, body) {
if(!callback) {
return;
}
if(self._checkCommunityError(body, callback)) {
callback(err || null);
}, "steamcommunity");
};
SteamCommunity.prototype.deleteGroupEvent = function(gid, id, callback) {
if (typeof gid === 'string') {
gid = new SteamID(gid);
}
var form = {
"sessionid": this.getSessionID(),
"action": "deleteEvent",
"eventID": id
};
var self = this;
this.httpRequestPost({
"uri": "https://steamcommunity.com/gid/" + gid.toString() + "/eventEdit",
"form": form
}, function(err, response, body) {
if(!callback) {
return;
}
callback(null);
});
callback(err || null);
}, "steamcommunity");
};
SteamCommunity.prototype.setGroupPlayerOfTheWeek = function(gid, steamID, callback) {
@@ -350,7 +378,7 @@ SteamCommunity.prototype.setGroupPlayerOfTheWeek = function(gid, steamID, callba
}
var self = this;
this.request.post({
this.httpRequestPost({
"uri": "https://steamcommunity.com/gid/" + gid.getSteamID64() + "/potwEdit",
"form": {
"xml": 1,
@@ -380,7 +408,7 @@ SteamCommunity.prototype.setGroupPlayerOfTheWeek = function(gid, steamID, callba
callback(new Error(results.response.results[0]));
}
});
});
}, "steamcommunity");
};
SteamCommunity.prototype.kickGroupMember = function(gid, steamID, callback) {
@@ -393,7 +421,7 @@ SteamCommunity.prototype.kickGroupMember = function(gid, steamID, callback) {
}
var self = this;
this.request.post({
this.httpRequestPost({
"uri": "https://steamcommunity.com/gid/" + gid.getSteamID64() + "/membersManage",
"form": {
"sessionID": this.getSessionID(),
@@ -406,17 +434,8 @@ SteamCommunity.prototype.kickGroupMember = function(gid, steamID, callback) {
return;
}
if(err || response.statusCode >= 400) {
callback(err || new Error("HTTP error " + response.statusCode));
return;
}
if(self._checkCommunityError(body, callback)) {
return;
}
callback(null);
});
callback(err || null);
}, "steamcommunity");
};
SteamCommunity.prototype.getGroupHistory = function(gid, page, callback) {
@@ -430,12 +449,9 @@ SteamCommunity.prototype.getGroupHistory = function(gid, page, callback) {
}
var self = this;
this.request("https://steamcommunity.com/gid/" + gid.getSteamID64() + "/history?p=" + page, function(err, response, body) {
if(self._checkHttpError(err, response, callback)) {
return;
}
if(self._checkCommunityError(body, callback)) {
this.httpRequest("https://steamcommunity.com/gid/" + gid.getSteamID64() + "/history?p=" + page, function(err, response, body) {
if (err) {
callback(err);
return;
}
@@ -499,5 +515,5 @@ SteamCommunity.prototype.getGroupHistory = function(gid, page, callback) {
});
callback(null, output);
});
}, "steamcommunity");
};

23
components/helpers.js Normal file
View File

@@ -0,0 +1,23 @@
exports.isSteamID = function(input) {
var keys = Object.keys(input);
if (keys.length != 4) {
return false;
}
// Make sure it has the keys we expect
keys = keys.filter(function(item) {
return ['universe', 'type', 'instance', 'accountid'].indexOf(item) != -1;
});
return keys.length == 4;
};
exports.decodeSteamTime = function(time) {
var parts = time.split('@');
if (!parts[0].match(/,/)) {
// no year, assume current year
parts[0] += ", " + (new Date()).getFullYear();
}
return new Date(parts.join('@').replace(/(am|pm)/, ' $1') + " UTC"); // add a space so JS can decode it
};

150
components/http.js Normal file
View File

@@ -0,0 +1,150 @@
var SteamCommunity = require('../index.js');
SteamCommunity.prototype.httpRequest = function(uri, options, callback, source) {
if (typeof uri === 'object') {
source = callback;
callback = options;
options = uri;
uri = options.url || options.uri;
} else if (typeof options === 'function') {
source = callback;
callback = options;
options = {};
}
options.url = options.uri = uri;
if (this._httpRequestConvenienceMethod) {
options.method = this._httpRequestConvenienceMethod;
delete this._httpRequestConvenienceMethod;
}
var requestID = ++this._httpRequestID;
source = source || "";
var self = this;
var continued = false;
if (!this.onPreHttpRequest || !this.onPreHttpRequest(requestID, source, options, continueRequest)) {
// No pre-hook, or the pre-hook doesn't want to delay the request.
continueRequest(null);
}
function continueRequest(err) {
if (continued) {
return;
}
continued = true;
if (err) {
if (callback) {
callback(err);
}
return;
}
self.request(options, function (err, response, body) {
var hasCallback = !!callback;
var httpError = options.checkHttpError !== false && self._checkHttpError(err, response, callback, body);
var communityError = !options.json && options.checkCommunityError !== false && self._checkCommunityError(body, httpError ? function () {} : callback); // don't fire the callback if hasHttpError did it already
var tradeError = !options.json && options.checkTradeError !== false && self._checkTradeError(body, httpError || communityError ? function () {} : callback); // don't fire the callback if either of the previous already did
var jsonError = options.json && options.checkJsonError !== false && !body ? new Error("Malformed JSON response") : null;
self.emit('postHttpRequest', requestID, source, options, httpError || communityError || tradeError || jsonError || null, response, body, {
"hasCallback": hasCallback,
"httpError": httpError,
"communityError": communityError,
"tradeError": tradeError,
"jsonError": jsonError
});
if (hasCallback && !(httpError || communityError || tradeError)) {
if (jsonError) {
callback.call(self, jsonError, response);
} else {
callback.apply(self, arguments);
}
}
});
}
};
SteamCommunity.prototype.httpRequestGet = function() {
this._httpRequestConvenienceMethod = "GET";
return this.httpRequest.apply(this, arguments);
};
SteamCommunity.prototype.httpRequestPost = function() {
this._httpRequestConvenienceMethod = "POST";
return this.httpRequest.apply(this, arguments);
};
SteamCommunity.prototype._notifySessionExpired = function(err) {
this.emit('sessionExpired', err);
};
SteamCommunity.prototype._checkHttpError = function(err, response, callback, body) {
if (err) {
callback(err, response, body);
return err;
}
if (response.statusCode >= 300 && response.statusCode <= 399 && response.headers.location.indexOf('/login') != -1) {
err = new Error("Not Logged In");
callback(err, response, body);
this._notifySessionExpired(err);
return err;
}
if (response.statusCode == 403 && response.body && response.body.match(/<div id="parental_notice_instructions">Enter your PIN below to exit Family View.<\/div>/)) {
err = new Error("Family View Restricted");
callback(err, response, body);
return err;
}
if (response.statusCode >= 400) {
err = new Error("HTTP error " + response.statusCode);
err.code = response.statusCode;
callback(err, response, body);
return err;
}
return false;
};
SteamCommunity.prototype._checkCommunityError = function(html, callback) {
var err;
if(typeof html === 'string' && html.match(/<h1>Sorry!<\/h1>/)) {
var match = html.match(/<h3>(.+)<\/h3>/);
err = new Error(match ? match[1] : "Unknown error occurred");
callback(err);
return err;
}
if (typeof html === 'string' && html.match(/g_steamID = false;/) && html.match(/<h1>Sign In<\/h1>/)) {
err = new Error("Not Logged In");
callback(err);
this._notifySessionExpired(err);
return err;
}
return false;
};
SteamCommunity.prototype._checkTradeError = function(html, callback) {
if (typeof html !== 'string') {
return false;
}
var match = html.match(/<div id="error_msg">\s*([^<]+)\s*<\/div>/);
if (match) {
var err = new Error(match[1].trim());
callback(err);
return err;
}
return false;
};

View File

@@ -5,139 +5,179 @@ var request = require('request');
var Cheerio = require('cheerio');
var Async = require('async');
/*
* Inventory history in a nutshell.
*
* There are no more page numbers. Now you have to request after_time and optionally after_trade.
* Without "prev" set, you will request 30 trades that were completed FURTHER IN THE PAST than after_time (and optionally after_trade)
* With "prev" set, you will request 30 trades that were completed MORE RECENTLY than after_time (and optionally after_trade)
*/
SteamCommunity.prototype.getInventoryHistory = function(options, callback) {
if(typeof options === 'function') {
if (typeof options === 'function') {
callback = options;
options = {};
}
options.page = options.page || 1;
this.request("https://steamcommunity.com/my/inventoryhistory?l=english&p=" + options.page, function(err, response, body) {
if(err) {
options.direction = options.direction || "past";
var qs = "?l=english";
if (options.startTime) {
if (options.startTime instanceof Date) {
options.startTime = Math.floor(options.startTime.getTime() / 1000);
}
qs += "&after_time=" + options.startTime;
if (options.startTrade) {
qs += "&after_trade=" + options.startTrade;
}
}
if (options.direction == "future") {
qs += "&prev=1";
}
this._myProfile("inventoryhistory" + qs, null, function(err, response, body) {
if (err) {
callback(err);
return;
}
var output = {};
var vanityURLs = [];
var $ = Cheerio.load(body);
var html = $('.inventory_history_pagingrow').html();
if(!html) {
if (!$('.inventory_history_pagingrow').html()) {
callback("Malformed page: no paging row found");
return;
}
var match = html.match(/(\d+) - (\d+) of (\d+) History Items/);
output.first = parseInt(match[1], 10);
output.last = parseInt(match[2], 10);
output.totalTrades = parseInt(match[3], 10);
// Load the inventory item data
var match2 = body.match(/var g_rgHistoryInventory = (.*);/);
if(!match2) {
if (!match2) {
callback(new Error("Malformed page: no trade found"));
return;
}
var historyInventory = JSON.parse(match2[1]);
try {
var historyInventory = JSON.parse(match2[1]);
} catch (ex) {
callback(new Error("Malformed page: no well-formed trade data found"));
return;
}
var i;
// See if we've got paging buttons
var $paging = $('.inventory_history_nextbtn .pagebtn:not(.disabled)');
var href;
for (i = 0; i < $paging.length; i++) {
href = $paging[i].attribs.href;
if (href.match(/prev=1/)) {
output.firstTradeTime = new Date(href.match(/after_time=(\d+)/)[1] * 1000);
output.firstTradeID = href.match(/after_trade=(\d+)/)[1];
} else {
output.lastTradeTime = new Date(href.match(/after_time=(\d+)/)[1] * 1000);
output.lastTradeID = href.match(/after_trade=(\d+)/)[1];
}
}
output.trades = [];
var trades = $('.tradehistoryrow');
var item, trade, profileLink, items, j, econItem, timeMatch, time;
for(var i = 0; i < trades.length; i++) {
for (i = 0; i < trades.length; i++) {
item = $(trades[i]);
trade = {};
trade.onHold = !!item.find('span:nth-of-type(2)').text().match(/Trade on Hold/i);
timeMatch = item.find('.tradehistory_timestamp').html().match(/(\d+):(\d+)(am|pm)/);
if(timeMatch[1] == 12 && timeMatch[3] == 'am') {
if (timeMatch[1] == 12 && timeMatch[3] == 'am') {
timeMatch[1] = 0;
}
if(timeMatch[1] < 12 && timeMatch[3] == 'pm') {
if (timeMatch[1] < 12 && timeMatch[3] == 'pm') {
timeMatch[1] = parseInt(timeMatch[1], 10) + 12;
}
time = (timeMatch[1] < 10 ? '0' : '') + timeMatch[1] + ':' + timeMatch[2] + ':00';
trade.date = new Date(item.find('.tradehistory_date').html() + ' ' + time);
trade.date = new Date(item.find('.tradehistory_date').html() + ' ' + time + ' UTC');
trade.partnerName = item.find('.tradehistory_event_description a').html();
trade.partnerSteamID = null;
trade.partnerVanityURL = null;
trade.itemsReceived = [];
trade.itemsGiven = [];
profileLink = item.find('.tradehistory_event_description a').attr('href');
if(profileLink.indexOf('/profiles/') != -1) {
if (profileLink.indexOf('/profiles/') != -1) {
trade.partnerSteamID = new SteamID(profileLink.match(/(\d+)$/)[1]);
} else {
trade.partnerVanityURL = profileLink.match(/\/([^\/]+)$/)[1];
if(options.resolveVanityURLs && vanityURLs.indexOf(trade.partnerVanityURL) == -1) {
if (options.resolveVanityURLs && vanityURLs.indexOf(trade.partnerVanityURL) == -1) {
vanityURLs.push(trade.partnerVanityURL);
}
}
items = item.find('.history_item');
for(j = 0; j < items.length; j++) {
for (j = 0; j < items.length; j++) {
match = body.match(new RegExp("HistoryPageCreateItemHover\\( '" + $(items[j]).attr('id') + "', (\\d+), '(\\d+)', '(\\d+|class_\\d+_instance_\\d+|class_\\d+)', '(\\d+)' \\);"));
econItem = historyInventory[match[1]][match[2]][match[3]];
if($(items[j]).attr('id').indexOf('received') != -1) {
if ($(items[j]).attr('id').indexOf('received') != -1) {
trade.itemsReceived.push(new CEconItem(econItem));
} else {
trade.itemsGiven.push(new CEconItem(econItem));
}
}
output.trades.push(trade);
}
if(options.resolveVanityURLs) {
if (options.resolveVanityURLs) {
Async.map(vanityURLs, resolveVanityURL, function(err, results) {
if(err) {
if (err) {
callback(err);
return;
}
for(i = 0; i < output.trades.length; i++) {
if(output.trades[i].partnerSteamID || !output.trades[i].partnerVanityURL) {
for (i = 0; i < output.trades.length; i++) {
if (output.trades[i].partnerSteamID || !output.trades[i].partnerVanityURL) {
continue;
}
// Find the vanity URL
for(j = 0; j < results.length; j++) {
if(results[j].vanityURL == output.trades[i].partnerVanityURL) {
for (j = 0; j < results.length; j++) {
if (results[j].vanityURL == output.trades[i].partnerVanityURL) {
output.trades[i].partnerSteamID = new SteamID(results[j].steamID);
break;
}
}
}
callback(null, output);
});
} else {
callback(null, output);
}
});
}, "steamcommunity");
};
function resolveVanityURL(vanityURL, callback) {
request("https://steamcommunity.com/id/" + vanityURL + "/?xml=1", function(err, response, body) {
if(err) {
if (err) {
callback(err);
return;
}
var match = body.match(/<steamID64>(\d+)<\/steamID64>/);
if(!match || !match[1]) {
if (!match || !match[1]) {
callback(new Error("Couldn't find Steam ID"));
return;
}
callback(null, {"vanityURL": vanityURL, "steamID": match[1]});
});
}

View File

@@ -3,10 +3,12 @@ var Cheerio = require('cheerio');
SteamCommunity.prototype.getMarketApps = function(callback) {
var self = this;
this.request('https://steamcommunity.com/market/', function (err, response, body) {
if(self._checkHttpError(err, response, callback)) {
this.httpRequest('https://steamcommunity.com/market/', function (err, response, body) {
if (err) {
callback(err);
return;
}
var $ = Cheerio.load(body);
if ($('.market_search_game_button_group')) {
apps = {};
@@ -21,5 +23,5 @@ SteamCommunity.prototype.getMarketApps = function(callback) {
} else {
callback(new Error("Malformed response"));
}
});
}
}, "steamcommunity");
};

View File

@@ -114,6 +114,10 @@ SteamCommunity.prototype.editProfile = function(settings, callback) {
}
self._myProfile("edit", values, function(err, response, body) {
if (settings.customURL) {
delete self._profileURL;
}
if(err || response.statusCode != 200) {
if(callback) {
callback(err || new Error("HTTP error " + response.statusCode));
@@ -190,15 +194,6 @@ SteamCommunity.prototype.profileSettings = function(settings, callback) {
case 'inventoryGifts':
values.inventoryGiftPrivacy = settings[i] ? 1 : 0;
break;
case 'emailConfirmation': // deprecated
case 'tradeConfirmation':
values.tradeConfirmationSetting = settings[i] ? 1 : 0;
break;
case 'marketConfirmation':
values.marketConfirmationSetting = settings[i] ? 1 : 0;
break;
}
}
@@ -229,7 +224,7 @@ SteamCommunity.prototype.uploadAvatar = function(image, format, callback) {
if(image instanceof Buffer) {
doUpload(image);
} else if(image.match(/^https?:\/\//)) {
this.request.get({
this.httpRequestGet({
"uri": image,
"encoding": null
}, function(err, response, body) {
@@ -246,7 +241,7 @@ SteamCommunity.prototype.uploadAvatar = function(image, format, callback) {
}
doUpload(body);
})
}, "steamcommunity");
} else {
if(!format) {
format = image.match(/\.([^\.]+)$/);
@@ -309,7 +304,7 @@ SteamCommunity.prototype.uploadAvatar = function(image, format, callback) {
return;
}
self.request.post({
self.httpRequestPost({
"uri": "https://steamcommunity.com/actions/FileUploader",
"formData": {
"MAX_FILE_SIZE": buffer.length,
@@ -363,6 +358,6 @@ SteamCommunity.prototype.uploadAvatar = function(image, format, callback) {
if(callback) {
callback(null, body.images.full);
}
});
}, "steamcommunity");
}
};

View File

@@ -16,24 +16,20 @@ SteamCommunity.prototype.enableTwoFactor = function(callback) {
return;
}
// Create a random device ID hash
var hash = require('crypto').createHash('sha1');
hash.update(self.steamID.getSteamID64());
hash = hash.digest('hex');
self.request.post({
self.httpRequestPost({
"uri": "https://api.steampowered.com/ITwoFactorService/AddAuthenticator/v1/",
"form": {
"steamid": self.steamID.getSteamID64(),
"access_token": token,
"authenticator_time": Math.floor(Date.now() / 1000),
"authenticator_type": ETwoFactorTokenType.ValveMobileApp,
"device_identifier": 'android:' + hash,
"device_identifier": SteamTotp.getDeviceID(self.steamID),
"sms_phone_id": "1"
},
"json": true
}, function(err, response, body) {
if(self._checkHttpError(err, response, callback)) {
if (err) {
callback(err);
return;
}
@@ -50,7 +46,7 @@ SteamCommunity.prototype.enableTwoFactor = function(callback) {
}
callback(null, body.response);
});
}, "steamcommunity");
});
};
@@ -65,13 +61,21 @@ SteamCommunity.prototype.finalizeTwoFactor = function(secret, activationCode, ca
return;
}
finalize(token);
SteamTotp.getTimeOffset(function(err, offset, latency) {
if (err) {
callback(err);
return;
}
diff = offset;
finalize(token);
});
});
function finalize(token) {
var code = SteamTotp.generateAuthCode(secret, diff);
self.request.post({
self.httpRequestPost({
"uri": "https://api.steampowered.com/ITwoFactorService/FinalizeAddAuthenticator/v1/",
"form": {
"steamid": self.steamID.getSteamID64(),
@@ -82,7 +86,8 @@ SteamCommunity.prototype.finalizeTwoFactor = function(secret, activationCode, ca
},
"json": true
}, function(err, response, body) {
if(self._checkHttpError(err, response, callback)) {
if (err) {
callback(err);
return;
}
@@ -109,7 +114,7 @@ SteamCommunity.prototype.finalizeTwoFactor = function(secret, activationCode, ca
} else {
callback(null);
}
});
}, "steamcommunity");
}
};
@@ -122,7 +127,7 @@ SteamCommunity.prototype.disableTwoFactor = function(revocationCode, callback) {
return;
}
self.request.post({
self.httpRequestPost({
"uri": "https://api.steampowered.com/ITwoFactorService/RemoveAuthenticator/v1/",
"form": {
"steamid": self.steamID.getSteamID64(),
@@ -132,7 +137,8 @@ SteamCommunity.prototype.disableTwoFactor = function(revocationCode, callback) {
},
"json": true
}, function(err, response, body) {
if(self._checkHttpError(err, response, callback)) {
if (err) {
callback(err);
return;
}
@@ -146,14 +152,8 @@ SteamCommunity.prototype.disableTwoFactor = function(revocationCode, callback) {
return;
}
if(body.response.status == 1) {
callback(null);
return;
}
var error = new Error("Cannot remove authenticator (" + body.response.status + ")");
error.eresult = body.response.status;
callback(error);
});
// success = true means it worked
callback(null);
}, "steamcommunity");
});
};

View File

@@ -1,6 +1,7 @@
var SteamCommunity = require('../index.js');
var SteamID = require('steamid');
var CEconItem = require('../classes/CEconItem.js');
var Helpers = require('./helpers.js');
SteamCommunity.prototype.addFriend = function(userID, callback) {
if(typeof userID === 'string') {
@@ -8,7 +9,7 @@ SteamCommunity.prototype.addFriend = function(userID, callback) {
}
var self = this;
this.request.post({
this.httpRequestPost({
"uri": "https://steamcommunity.com/actions/AddFriendAjax",
"form": {
"accept_invite": 0,
@@ -21,7 +22,8 @@ SteamCommunity.prototype.addFriend = function(userID, callback) {
return;
}
if(self._checkHttpError(err, response, callback)) {
if (err) {
callback(err);
return;
}
@@ -30,7 +32,7 @@ SteamCommunity.prototype.addFriend = function(userID, callback) {
} else {
callback(new Error("Unknown error"));
}
});
}, "steamcommunity");
};
SteamCommunity.prototype.acceptFriendRequest = function(userID, callback) {
@@ -39,7 +41,7 @@ SteamCommunity.prototype.acceptFriendRequest = function(userID, callback) {
}
var self = this;
this.request.post({
this.httpRequestPost({
"uri": "https://steamcommunity.com/actions/AddFriendAjax",
"form": {
"accept_invite": 1,
@@ -51,12 +53,8 @@ SteamCommunity.prototype.acceptFriendRequest = function(userID, callback) {
return;
}
if(self._checkHttpError(err, response, callback)) {
return;
}
callback(null);
});
callback(err || null);
}, "steamcommunity");
};
SteamCommunity.prototype.removeFriend = function(userID, callback) {
@@ -65,7 +63,7 @@ SteamCommunity.prototype.removeFriend = function(userID, callback) {
}
var self = this;
this.request.post({
this.httpRequestPost({
"uri": "https://steamcommunity.com/actions/RemoveFriendAjax",
"form": {
"sessionID": this.getSessionID(),
@@ -76,12 +74,8 @@ SteamCommunity.prototype.removeFriend = function(userID, callback) {
return;
}
if(self._checkHttpError(err, response, callback)) {
return;
}
callback(null);
});
callback(err || null);
}, "steamcommunity");
};
SteamCommunity.prototype.blockCommunication = function(userID, callback) {
@@ -90,7 +84,7 @@ SteamCommunity.prototype.blockCommunication = function(userID, callback) {
}
var self = this;
this.request.post({
this.httpRequestPost({
"uri": "https://steamcommunity.com/actions/BlockUserAjax",
"form": {
"sessionID": this.getSessionID(),
@@ -101,12 +95,8 @@ SteamCommunity.prototype.blockCommunication = function(userID, callback) {
return;
}
if(self._checkHttpError(err, response, callback)) {
return;
}
callback(null);
});
callback(err || null);
}, "steamcommunity");
};
SteamCommunity.prototype.unblockCommunication = function(userID, callback) {
@@ -137,7 +127,7 @@ SteamCommunity.prototype.postUserComment = function(userID, message, callback) {
}
var self = this;
this.request.post({
this.httpRequestPost({
"uri": "https://steamcommunity.com/comment/Profile/post/" + userID.toString() + "/-1",
"form": {
"comment": message,
@@ -150,7 +140,8 @@ SteamCommunity.prototype.postUserComment = function(userID, message, callback) {
return;
}
if(self._checkHttpError(err, response, callback)) {
if (err) {
callback(err);
return;
}
@@ -161,7 +152,7 @@ SteamCommunity.prototype.postUserComment = function(userID, message, callback) {
} else {
callback(new Error("Unknown error"));
}
});
}, "steamcommunity");
};
SteamCommunity.prototype.inviteUserToGroup = function(userID, groupID, callback) {
@@ -170,7 +161,7 @@ SteamCommunity.prototype.inviteUserToGroup = function(userID, groupID, callback)
}
var self = this;
this.request.post({
this.httpRequestPost({
"uri": "https://steamcommunity.com/actions/GroupInvite",
"form": {
"group": groupID.toString(),
@@ -185,7 +176,8 @@ SteamCommunity.prototype.inviteUserToGroup = function(userID, groupID, callback)
return;
}
if(self._checkHttpError(err, response, callback)) {
if (err) {
callback(err);
return;
}
@@ -196,7 +188,33 @@ SteamCommunity.prototype.inviteUserToGroup = function(userID, groupID, callback)
} else {
callback(new Error("Unknown error"));
}
});
}, "steamcommunity");
};
SteamCommunity.prototype.getUserAliases = function(userID, callback) {
if (typeof userID === 'string') {
userID = new SteamID(userID);
}
this.httpRequestGet({
"uri": "https://steamcommunity.com/profiles/" + userID.getSteamID64() + "/ajaxaliases",
"json": true
}, function(err, response, body) {
if (err) {
callback(err);
return;
}
if (typeof body !== 'object') {
callback(new Error("Malformed response"));
return;
}
callback(null, body.map(function(entry) {
entry.timechanged = Helpers.decodeSteamTime(entry.timechanged);
return entry;
}));
}, "steamcommunity");
};
SteamCommunity.prototype.getUserInventoryContexts = function(userID, callback) {
@@ -215,8 +233,9 @@ SteamCommunity.prototype.getUserInventoryContexts = function(userID, callback) {
}
var self = this;
this.request("https://steamcommunity.com/profiles/" + userID.getSteamID64() + "/inventory/", function(err, response, body) {
if(self._checkHttpError(err, response, callback)) {
this.httpRequest("https://steamcommunity.com/profiles/" + userID.getSteamID64() + "/inventory/", function(err, response, body) {
if (err) {
callback(err);
return;
}
@@ -235,13 +254,22 @@ SteamCommunity.prototype.getUserInventoryContexts = function(userID, callback) {
}
callback(null, data);
});
}, "steamcommunity");
};
/**
* Get the contents of a user's inventory context.
* @deprecated Use getUserInventoryContents instead
* @param {SteamID|string} userID - The user's SteamID as a SteamID object or a string which can parse into one
* @param {int} appID - The Steam application ID of the game for which you want an inventory
* @param {int} contextID - The ID of the "context" within the game you want to retrieve
* @param {boolean} tradableOnly - true to get only tradable items and currencies
* @param {function} callback
*/
SteamCommunity.prototype.getUserInventory = function(userID, appID, contextID, tradableOnly, callback) {
var self = this;
if(typeof userID === 'string') {
if (typeof userID === 'string') {
userID = new SteamID(userID);
}
@@ -249,41 +277,50 @@ SteamCommunity.prototype.getUserInventory = function(userID, appID, contextID, t
get([], []);
function get(inventory, currency, start) {
self.request({
self.httpRequest({
"uri": "https://steamcommunity.com" + endpoint + "/inventory/json/" + appID + "/" + contextID,
"headers": {
"Referer": "https://steamcommunity.com" + endpoint + "/inventory"
},
"qs": {
"start": start,
"trading": tradableOnly ? 1 : undefined
},
"json": true
}, function(err, response, body) {
if(self._checkHttpError(err, response, callback)) {
if (err) {
callback(err);
return;
}
if(!body || !body.success || !body.rgInventory || !body.rgDescriptions || !body.rgCurrency) {
callback(new Error(body.Error || "Malformed response"));
if (!body || !body.success || !body.rgInventory || !body.rgDescriptions || !body.rgCurrency) {
if (body) {
callback(new Error(body.Error || "Malformed response"));
} else {
callback(new Error("Malformed response"));
}
return;
}
var i;
for(i in body.rgInventory) {
if(!body.rgInventory.hasOwnProperty(i)) {
for (i in body.rgInventory) {
if (!body.rgInventory.hasOwnProperty(i)) {
continue;
}
inventory.push(new CEconItem(body.rgInventory[i], body.rgDescriptions, contextID));
}
for(i in body.rgCurrency) {
if(!body.rgCurrency.hasOwnProperty(i)) {
for (i in body.rgCurrency) {
if (!body.rgCurrency.hasOwnProperty(i)) {
continue;
}
currency.push(new CEconItem(body.rgInventory[i], body.rgDescriptions, contextID));
}
if(body.more) {
if (body.more) {
var match = response.request.uri.href.match(/\/(profiles|id)\/([^\/]+)\//);
if(match) {
endpoint = "/" + match[1] + "/" + match[2];
@@ -293,6 +330,98 @@ SteamCommunity.prototype.getUserInventory = function(userID, appID, contextID, t
} else {
callback(null, inventory, currency);
}
});
}, "steamcommunity");
}
};
/**
* Get the contents of a user's inventory context.
* @param {SteamID|string} userID - The user's SteamID as a SteamID object or a string which can parse into one
* @param {int} appID - The Steam application ID of the game for which you want an inventory
* @param {int} contextID - The ID of the "context" within the game you want to retrieve
* @param {boolean} tradableOnly - true to get only tradable items and currencies
* @param {function} callback
*/
SteamCommunity.prototype.getUserInventoryContents = function(userID, appID, contextID, tradableOnly, callback) {
var self = this;
if(typeof userID === 'string') {
userID = new SteamID(userID);
}
var pos = 1;
get([], []);
function get(inventory, currency, start) {
self.httpRequest({
"uri": "https://steamcommunity.com/inventory/" + userID.getSteamID64() + "/" + appID + "/" + contextID,
"headers": {
"Referer": "https://steamcommunity.com/profiles/" + userID.getSteamID64() + "/inventory"
},
"qs": {
"l": "english", // Default language
"count": 5000, // Max items per 'page'
"start_assetid": start
},
"json": true
}, function(err, response, body) {
if (err) {
if (err.message == "HTTP error 403" && body === null) {
// 403 with a body of "null" means the inventory/profile is private.
callback(new Error("This profile is private."));
return;
}
callback(err);
return;
}
if (!body || !body.success || !body.assets || !body.descriptions) {
if (body) {
// Dunno if the error/Error property even exists on this new endpoint
callback(new Error(body.error || body.Error || "Malformed response"));
} else {
callback(new Error("Malformed response"));
}
return;
}
for (var i = 0; i < body.assets.length; i++) {
var description = getDescription(body.descriptions, body.assets[i].classid, body.assets[i].instanceid);
if (!tradableOnly || (description && description.tradable)) {
body.assets[i].pos = pos++;
(body.assets[i].currencyid ? currency : inventory).push(new CEconItem(body.assets[i], description, contextID));
}
}
if (body.more_items) {
get(inventory, currency, body.last_assetid);
} else {
callback(null, inventory, currency, body.total_inventory_count);
}
}, "steamcommunity");
}
// A bit of optimization; objects are hash tables so it's more efficient to look up by key than to iterate an array
var quickDescriptionLookup = {};
function getDescription(descriptions, classID, instanceID) {
instanceID = instanceID || '0'; // instanceID can be undefined, in which case it's 0.
var key = classID + '_' + instanceID;
if (quickDescriptionLookup[key]) {
return quickDescriptionLookup[key];
}
for (var i = 0; i < descriptions.length; i++) {
quickDescriptionLookup[key] = descriptions[i];
if (descriptions[i].classid == classID && descriptions[i].instanceid == instanceID) {
return descriptions[i];
}
}
}
};

View File

@@ -2,11 +2,12 @@ var SteamCommunity = require('../index.js');
SteamCommunity.prototype.getWebApiKey = function(domain, callback) {
var self = this;
this.request({
"uri": "https://steamcommunity.com/dev/apikey",
this.httpRequest({
"uri": "https://steamcommunity.com/dev/apikey?l=english",
"followRedirect": false
}, function(err, response, body) {
if(self._checkHttpError(err, response, callback)) {
if (err) {
callback(err);
return;
}
@@ -20,7 +21,7 @@ SteamCommunity.prototype.getWebApiKey = function(domain, callback) {
callback(null, match[1]);
} else {
// We need to register a new API key
self.request.post('https://steamcommunity.com/dev/registerkey', {
self.httpRequestPost('https://steamcommunity.com/dev/registerkey?l=english', {
"form": {
"domain": domain,
"agreeToTerms": "agreed",
@@ -28,14 +29,15 @@ SteamCommunity.prototype.getWebApiKey = function(domain, callback) {
"Submit": "Register"
}
}, function(err, response, body) {
if(self._checkHttpError(err, response, callback)) {
if (err) {
callback(err);
return;
}
self.getWebApiKey(domain, callback);
});
}, "steamcommunity");
}
});
}, "steamcommunity");
};
SteamCommunity.prototype.getWebApiOauthToken = function(callback) {
@@ -46,12 +48,9 @@ SteamCommunity.prototype.getWebApiOauthToken = function(callback) {
}
// Pull an oauth token from the webchat UI
this.request("https://steamcommunity.com/chat", function(err, response, body) {
if(self._checkHttpError(err, response, callback)) {
return;
}
if(self._checkCommunityError(body, callback)) {
this.httpRequest("https://steamcommunity.com/chat", function(err, response, body) {
if (err) {
callback(err);
return;
}
@@ -62,5 +61,5 @@ SteamCommunity.prototype.getWebApiOauthToken = function(callback) {
}
callback(null, match[1]);
});
}, "steamcommunity");
};

View File

@@ -0,0 +1,61 @@
var SteamCommunity = require('../index.js');
var ReadLine = require('readline');
var fs = require('fs');
var community = new SteamCommunity();
var rl = ReadLine.createInterface({
"input": process.stdin,
"output": process.stdout
});
rl.question("Username: ", function(accountName) {
rl.question("Password: ", function(password) {
rl.question("Two-Factor Auth Code: ", function(authCode) {
rl.question("Revocation Code: R", function(rCode) {
doLogin(accountName, password, authCode, "", rCode);
});
});
});
});
function doLogin(accountName, password, authCode, captcha, rCode) {
community.login({
"accountName": accountName,
"password": password,
"twoFactorCode": authCode,
"captcha": captcha
}, function(err, sessionID, cookies, steamguard) {
if(err) {
if(err.message == 'SteamGuard') {
console.log("This account does not have two-factor authentication enabled.");
process.exit();
return;
}
if(err.message == 'CAPTCHA') {
console.log(err.captchaurl);
rl.question("CAPTCHA: ", function(captchaInput) {
doLogin(accountName, password, authCode, captchaInput);
});
return;
}
console.log(err);
process.exit();
return;
}
console.log("Logged on!");
community.disableTwoFactor("R" + rCode, function(err) {
if(err) {
console.log(err);
process.exit();
return;
}
console.log("Two-factor authentication disabled!");
process.exit();
});
});
}

View File

@@ -14,12 +14,13 @@ rl.question("Username: ", function(accountName) {
});
});
function doLogin(accountName, password, authCode, twoFactorCode) {
function doLogin(accountName, password, authCode, twoFactorCode, captcha) {
community.login({
"accountName": accountName,
"password": password,
"authCode": authCode,
"twoFactorCode": twoFactorCode
"twoFactorCode": twoFactorCode,
"captcha": captcha
}, function(err, sessionID, cookies, steamguard) {
if(err) {
if(err.message == 'SteamGuardMobile') {
@@ -39,6 +40,15 @@ function doLogin(accountName, password, authCode, twoFactorCode) {
return;
}
if(err.message == 'CAPTCHA') {
console.log(err.captchaurl);
rl.question("CAPTCHA: ", function(captchaInput) {
doLogin(accountName, password, authCode, twoFactorCode, captchaInput);
});
return;
}
console.log(err);
process.exit();
return;

View File

@@ -14,11 +14,12 @@ rl.question("Username: ", function(accountName) {
});
});
function doLogin(accountName, password, authCode) {
function doLogin(accountName, password, authCode, captcha) {
community.login({
"accountName": accountName,
"password": password,
"authCode": authCode
"authCode": authCode,
"captcha": captcha
}, function(err, sessionID, cookies, steamguard) {
if(err) {
if(err.message == 'SteamGuardMobile') {
@@ -29,13 +30,22 @@ function doLogin(accountName, password, authCode) {
if(err.message == 'SteamGuard') {
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);
});
return;
}
if(err.message == 'CAPTCHA') {
console.log(err.captchaurl);
rl.question("CAPTCHA: ", function(captchaInput) {
doLogin(accountName, password, authCode, captchaInput);
});
return;
}
console.log(err);
process.exit();
return;

294
index.js
View File

@@ -10,12 +10,19 @@ require('util').inherits(SteamCommunity, require('events').EventEmitter);
module.exports = SteamCommunity;
SteamCommunity.SteamID = SteamID;
SteamCommunity.ConfirmationType = {
// 1 is unknown, possibly "Invalid"
"Trade": 2,
"MarketListing": 3
// 4 is opt-out or other like account confirmation?
};
function SteamCommunity(options) {
options = options || {};
this._jar = Request.jar();
this._captchaGid = -1;
this._httpRequestID = 0;
this.chatState = SteamCommunity.ChatState.Offline;
var defaults = {
@@ -42,20 +49,23 @@ function SteamCommunity(options) {
this.request = this.request.defaults(defaults);
// English
this._jar.setCookie(Request.cookie('Steam_Language=english'), 'https://steamcommunity.com');
this._setCookie(Request.cookie('Steam_Language=english'));
// UTC
this._jar.setCookie(Request.cookie('timezoneOffset=0,0'), 'https://steamcommunity.com');
this._setCookie(Request.cookie('timezoneOffset=0,0'));
}
SteamCommunity.prototype.login = function(details, callback) {
if(details.steamguard) {
var parts = details.steamguard.split('||');
this._jar.setCookie(Request.cookie('steamMachineAuth' + parts[0] + '=' + encodeURIComponent(parts[1])), 'https://steamcommunity.com');
this._setCookie(Request.cookie('steamMachineAuth' + parts[0] + '=' + encodeURIComponent(parts[1])), true);
}
var self = this;
// Delete the cache
delete self._profileURL;
// headers required to convince steam that we're logging in from a mobile device so that we can get the oAuth data
var mobileHeaders = {
"X-Requested-With": "com.valvesoftware.android.steam.community",
@@ -64,89 +74,82 @@ SteamCommunity.prototype.login = function(details, callback) {
"Accept": "text/javascript, text/html, application/xml, text/xml, */*"
};
this._jar.setCookie(Request.cookie("mobileClientVersion=0 (2.1.3)"), "https://steamcommunity.com");
this._jar.setCookie(Request.cookie("mobileClient=android"), "https://steamcommunity.com");
this._setCookie(Request.cookie("mobileClientVersion=0 (2.1.3)"));
this._setCookie(Request.cookie("mobileClient=android"));
this.request.post("https://steamcommunity.com/login/getrsakey/", {
"form": {
"username": details.accountName
},
"headers": mobileHeaders
this.httpRequestPost("https://steamcommunity.com/login/getrsakey/", {
"form": {"username": details.accountName},
"headers": mobileHeaders,
"json": true
}, function(err, response, body) {
// Remove the mobile cookies
if(err) {
if (err) {
deleteMobileCookies();
callback(err);
return;
}
var json;
try {
json = JSON.parse(body);
} catch(e) {
deleteMobileCookies();
callback(e);
return;
}
if(!json.publickey_mod || !json.publickey_exp) {
if(!body.publickey_mod || !body.publickey_exp) {
deleteMobileCookies();
callback(new Error("Invalid RSA key received"));
return;
}
var key = new RSA();
key.setPublic(json.publickey_mod, json.publickey_exp);
key.setPublic(body.publickey_mod, body.publickey_exp);
var form = {
"captcha_text": details.captcha || "",
"captchagid": self._captchaGid,
"emailauth": details.authCode || "",
"emailsteamid": "",
"password": hex2b64(key.encrypt(details.password)),
"remember_login": "true",
"rsatimestamp": json.timestamp,
"twofactorcode": details.twoFactorCode || "",
"username": details.accountName,
"oauth_client_id": "DE45CD61",
"oauth_scope": "read_profile write_profile read_client write_client",
"loginfriendlyname": "#login_emailauth_friendlyname_mobile"
};
self.request.post({
self.httpRequestPost({
"uri": "https://steamcommunity.com/login/dologin/",
"json": true,
"form": form,
"form": {
"captcha_text": details.captcha || "",
"captchagid": self._captchaGid,
"emailauth": details.authCode || "",
"emailsteamid": "",
"password": hex2b64(key.encrypt(details.password)),
"remember_login": "true",
"rsatimestamp": body.timestamp,
"twofactorcode": details.twoFactorCode || "",
"username": details.accountName,
"oauth_client_id": "DE45CD61",
"oauth_scope": "read_profile write_profile read_client write_client",
"loginfriendlyname": "#login_emailauth_friendlyname_mobile",
"donotcache": Date.now()
},
"headers": mobileHeaders
}, function(err, response, body) {
deleteMobileCookies();
if(self._checkHttpError(err, response, callback)) {
if (err) {
callback(err);
return;
}
var error;
if(!body.success && body.emailauth_needed) {
// Steam Guard (email)
var error = new Error("SteamGuard");
error = new Error("SteamGuard");
error.emaildomain = body.emaildomain;
callback(error);
} else if(!body.success && body.requires_twofactor) {
// Steam Guard (app)
callback(new Error("SteamGuardMobile"));
} else if(!body.success && body.captcha_needed) {
var error = new Error("CAPTCHA");
error.captchaurl = "https://steamcommunity.com/public/captcha.php?gid=" + body.captcha_gid;
} else if(!body.success && body.captcha_needed && body.message.match(/Please verify your humanity/)) {
error = new Error("CAPTCHA");
error.captchaurl = "https://steamcommunity.com/login/rendercaptcha/?gid=" + body.captcha_gid;
self._captchaGid = body.captcha_gid;
callback(error);
} else if(!body.success) {
callback(new Error(body.message || "Unknown error"));
} else if(!body.oauth) {
callback(new Error("Malformed response"));
} else {
var sessionID = generateSessionID();
var oAuth = JSON.parse( body.oauth );
self._jar.setCookie(Request.cookie('sessionid=' + sessionID), 'http://steamcommunity.com');
self._setCookie(Request.cookie('sessionid=' + sessionID));
self.steamID = new SteamID(oAuth.steamid);
self.oAuthToken = oAuth.oauth_token;
@@ -164,20 +167,22 @@ SteamCommunity.prototype.login = function(details, callback) {
break;
}
}
self.setCookies(cookies);
callback(null, sessionID, cookies, steamguard, oAuth.oauth_token);
}
});
});
}, "steamcommunity");
}, "steamcommunity");
function deleteMobileCookies() {
var cookie = Request.cookie('mobileClientVersion=');
cookie.expires = new Date(0);
self._jar.setCookie(cookie, "https://steamcommunity.com");
self._setCookie(cookie);
cookie = Request.cookie('mobileClient=');
cookie.expires = new Date(0);
self._jar.setCookie(cookie, "https://steamcommunity.com");
self._setCookie(cookie);
}
};
@@ -186,14 +191,15 @@ SteamCommunity.prototype.oAuthLogin = function(steamguard, token, callback) {
var steamID = new SteamID(steamguard[0]);
var self = this;
this.request.post({
this.httpRequestPost({
"uri": "https://api.steampowered.com/IMobileAuthService/GetWGToken/v1/",
"form": {
"access_token": token
},
"json": true
}, function(err, response, body) {
if(self._checkHttpError(err, response, callback)) {
if (err) {
callback(err);
return;
}
@@ -211,7 +217,16 @@ SteamCommunity.prototype.oAuthLogin = function(steamguard, token, callback) {
self.setCookies(cookies);
callback(null, self.getSessionID(), cookies);
});
}, "steamcommunity");
};
SteamCommunity.prototype._setCookie = function(cookie, secure) {
var protocol = secure ? "https" : "http";
cookie.secure = !!secure;
this._jar.setCookie(cookie.clone(), protocol + "://steamcommunity.com");
this._jar.setCookie(cookie.clone(), protocol + "://store.steampowered.com");
this._jar.setCookie(cookie.clone(), protocol + "://help.steampowered.com");
};
SteamCommunity.prototype.setCookies = function(cookies) {
@@ -221,8 +236,8 @@ SteamCommunity.prototype.setCookies = function(cookies) {
if(cookieName == 'steamLogin') {
self.steamID = new SteamID(cookie.match(/=(\d+)/)[1]);
}
self._jar.setCookie(Request.cookie(cookie), (cookieName.match(/^steamMachineAuth/) || cookieName.match(/Secure$/) ? "https://" : "http://") + "steamcommunity.com");
self._setCookie(Request.cookie(cookie), !!(cookieName.match(/^steamMachineAuth/) || cookieName.match(/Secure$/)));
});
};
@@ -236,7 +251,7 @@ SteamCommunity.prototype.getSessionID = function() {
}
var sessionID = generateSessionID();
this._jar.setCookie(Request.cookie('sessionid=' + sessionID), "http://steamcommunity.com");
this._setCookie(Request.cookie('sessionid=' + sessionID));
return sessionID;
};
@@ -245,7 +260,9 @@ function generateSessionID() {
}
SteamCommunity.prototype.parentalUnlock = function(pin, callback) {
this.request.post("https://steamcommunity.com/parental/ajaxunlock", {
var self = this;
this.httpRequestPost("https://steamcommunity.com/parental/ajaxunlock", {
"json": true,
"form": {
"pin": pin
@@ -255,75 +272,76 @@ SteamCommunity.prototype.parentalUnlock = function(pin, callback) {
return;
}
if(self._checkHttpError(err, response, callback)) {
if (err) {
callback(err);
return;
}
if(!body || typeof body.success !== 'boolean') {
return callback("Invalid response");
callback("Invalid response");
return;
}
if(!body.success) {
return callback("Incorrect PIN");
callback("Incorrect PIN");
return;
}
callback();
}.bind(this));
}.bind(this), "steamcommunity");
};
SteamCommunity.prototype.getNotifications = function(callback) {
var self = this;
this.request.get("https://steamcommunity.com/actions/RefreshNotificationArea", function(err, response, body) {
if(self._checkHttpError(err, response, callback)) {
this.httpRequestGet({
"uri": "https://steamcommunity.com/actions/GetNotificationCounts",
"json": true
}, function(err, response, body) {
if (err) {
callback(err);
return;
}
if (!body || !body.notifications) {
callback(new Error("Malformed response"));
return;
}
var notifications = {
"comments": 0,
"items": 0,
"invites": 0,
"gifts": 0,
"chat": 0,
"trades": 0
"trades": body.notifications[1] || 0,
"gameTurns": body.notifications[2] || 0,
"moderatorMessages": body.notifications[3] || 0,
"comments": body.notifications[4] || 0,
"items": body.notifications[5] || 0,
"invites": body.notifications[6] || 0,
// dunno about 7
"gifts": body.notifications[8] || 0,
"chat": body.notifications[9] || 0,
"helpRequestReplies": body.notifications[10] || 0,
"accountAlerts": body.notifications[11] || 0
};
var items = {
"comments": /(\d+) new comments?/,
"items": /(\d+) new items? in your inventory/,
"invites": /(\d+) new invites?/,
"gifts": /(\d+) new gifts?/,
"chat": /(\d+) unread chat messages?/,
"trades": /(\d+) new trade notifications?/
};
var match;
for(var i in items) {
if(match = body.match(items[i])) {
notifications[i] = parseInt(match[1], 10);
}
}
callback(null, notifications);
});
}, "steamcommunity");
};
SteamCommunity.prototype.resetItemNotifications = function(callback) {
var self = this;
this.request.get("https://steamcommunity.com/my/inventory", function(err, response, body) {
this.httpRequestGet("https://steamcommunity.com/my/inventory", function(err, response, body) {
if(!callback) {
return;
}
if(self._checkHttpError(err, response, callback)) {
return;
}
callback(null);
});
callback(err || null);
}, "steamcommunity");
};
SteamCommunity.prototype.loggedIn = function(callback) {
this.request("https://steamcommunity.com/my", {"followRedirect": false}, function(err, response, body) {
this.httpRequestGet({
"uri": "https://steamcommunity.com/my",
"followRedirect": false,
"checkHttpError": false
}, function(err, response, body) {
if(err || (response.statusCode != 302 && response.statusCode != 403)) {
callback(err || new Error("HTTP error " + response.statusCode));
return;
@@ -335,58 +353,52 @@ SteamCommunity.prototype.loggedIn = function(callback) {
}
callback(null, !!response.headers.location.match(/steamcommunity\.com(\/(id|profiles)\/[^\/]+)\/?/), false);
});
};
SteamCommunity.prototype._checkCommunityError = function(html, callback) {
if(html.match(/<h1>Sorry!<\/h1>/)) {
var match = html.match(/<h3>(.+)<\/h3>/);
callback(new Error(match ? match[1] : "Unknown error occurred"));
return true;
}
return false;
}, "steamcommunity");
};
SteamCommunity.prototype._myProfile = function(endpoint, form, callback) {
var self = this;
this.request("https://steamcommunity.com/my", {"followRedirect": false}, function(err, response, body) {
if(err || response.statusCode != 302) {
callback(err || "HTTP error " + response.statusCode);
return;
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;
}
var 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);
completeRequest(match[1]);
}, "steamcommunity");
}
function completeRequest(url) {
var options = {
"uri": "https://steamcommunity.com" + url + "/" + endpoint,
"method": "GET"
};
if (form) {
options.method = "POST";
options.form = form;
}
var match = response.headers.location.match(/steamcommunity\.com(\/(id|profiles)\/[^\/]+)\/?/);
if(!match) {
callback(new Error("Can't get profile URL"));
return;
}
(form ? self.request.post : self.request)("https://steamcommunity.com" + match[1] + "/" + endpoint, form ? {"form": form} : {}, callback);
});
};
SteamCommunity.prototype._checkHttpError = function(err, response, callback) {
if(err) {
callback(err);
return true;
}
if(response.statusCode >= 300 && response.statusCode <= 399 && response.headers.location.indexOf('/login') != -1) {
callback(new Error("Not Logged In"));
return true;
}
if(response.statusCode >= 400) {
var error = new Error("HTTP error " + response.statusCode);
error.code = response.statusCode;
callback(error);
return true;
}
return false;
self.httpRequest(options, callback, "steamcommunity");
}
};
require('./components/http.js');
require('./components/chat.js');
require('./components/profile.js');
require('./components/market.js');

View File

@@ -1,6 +1,6 @@
{
"name": "steamcommunity",
"version": "3.18.2",
"version": "3.30.0",
"description": "Provides an interface for logging into and interacting with the Steam Community website",
"keywords": ["steam", "steam community"],
"homepage": "https://github.com/DoctorMcKay/node-steamcommunity",
@@ -15,10 +15,13 @@
"dependencies": {
"request": "^2.61.0",
"node-bignumber": "^1.2.1",
"steamid": "^0.3.1",
"steamid": "^1.0.0",
"xml2js": "^0.4.11",
"cheerio": "^0.19.0",
"cheerio": "0.19.0",
"async": "^1.4.2",
"steam-totp": "^1.3.0"
},
"engines": {
"node": ">=4.0.0"
}
}
}