This repository has been archived by the owner on Mar 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
index.js
423 lines (358 loc) · 12 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
module.exports = SteamTrade;
var request = require('request');
require('util').inherits(SteamTrade, require('events').EventEmitter);
function SteamTrade() {
require('events').EventEmitter.call(this);
this._j = request.jar();
this._request = request.defaults({jar:this._j});
}
SteamTrade.prototype._loadForeignInventory = function(appid, contextid) {
if (!this._themInventories[appid]) {
this._themInventories[appid] = {};
}
if (!this._themInventories[appid][contextid]) {
this._themInventories[appid][contextid] = {};
}
var self = this;
this._request.get({
uri: 'http://steamcommunity.com/trade/' + this.tradePartnerSteamID + '/foreigninventory?' + require('querystring').stringify({
sessionid: this.sessionID,
steamid: this.tradePartnerSteamID,
appid: appid,
contextid: contextid
}),
headers: {
referer: 'http://steamcommunity.com/trade/1'
},
json: true
}, function continueFullInventoryRequestIfNecessary(error, response, body) {
if (error) {
self.emit('debug', 'loading inventory: ' + error);
// retry
self._loadForeignInventory(appid, contextid);
return;
}
for (var id in body.rgInventory) {
var item = self._themInventories[appid][contextid][id] = body.rgInventory[id];
var description = body.rgDescriptions[item.classid + '_' + item.instanceid];
for (var key in description) {
item[key] = description[key];
}
}
if (body.more) {
self.emit('debug', 'loading inventory: continuing from ' + body.more_start);
self._request.get({
uri: 'http://steamcommunity.com/trade/' + self.tradePartnerSteamID + '/foreigninventory?' + require('querystring').stringify({
sessionid: self.sessionID,
steamid: self.tradePartnerSteamID,
appid: appid,
contextid: contextid,
start: body.more_start
}),
headers: {
referer: 'http://steamcommunity.com/trade/1'
},
json: true
}, continueFullInventoryRequestIfNecessary);
return;
}
self._loadingInventoryData = false;
});
};
SteamTrade.prototype._onTradeStatusUpdate = function(body, callback) {
clearTimeout(this._timerTradePoll);
var self = this;
if (body.trade_status > 0) {
if (callback) {
// callback before emitting events
callback(body);
}
if (body.trade_status == 1) {
this.emit('end', 'complete', function getItems(callback) {
self._request.get('http://steamcommunity.com/trade/' + body.tradeid + '/receipt/', function(error, response, body) {
if (error || response.statusCode != 200) {
self.emit('debug', 'Opening receipt page: ' + (error || response.statusCode));
getItems(callback);
return;
}
var script = body.match(/(var oItem;[\s\S]*)<\/script>/);
if (!script) {
// no session
callback();
return;
}
var items = [];
// prepare to execute the script in the page
var UserYou;
function BuildHover(str, item) {
items.push(item);
}
function $() {
return {
show: function() {}
};
}
// evil magic happens here
eval(script[1]);
callback(items);
});
});
} else {
this.emit('end', {
2: 'empty', // happens when both parties confirm a trade with no items on either side
3: 'cancelled',
4: 'timeout',
5: 'failed',
6: 'pending',
}[body.trade_status], body.tradeid);
}
delete this.tradePartnerSteamID;
return;
}
this._timerTradePoll = setTimeout(function() {
self._send('tradestatus', {
logpos: self._nextLogPos,
version: self._version
}, function(status) {
// account for { trade_status: 2, success: false } which is not an error
if (!status.success && !status.trade_status) {
// assume session lost, stop polling
self.emit('debug', JSON.stringify(status));
clearTimeout(self._timerTradePoll);
var err = new Error('Invalid cookie');
self.emit('error', err);
}
});
}, 1000);
if (body.newversion)
// we can update our own assets safely
this._meAssets = body.me.assets || []; // Valve uses '' to denote an empty array
if (callback) {
// callback now, otherwise we might return (loading inventory) and never get there
callback(body);
}
if (this._loadingInventoryData) {
// we'll receive the same events again
return;
}
var ready = false;
// events might be undefined, but it's fine
for (var i in body.events) {
if (i < this._nextLogPos)
continue;
var event = body.events[i];
if (event.steamid != this.tradePartnerSteamID)
continue; // not interested in our own actions
switch (event.action) {
case '0':
case '1':
var inventory = this._themInventories[event.appid] && this._themInventories[event.appid][event.contextid];
if (!inventory) {
this._loadForeignInventory(event.appid, event.contextid);
this._loadingInventoryData = true;
return;
}
this.emit('offerChanged', event.action == '0', inventory[event.assetid]);
break;
case '2':
// defer 'ready' event until we've handled anything else
ready = true;
break;
case '3':
ready = false;
this.emit('unready');
break;
case '7':
this.emit('chatMsg', event.text);
}
}
if (i >= this._nextLogPos)
this._nextLogPos = ++i;
if (body.newversion) {
// now that we know we have all inventories, we can update their assets too
// it can be '', [item, item], or {'1': item, '3': item}
this.themAssets = body.them.assets ? Object.keys(body.them.assets).map(function(key) {
var item = body.them.assets[key];
return self._themInventories[item.appid][item.contextid][item.assetid];
}) : [];
this._version = body.version;
}
if (ready)
this.emit('ready');
};
SteamTrade.prototype._send = function(action, data, callback) {
clearTimeout(this._timerTradePoll);
data.sessionid = this.sessionID;
var self = this;
this._request.post({
uri: 'http://steamcommunity.com/trade/' + this.tradePartnerSteamID + '/' + action,
headers: {
referer: 'http://steamcommunity.com/trade/1'
},
form: data,
json: true
}, function(error, response, body) {
if (!self.tradePartnerSteamID) {
// trade is over already
return;
}
if (error || response.statusCode != 200) {
self.emit('debug', 'sending ' + action + ': ' + (error || response.statusCode));
// retry
self._send(action, data, callback);
return;
}
self._onTradeStatusUpdate(body, callback);
return;
});
};
SteamTrade.prototype.setCookie = function(cookie) {
this._j.setCookie(request.cookie(cookie), 'http://steamcommunity.com');
};
SteamTrade.prototype.open = function(steamID, callback) {
this.tradePartnerSteamID = steamID;
this.themAssets = [];
this._themInventories = {};
this._meAssets = [];
this._nextLogPos = 0;
this._version = 1;
this._send('tradestatus', {
logpos: this._nextLogPos,
version: this._version
}, callback);
};
SteamTrade.prototype.getContexts = function(callback) {
this._request.get('http://steamcommunity.com/trade/' + this.tradePartnerSteamID, function(error, response, body) {
var appContextData = body.match(/var g_rgAppContextData = (.*);/);
callback(appContextData && JSON.parse(appContextData[1]));
});
};
SteamTrade.prototype.loadInventory = function(appid, contextid, callback) {
var inventory = [];
this._request.get({
uri: 'http://steamcommunity.com/my/inventory/json/' + appid + '/' + contextid,
json: true
}, function continueFullInventoryRequestIfNecessary(error, response, body) {
if (error || response.statusCode != 200 || typeof body == 'object' && !body.success) {
this.emit('debug', 'loading my inventory: ' + (error || (response.statusCode != 200 ? response.statusCode : JSON.stringify(body))));
this.loadInventory(appid, contextid, callback);
return;
}
if (typeof body != 'object') {
// no session
callback();
return;
}
inventory = inventory
.concat(mergeWithDescriptions(body.rgInventory, body.rgDescriptions, contextid))
.concat(mergeWithDescriptions(body.rgCurrency, body.rgDescriptions, contextid));
if (body.more) {
this.emit('debug', 'loading my inventory: continuing from ' + body.more_start);
this._request.get({
uri: 'http://steamcommunity.com/my/inventory/json/' + appid + '/' + contextid + '?start=' + body.more_start,
json: true
}, continueFullInventoryRequestIfNecessary.bind(this));
} else {
callback(inventory);
}
}.bind(this));
};
function mergeWithDescriptions(items, descriptions, contextid) {
return Object.keys(items).map(function(id) {
var item = items[id];
var description = descriptions[item.classid + '_' + (item.instanceid || '0')];
for (var key in description) {
item[key] = description[key];
}
// add contextid because Steam is retarded
item.contextid = contextid;
return item;
});
}
SteamTrade.prototype.addItem = function(item, callback) {
// find first free slot
for (var slot = 0; slot in this._meAssets; slot++);
this._meAssets[slot] = item; // prevent using this slot at least until the next version
this._send(item.is_currency ? 'setcurrency' : 'additem', {
appid: item.appid,
contextid: item.contextid,
itemid: item.id,
currencyid: item.id,
slot: slot,
amount: item.amount
}, callback);
};
SteamTrade.prototype.addItems = function(items, callback) {
var count = items.length;
var slot = 0;
var results = [];
items.forEach(function(item, index) {
// find first free slot
for (; slot in this._meAssets; slot++);
this._meAssets[slot] = item; // prevent using this slot at least until the next version
this._send(item.is_currency ? 'setcurrency' : 'additem', {
appid: item.appid,
contextid: item.contextid,
itemid: item.id,
currencyid: item.id,
slot: slot++, // it's taken tentatively
amount: item.amount
}, function(res) {
results[index] = res;
if (!--count) {
callback && callback(results);
}
});
}.bind(this));
};
SteamTrade.prototype.removeItem = function(item, callback) {
this._send('removeitem', {
appid: item.appid,
contextid: item.contextid,
itemid: item.id
}, callback);
};
SteamTrade.prototype.ready = function(callback) {
this._send('toggleready', {
version: this._version,
ready: true
}, callback);
};
SteamTrade.prototype.unready = function(callback) {
this._send('toggleready', {
version: this._version,
ready: false
}, callback);
};
SteamTrade.prototype.confirm = function(callback) {
this._send('confirm', {
logpos: this._nextLogPos,
version: this._version
}, function(status) {
// sometimes Steam is dumb and ignores the confirm for no apparent reason
// so we'll have to resend the confirm if this one failed
// but only if it _should_ have worked
if (status.trade_status === 0 && !status.me.confirmed && status.me.ready && status.them.ready) {
// this.emit('debug', 'Steam dumbed');
this.confirm(callback);
return;
}
callback && callback(status);
}.bind(this));
};
SteamTrade.prototype.cancel = function(callback) {
this._send('cancel', {}, function(res) {
if (res.success) {
// stop polling
delete this.tradePartnerSteamID;
}
callback && callback(res);
}.bind(this));
};
SteamTrade.prototype.chatMsg = function(msg, callback) {
this._send('chat', {
message: msg,
logpos: this._nextLogPos,
version: this._version
}, callback);
};