-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
263 lines (206 loc) · 8.07 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
global._mckay_statistics_opt_out = true; // Opt out of node-steam-user stats
const optionDefinitions = [
{ name: 'config', alias: 'c', type: String, defaultValue: './config.js' }, // Config file location
{ name: 'steam_data', alias: 's', type: String } // Steam data directory
];
const winston = require('winston'),
args = require('command-line-args')(optionDefinitions),
bodyParser = require('body-parser'),
rateLimit = require('express-rate-limit'),
utils = require('./lib/utils'),
queue = new (require('./lib/queue'))(),
InspectURL = require('./lib/inspect_url'),
botController = new (require('./lib/bot_controller'))(),
CONFIG = require(args.config),
postgres = new (require('./lib/postgres'))(CONFIG.database_url, CONFIG.enable_bulk_inserts),
gameData = new (require('./lib/game_data'))(CONFIG.game_files_update_interval, CONFIG.enable_game_file_updates),
errors = require('./errors'),
Job = require('./lib/job');
if (CONFIG.max_simultaneous_requests === undefined) {
CONFIG.max_simultaneous_requests = 1;
}
winston.level = CONFIG.logLevel || 'debug';
if (CONFIG.logins.length === 0) {
console.log('There are no bot logins. Please add some in config.json');
process.exit(1);
}
if (args.steam_data) {
CONFIG.bot_settings.steam_user.dataDirectory = args.steam_data;
}
for (let loginData of CONFIG.logins) {
botController.addBot(loginData, CONFIG.bot_settings);
}
postgres.connect();
// Setup and configure express
const app = require('express')();
app.use(function (req, res, next) {
if (req.method === 'POST') {
// Default content-type
req.headers['content-type'] = 'application/json';
}
next();
});
app.use(bodyParser.json({limit: '5mb'}));
app.use(function (error, req, res, next) {
// Handle bodyParser errors
if (error instanceof SyntaxError) {
errors.BadBody.respond(res);
}
else next();
});
if (CONFIG.trust_proxy === true) {
app.enable('trust proxy');
}
CONFIG.allowed_regex_origins = CONFIG.allowed_regex_origins || [];
CONFIG.allowed_origins = CONFIG.allowed_origins || [];
const allowedRegexOrigins = CONFIG.allowed_regex_origins.map((origin) => new RegExp(origin));
async function handleJob(job) {
// See which items have already been cached
const itemData = await postgres.getItemData(job.getRemainingLinks().map(e => e.link));
for (let item of itemData) {
const link = job.getLink(item.a);
if (!item.price && link.price) {
postgres.updateItemPrice(item.a, link.price);
}
gameData.addAdditionalItemProperties(item);
item = utils.removeNullValues(item);
job.setResponse(item.a, item);
}
if (!botController.hasBotOnline()) {
return job.setResponseRemaining(errors.SteamOffline);
}
if (CONFIG.max_simultaneous_requests > 0 &&
(queue.getUserQueuedAmt(job.ip) + job.remainingSize()) > CONFIG.max_simultaneous_requests) {
return job.setResponseRemaining(errors.MaxRequests);
}
if (job.remainingSize() > 0) {
queue.addJob(job, CONFIG.bot_settings.max_attempts);
}
}
function canSubmitPrice(key, link, price) {
return CONFIG.price_key && key === CONFIG.price_key && price && link.isMarketLink() && utils.isOnlyDigits(price);
}
app.use(function (req, res, next) {
if (CONFIG.allowed_origins.length > 0 && req.get('origin') != undefined) {
// check to see if its a valid domain
const allowed = CONFIG.allowed_origins.indexOf(req.get('origin')) > -1 ||
allowedRegexOrigins.findIndex((reg) => reg.test(req.get('origin'))) > -1;
if (allowed) {
res.header('Access-Control-Allow-Origin', req.get('origin'));
res.header('Access-Control-Allow-Methods', 'GET');
}
}
next()
});
if (CONFIG.rate_limit && CONFIG.rate_limit.enable) {
app.use(rateLimit({
windowMs: CONFIG.rate_limit.window_ms,
max: CONFIG.rate_limit.max,
headers: false,
handler: function (req, res) {
errors.RateLimit.respond(res);
}
}))
}
app.get('/', function(req, res) {
// Get and parse parameters
let link;
if ('url' in req.query) {
link = new InspectURL(req.query.url);
}
else if ('a' in req.query && 'd' in req.query && ('s' in req.query || 'm' in req.query)) {
link = new InspectURL(req.query);
}
if (!link || !link.getParams()) {
return errors.InvalidInspect.respond(res);
}
const job = new Job(req, res, /* bulk */ false);
let price;
if (canSubmitPrice(req.query.priceKey, link, req.query.price)) {
price = parseInt(req.query.price);
}
job.add(link, price);
try {
handleJob(job);
} catch (e) {
winston.warn(e);
errors.GenericBad.respond(res);
}
});
app.post('/bulk', (req, res) => {
if (!req.body || (CONFIG.bulk_key && req.body.bulk_key != CONFIG.bulk_key)) {
return errors.BadSecret.respond(res);
}
if (!req.body.links || req.body.links.length === 0) {
return errors.BadBody.respond(res);
}
if (CONFIG.max_simultaneous_requests > 0 && req.body.links.length > CONFIG.max_simultaneous_requests) {
return errors.MaxRequests.respond(res);
}
const job = new Job(req, res, /* bulk */ true);
for (const data of req.body.links) {
const link = new InspectURL(data.link);
if (!link.valid) {
return errors.InvalidInspect.respond(res);
}
let price;
if (canSubmitPrice(req.body.priceKey, link, data.price)) {
price = parseInt(req.query.price);
}
job.add(link, price);
}
try {
handleJob(job);
} catch (e) {
winston.warn(e);
errors.GenericBad.respond(res);
}
});
app.get('/stats', (req, res) => {
res.json({
bots_online: botController.getReadyAmount(),
bots_total: botController.bots.length,
queue_size: queue.queue.length,
queue_concurrency: queue.concurrency,
});
});
app.get('/get-user', async (req,res) =>{
const {user} = req.query;
res.status(200).send(await lookupProfile(user))
})
async function lookupProfile(user){
let freeBot = botController.getFreeBot();
if (freeBot) return freeBot.sendGetUserRequest(user);
else return {success:false, msg:'No bots available'};
}
const http_server = require('http').Server(app);
http_server.listen(CONFIG.http.port);
winston.info('Listening for HTTP on port: ' + CONFIG.http.port);
queue.process(CONFIG.logins.length, botController, async (job) => {
const itemData = await botController.lookupFloat(job.data.link);
winston.debug(`Received itemData for ${job.data.link.getParams().a}`);
// Save and remove the delay attribute
let delay = itemData.delay;
delete itemData.delay;
// add the item info to the DB
await postgres.insertItemData(itemData.iteminfo, job.data.price);
// Get rank, annotate with game files
itemData.iteminfo = Object.assign(itemData.iteminfo, await postgres.getItemRank(itemData.iteminfo.a));
gameData.addAdditionalItemProperties(itemData.iteminfo);
itemData.iteminfo = utils.removeNullValues(itemData.iteminfo);
itemData.iteminfo.stickers = itemData.iteminfo.stickers.map((s) => utils.removeNullValues(s));
job.data.job.setResponse(job.data.link.getParams().a, itemData.iteminfo);
return delay;
});
queue.on('job failed', (job, err) => {
const params = job.data.link.getParams();
winston.warn(`Job Failed! S: ${params.s} A: ${params.a} D: ${params.d} M: ${params.m} IP: ${job.ip}, Err: ${(err || '').toString()}`);
job.data.job.setResponse(params.a, errors.TTLExceeded);
});
process
.on('unhandledRejection', (reason, p) => {
console.error(reason, 'Unhandled Rejection at Promise', p);
})
.on('uncaughtException', err => {
console.error(err, 'Uncaught Exception thrown');
});