This repository was archived by the owner on Mar 21, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
384 lines (324 loc) · 10.2 KB
/
server.js
File metadata and controls
384 lines (324 loc) · 10.2 KB
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
const express = require("express");
const axios = require("axios");
const qs = require("qs");
const { encode, decode, trim } = require("url-safe-base64");
const crypto = require("crypto");
const hash = crypto.createHash("sha256");
const endpoints = require("./endpoints");
const { Pool } = require("pg");
require("dotenv").config();
const app = express();
const pool = new Pool();
const MAX = Number.MAX_SAFE_INTEGER;
//
// Code challenge for ESI
//
const client_id = process.env.CLIENT_ID;
const redirect_uri = process.env.REDIRECT_URI;
const scope = process.env.SCOPE;
const state = "the absolute";
const bytes = trim(encode(crypto.randomBytes(32).toString("base64")));
hash.update(bytes);
const code_challenge = trim(encode(hash.digest().toString("base64")));
app.get("/materials", (req, res) => {
const { type } = req.query;
const build_system = req.query.build_system || 30004759; // 1dq
const highsec_region = req.query.highsec_region || 10000002;
const highsec_station = req.query.highsec_station || 60003760;
const nullsec_structure = req.query.nullsec_structure || 1022734985679; // 1st Thetastar
createHeirarchyForType(type)
.then(injectHighsecSplit(highsec_region, highsec_station))
.then(injectTypeName)
.then(injectBuildCost(type, build_system))
.then(types => {
res.json(types);
});
});
app.get("/market", (req, res) => {
const highsec_region = req.query.highsec_region || 10000002;
const highsec_station = req.query.highsec_station || 60003760;
createTypesContainer(req.query.types.split(","))
.then(injectHighsecSplit(highsec_region, highsec_station))
.then(injectTypeName)
.then(types => {
res.json(types);
});
});
app.get("/costs", (req, res) => {
getSystemCosts().then(costs => {
res.json(costs);
});
});
app.get("/login", (req, res) => {
const params = qs.stringify({
response_type: "code",
code_challenge_method: "S256",
scope,
redirect_uri,
client_id,
code_challenge,
state
});
const url = [endpoints.authorize, params].join("?");
res.redirect(url);
});
app.get("/callback", (req, res) => {
const { code, state: esi_state } = req.query;
if (state !== esi_state) {
res.json({ error: "Invalid state received from ESI" });
}
const code_verifier = bytes;
const data = qs.stringify({
grant_type: "authorization_code",
client_id,
code,
code_verifier
});
axios.post(endpoints.token, data).then(({ data }) => {
res.send(data);
});
});
//
// Cache the response of an axios request
//
const inspectResponse = response => {
console.log(`Status: ${response.status}`);
console.log(response.headers);
return response;
};
const cacheRequest = request => {
let cache = {};
return function() {
const args = JSON.stringify(arguments);
cache[args] =
cache[args] || request.apply(this, arguments).then(({ data }) => data);
return cache[args];
};
};
//
// Queries for PSQL
//
const materialsForType = id => `select * from lookup_materials(${id})`;
const namesForTypes = ids => `
select "typeName" as name, "typeID" as id from "invTypes" where "typeID" in (${ids})
`;
//
// Expensive requests used in multiple calculations
//
const systemCostsRequest = () => axios.get(endpoints.systemCosts);
const getSystemCosts = cacheRequest(systemCostsRequest);
const adjustedPricesRequest = () => axios.get(endpoints.marketPrices);
const getAdjustedPrices = cacheRequest(adjustedPricesRequest);
const highsecSplitRequest = (region, id) =>
axios.get(endpoints.regionOrders(region, id));
const getHighsecSplit = cacheRequest(highsecSplitRequest);
const createTypesContainer = ids => {
return new Promise(resolve => {
const types = {};
ids.forEach(id => (types[id] = {}));
resolve(types);
});
};
const createHeirarchyForType = type => {
return new Promise(resolve => {
pool.query(materialsForType(type)).then(({ rows }) => {
const types = {};
rows.forEach(
({
output_id,
output_quantity,
activity_name,
input_id,
input_quantity
}) => {
// Non-destructively create or update data for output types
types[output_id] = {
...types[output_id],
recipe: {
activity_name,
quantity: output_quantity
},
inputs: {
...(types[output_id] || {}).inputs,
[input_id]: input_quantity
}
};
// Do the same for input types
types[input_id] = {
...types[input_id],
outputs: {
...(types[input_id] || {}).outputs,
[output_id]: input_quantity
}
};
}
);
resolve(types);
});
});
};
//
// Add adjusted price for each item for job cost calculation
//
const injectAdjustedPrice = types => {
return new Promise(resolve => {
getAdjustedPrices().then(prices => {
prices.forEach(({ type_id: id, adjusted_price }) => {
if (types[id] && types[id].outputs) {
types[id].adjusted_price = adjusted_price;
}
});
resolve(types);
});
});
};
//
// Recursively calculates build cost of recipe output
// TODO - Structure bonuses, System Cost Indices, Calculated job times
// - User configuration
//
const injectBuildCost = (root_id, system_id) => in_types => {
return new Promise(resolve => {
// Get access to adjusted prices and cost indices for job fee calculation
Promise.all([
injectAdjustedPrice(in_types),
provideCostIndices(system_id)
]).then(([types, cost_indices]) => {
// Recursive function to populate each level with recipe costs
const recurse = id => {
const product = types[id];
const { sell, inputs, recipe } = product;
if (!inputs) {
return;
}
// Recurse to the bottom level before starting our work
Object.keys(inputs).forEach(input => recurse(input));
const { quantity, activity_name } = recipe;
let base_job_cost = 0;
let material_cost = 0;
for (let id in inputs) {
const { buy, recipe, adjusted_price } = types[id];
const base_quantity = inputs[id];
let best_cost = buy;
if (recipe) {
best_cost = Math.min(buy, recipe.unit_cost);
}
const adjusted_quantity = applyMaterialEfficiency(
base_quantity,
activity_name
);
material_cost += best_cost * adjusted_quantity;
base_job_cost += adjusted_price * base_quantity;
}
// HARDCODED
const cost_index = cost_indices[activity_name];
const tax_rate = 1.1;
const job_fees = base_job_cost * cost_index * tax_rate;
const blueprint_cost = material_cost + job_fees;
const unit_cost = blueprint_cost / quantity;
const margin = (sell - unit_cost) / sell;
product.recipe = {
margin,
unit_cost,
material_cost,
job_fees,
base_job_cost,
blueprint_cost,
cost_index,
...product.recipe
};
};
// Kick off recursion
recurse(root_id);
// Pass control back to caller
resolve(types);
});
});
};
const applyMaterialEfficiency = (
input_quantity,
activity_name,
efficiency_factor = 1.0
) => {
if (activity_name == "manufacturing") {
efficiency_factor = 0.9; // Hardcoded perfection, for now
}
const max_job_time = 2592000; // Assume 30 days of production
const time = 25920; // PLACEHOLDER
const runs = Math.ceil(Math.max(max_job_time / time, 1));
// EVE Industry formula
const reduced_quantity = Math.max(
runs,
Math.ceil(runs * efficiency_factor * input_quantity)
);
// single run
return reduced_quantity / runs;
};
//
// Adds buy / sell split to provided object with typeIDs for keys
//
const injectHighsecSplit = (highsec_region, highsec_station) => types => {
return new Promise(resolve => {
const requests = Object.keys(types).map(
id => getHighsecSplit(highsec_region, id) // The Forge region
);
Promise.all(requests).then(responses => {
responses.forEach(orders => {
orders = orders.filter(order => order.location_id == highsec_station); // clamp to specified station
if (orders.length == 0) {
return;
}
const buy = orders
.filter(order => order.is_buy_order)
.map(order => order.price)
.reduce((max, curr) => (curr > max ? curr : max), 0);
const sell = orders
.filter(order => !order.is_buy_order)
.map(order => order.price)
.reduce((min, curr) => (curr < min ? curr : min), MAX);
const id = orders[0].type_id;
// attach buy and sell split to existing entry
types[id] = { buy, sell, ...types[id] };
});
resolve(types);
});
});
};
//
// Lookup type names for each ID in a dictionary with IDs for keys
//
const injectTypeName = async types => {
const ids = Object.keys(types).join(",");
const { rows } = await pool.query(namesForTypes(ids))
rows.forEach(({ name, id }) => (types[id] = { name, ...types[id] }));
return types;
};
const provideCostIndices = async id => {
const indices = {};
const systems = await getSystemCosts();
systems
.find(system => system.solar_system_id == id)
.cost_indices.forEach(({ activity, cost_index }) => {
// CCP
if (activity == "reaction") {
activity = "reactions";
}
indices[activity] = cost_index;
});
return indices;
};
const port = process.env.PORT || 5000;
// Connect to postgres first
const startup_tasks = [
pool.connect(),
app.listen(port),
getAdjustedPrices(),
getSystemCosts()
];
Promise.all(startup_tasks)
.then(() => {
console.log("Server started");
})
.catch(err => {
console.log(err);
});