Repository navigation
Expand file tree
/
Copy pathscraper.ts
More file actions
378 lines (340 loc) · 12.1 KB
/
Copy pathscraper.ts
File metadata and controls
378 lines (340 loc) · 12.1 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
import lzma from 'lzma';
import { load } from 'cheerio';
import { Generator as RelicGenerator } from '@wfcd/relics';
import patchlogs from '@wfcd/patchlogs';
import Progress from './progress';
import ArcaneScraper from './wikia/scrapers/ArcaneScraper';
import ArchwingScraper from './wikia/scrapers/ArchwingScraper';
import CompanionScraper from './wikia/scrapers/CompanionScraper';
import ModScraper from './wikia/scrapers/ModScraper';
import WeaponScraper from './wikia/scrapers/WeaponScraper';
import WarframeScraper from './wikia/scrapers/WarframeScraper';
import NecramechScraper from './wikia/scrapers/NecramechScraper';
import VaultScraper from './wikia/scrapers/VaultScraper';
import VersionScraper from './wikia/scrapers/VersionScraper';
import HonoriumScraper from './wikia/scrapers/HonoriaScraper';
import readJson from './readJson';
import sleep from './sleep';
import { get, getJSON, retryAttempts } from './network';
import type { WikiaData } from './types/shared';
import type { TitaniaRelic } from '@wfcd/relics';
import type { Patchlogs } from '@wfcd/patchlogs';
const locales = await readJson<string[]>(new URL('../config/locales.json', import.meta.url));
const wikiaNameOverrides = await readJson<WikiaNameOverride[]>(new URL('../config/wikiaNameOverrides.json', import.meta.url));
const prod = process.env.NODE_ENV === 'production';
interface WikiaNameOverride {
name: string;
override: string;
}
/**
* Check for and apply overrides for WikiaData names
* @param wikiaData - set of WikiaData to check
*/
const applyNameOverrides = (wikiaData: WikiaData) => {
const overrideMap: Record<string, string> = Object.fromEntries(
wikiaNameOverrides.map((override) => [override.name, override.override])
);
for (const key of Object.keys(wikiaData) as (keyof WikiaData)[]) {
for (const entry of wikiaData[key]) {
const replacement = overrideMap[entry.name];
if (replacement) entry.name = replacement;
}
}
};
interface ApiChunk {
category: string;
data: Record<string, unknown>[];
}
interface WikiaDucat {
name: string;
ducats: number;
}
/**
* Retrieves the base item data necessary for the parsing process
*/
class Scraper {
endpointCache = new Map<string, Uint8Array>();
originServerAvailable = false;
async checkOriginServerAvailability(): Promise<void> {
this.originServerAvailable = true;
try {
// If this call is successful, it means that the origin server is available.
await this.fetchEndpoints(true, 'en');
} catch (_err) {
// Origin server not available, fall back to content server
this.originServerAvailable = false;
console.warn(
'origin.warframe.com not available. Using content.warframe.com instead. Data might not be up-to-date!!!'
);
}
}
/**
* Get Endpoints from Warframe's origin file
* @param manifest - to fetch only the manifest or everything else
* @param locale - Locale to fetch data for
*/
async fetchEndpoints(manifest?: boolean, locale?: string): Promise<string | string[] | undefined> {
return await retryAttempts(5, async () => {
const origin = `https://${this.originServerAvailable ? 'origin' : 'content'}.warframe.com/PublicExport/index_${
locale ?? 'en'
}.txt.lzma`;
let raw = this.endpointCache.get(origin);
raw ??= (await get(origin, !prod)) as Uint8Array;
const decompressed = lzma.decompress(raw);
this.endpointCache.set(origin, raw); // Cache endpoint only if lzma.decompress didn't throw an error
const manifestRegex = /(\r?\n)?ExportManifest.*/;
// We either don't need the manifest, or *only* the manifest
if (manifest) {
if (typeof decompressed === 'string') {
const match = manifestRegex.exec(decompressed);
return match ? match[0].replace(/\r?\n/, '') : '';
}
if (typeof decompressed === 'object') {
const match = manifestRegex.exec(decompressed.toString());
return match ? match[0].replace(/\r?\n/, '') : '';
}
}
if (typeof decompressed === 'string') {
return decompressed
.replace(manifestRegex, '')
.split(/\r?\n/g)
.filter((d) => d !== '');
}
if (typeof decompressed === 'object') {
return decompressed.toString()
.replace(manifestRegex, '')
.split(/\r?\n/g)
.filter((d) => d !== '');
}
return undefined;
});
}
/**
* Fetch Warframe API data, split up by endpoint.
*/
async fetchResources(): Promise<Record<string, ApiChunk[]>> {
const endpoints = (await this.fetchEndpoints()) as string[];
const result: ApiChunk[] = [];
const i18nEndpoints: Record<string, string[]> = {};
await Promise.all(
locales.map(async (locale) => {
i18nEndpoints[locale] = (await this.fetchEndpoints(false, locale)) as string[];
})
);
const firstKey = Object.keys(i18nEndpoints)[0];
const totalEndpoints
= (firstKey && i18nEndpoints[firstKey] ? i18nEndpoints[firstKey].length : 0) * Object.keys(i18nEndpoints).length
+ endpoints.length;
const bar = new Progress('Fetching API Endpoints', totalEndpoints);
const fetchEndpoint = async (endpoint: string | undefined): Promise<ApiChunk | undefined> => {
if (!endpoint) {
return undefined;
}
const category = endpoint.replace('Export', '').replace(/_[a-z]{2}\.json.*/, '');
const raw = await getJSON<Record<string, unknown>>(
`https://content.warframe.com/PublicExport/Manifest/${endpoint}`,
true
);
const data = raw[`Export${category}`] as Record<string, unknown>[] | undefined;
bar.tick();
if (category === 'SortieRewards' && data) {
const nightwave = raw.ExportNightwave as { challenges?: Record<string, unknown>[] } | undefined;
if (nightwave?.challenges) {
data.push(...nightwave.challenges);
}
}
if (category === 'Weapons' && data) {
const railjackWeapons = raw.ExportRailjackWeapons as Record<string, unknown>[];
data.push(...railjackWeapons);
}
if (category === 'Warframes' && data) {
const helminth = {
uniqueName: '/Lotus/Powersuits/PowersuitAbilities/Helminth',
name: 'Helminth',
health: 0,
shield: 0,
armor: 0,
stamina: 0,
power: 0,
abilities: raw.ExportAbilities
};
data.push(helminth);
}
if (category === 'Upgrades' && data) {
const modSets = raw.ExportModSet as Record<string, unknown>[] | undefined;
const avionics = raw.ExportAvionics as Record<string, unknown>[] | undefined;
const focusUpgrades = raw.ExportFocusUpgrades as Record<string, unknown>[] | undefined;
if (modSets) {
data.push(...modSets.map((modSet) => ({ ...modSet, type: 'Mod Set' })));
}
if (avionics) {
data.push(...avionics);
}
if (focusUpgrades) {
data.push(...focusUpgrades);
}
}
return { category, data: data ?? [] };
};
await Promise.all(
endpoints
.filter(Boolean)
.map(async (endpoint) => {
const endpointResult = await fetchEndpoint(endpoint);
if (endpointResult) {
result.push(endpointResult);
}
})
);
const i18n: Record<string, ApiChunk[]> = {
en: result
};
// Request i18n sequentially by locale to avoid getting randomly stuck in some computers
// It is roughly the same speed as the "all async" method but is always successful
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < locales.length; i += 1) {
const locale = locales[i];
if (!locale) continue;
i18n[locale] = [];
const localeEndpoints = i18nEndpoints[locale];
if (localeEndpoints) {
await Promise.all(
localeEndpoints.map(async (endpoint: string) => {
if (i18n[locale]) {
const result = await fetchEndpoint(endpoint);
if (result) {
i18n[locale].push(result);
}
}
})
);
}
}
return i18n;
}
/**
* Get the manifest of all available images.
* @param skipProgress - whether to show progress
* @returns image manifest
*/
async fetchImageManifest(skipProgress?: boolean): Promise<unknown[]> {
const bar = skipProgress ? undefined : new Progress('Fetching Image Manifest', 1);
const endpoint = await this.fetchEndpoints(true);
if (!endpoint) {
console.error(`No Image Manifest Retrieved from API: ${endpoint!}`);
return process.exit(1);
}
const manifest = (
await getJSON<{ Manifest: unknown[] }>(`https://content.warframe.com/PublicExport/Manifest/${endpoint as string}`, true)
).Manifest;
if (!skipProgress) {
bar?.tick();
}
return manifest;
}
/**
* Get official drop rates and check if they changed since last build.
* @param skipProgress - whether to show progress
* @returns drop data
*/
async fetchDropRates(skipProgress?: boolean): Promise<unknown> {
const bar = skipProgress ? undefined : new Progress('Fetching Drop Rates', 1);
const rates = await getJSON('https://drops.warframestat.us/data/all.slim.json', true);
if (!skipProgress) {
bar?.tick();
}
return rates;
}
/**
* Get patchlogs from the forums
* @param skipProgress - whether to show progress
* @returns patchlogs object
*/
// eslint-disable-next-line @typescript-eslint/require-await
async fetchPatchLogs(skipProgress?: boolean): Promise<Patchlogs> {
const bar = skipProgress ? undefined : new Progress('Fetching Patchlogs', 1);
if (!skipProgress) {
bar?.tick();
}
return patchlogs;
}
/**
* Get additional data from wikia if it's not provided in the API
* @returns wikia data
*/
async fetchWikiaData(): Promise<WikiaData> {
const bar = new Progress('Fetching Wikia Data', 11);
const ducats: WikiaDucat[] = [];
const ducatsWikia = await get('https://wiki.warframe.com/w/Ducats/Prices/All', true);
const $ = load(ducatsWikia as string);
$('.mw-content-text table tbody tr').each(function () {
const $this = $(this);
const name = $this.find('td:nth-of-type(1) a:nth-of-type(2)').text();
const value = $this.find('td:nth-of-type(3)').attr('data-sort-value');
ducats.push({ name, ducats: Number.parseInt(value ?? '0', 10) });
});
bar.tick();
await sleep(100);
const weapons = await new WeaponScraper().scrape();
bar.tick();
await sleep(100);
const warframes = await new WarframeScraper().scrape();
bar.tick();
await sleep(100);
const necramechs = await new NecramechScraper().scrape();
bar.tick();
await sleep(100);
const mods = await new ModScraper().scrape();
bar.tick();
await sleep(100);
const arcanes = await new ArcaneScraper().scrape();
bar.tick();
await sleep(100);
const versions = await new VersionScraper().scrape();
bar.tick();
await sleep(100);
const archwings = await new ArchwingScraper().scrape();
bar.tick();
await sleep(100);
const companions = await new CompanionScraper().scrape();
bar.tick();
await sleep(100);
const vaultData = await new VaultScraper().scrape();
bar.tick();
await sleep(100);
const honoria = await new HonoriumScraper().scrape();
bar.tick();
const wikiaToReturn: WikiaData = {
weapons,
warframes,
necramechs,
mods,
versions,
ducats,
archwings,
companions,
arcanes,
vaultData,
honoria
};
applyNameOverrides(wikiaToReturn);
return wikiaToReturn;
}
/**
* Generate Relic Data from Titania Project
* @returns relic data array
*/
async generateRelicData(): Promise<TitaniaRelic[] | undefined> {
const bar = new Progress('Generating Relic Data', 1);
const relicGenerator = new RelicGenerator();
try {
const relicData = await relicGenerator.generate();
bar.tick();
return relicData;
} catch (e) {
console.error(e);
return undefined;
}
}
}
export default new Scraper();