This repository has been archived by the owner on Feb 19, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.cjs.js
727 lines (706 loc) · 32 KB
/
index.cjs.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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
/* eslint-disable */
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var path = require('path');
var cheerio = require('cheerio');
var request = require('request');
var url = require('url');
var util = require('util');
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
// TODO mode refactor this and prefix interfaces with I
var _a;
var GearLevel;
(function (GearLevel) {
GearLevel[GearLevel["I"] = 1] = "I";
GearLevel[GearLevel["II"] = 3] = "II";
GearLevel[GearLevel["III"] = 3] = "III";
GearLevel[GearLevel["IV"] = 4] = "IV";
GearLevel[GearLevel["V"] = 5] = "V";
GearLevel[GearLevel["VI"] = 6] = "VI";
GearLevel[GearLevel["VII"] = 7] = "VII";
GearLevel[GearLevel["VIII"] = 8] = "VIII";
GearLevel[GearLevel["IX"] = 9] = "IX";
GearLevel[GearLevel["X"] = 10] = "X";
GearLevel[GearLevel["XI"] = 11] = "XI";
GearLevel[GearLevel["XII"] = 12] = "XII";
})(GearLevel || (GearLevel = {}));
/* end user base*/
/*Mod*/
var ModSlot;
(function (ModSlot) {
ModSlot[ModSlot["Transmitter"] = 0] = "Transmitter";
ModSlot[ModSlot["Receiver"] = 1] = "Receiver";
ModSlot[ModSlot["Processor"] = 2] = "Processor";
ModSlot[ModSlot["HoloArray"] = 3] = "HoloArray";
ModSlot[ModSlot["DataBus"] = 4] = "DataBus";
ModSlot[ModSlot["Multiplexer"] = 5] = "Multiplexer";
})(ModSlot || (ModSlot = {}));
var ModSet;
(function (ModSet) {
ModSet[ModSet["Health"] = 0] = "Health";
ModSet[ModSet["Defense"] = 1] = "Defense";
ModSet[ModSet["CriticalDamage"] = 2] = "CriticalDamage";
ModSet[ModSet["CriticalChance"] = 3] = "CriticalChance";
ModSet[ModSet["Tenacity"] = 4] = "Tenacity";
ModSet[ModSet["Offense"] = 5] = "Offense";
ModSet[ModSet["Potency"] = 6] = "Potency";
ModSet[ModSet["Speed"] = 7] = "Speed";
})(ModSet || (ModSet = {}));
// todo probably replace this names on the enum
var TranslatedModName = (_a = {},
_a[ModSlot.Transmitter] = "Square",
_a[ModSlot.Receiver] = "Arrow",
_a[ModSlot.Processor] = "Diamond",
_a[ModSlot.HoloArray] = "Triangle",
_a[ModSlot.DataBus] = "Circle",
_a[ModSlot.Multiplexer] = "Cross",
_a);
var ModPrimary;
(function (ModPrimary) {
ModPrimary["Speed"] = "Speed";
ModPrimary["CriticalChance"] = "Critical Chance";
ModPrimary["CriticalDamage"] = "Critical Damage";
ModPrimary["Potency"] = "Potency";
ModPrimary["Tenacity"] = "Tenacity";
ModPrimary["Accuracy"] = "Accuracy";
ModPrimary["CriticalAvoidance"] = "Critical Avoidance";
ModPrimary["Offense"] = "Offense";
ModPrimary["Defense"] = "Defense";
ModPrimary["Health"] = "Health";
ModPrimary["Protection"] = "Protection";
})(ModPrimary || (ModPrimary = {}));
var ModSecondary;
(function (ModSecondary) {
ModSecondary["Speed"] = "Speed";
ModSecondary["CriticalChance"] = "Critical Chance";
ModSecondary["Potency"] = "Potency";
ModSecondary["Tenacity"] = "Tenacity";
ModSecondary["Offense"] = "Offense";
ModSecondary["Defense"] = "Defense";
ModSecondary["Health"] = "Health";
ModSecondary["Protection"] = "Protection";
ModSecondary["Offense100"] = "Offense %";
ModSecondary["Defense100"] = "Defense %";
ModSecondary["Health100"] = "Health %";
ModSecondary["Protection100"] = "Protection %";
})(ModSecondary || (ModSecondary = {}));
var parseModCollection = function ($) {
var m = $("body > div.container.p-t-md > div.content-container > div.content-container-primary.mod-list > ul > li.media.list-group-item.p-a.collection-mod-list > div > div > div")
.map(function (x) {
var _$ = $(this);
var tier = _$.find(".statmod-pip").length;
var character = _$.find(".char-portrait-img").attr("alt");
var level = _$.find(".statmod-level").text();
var description = _$.find(".statmod-img").attr("alt");
var mod = _$.find(".pc-statmod").first();
/*
export enum ModSlot {
Transmitter,
Receiver,
Processor,
HoloArray,
DataBus,
Multiplexer
}*/
var slot = mod.hasClass("pc-statmod-slot1") && ModSlot.Transmitter;
slot = !slot && mod.hasClass("pc-statmod-slot2") && ModSlot.Receiver || slot;
slot = !slot && mod.hasClass("pc-statmod-slot3") && ModSlot.Processor || slot;
slot = !slot && mod.hasClass("pc-statmod-slot4") && ModSlot.HoloArray || slot;
slot = !slot && mod.hasClass("pc-statmod-slot5") && ModSlot.DataBus || slot;
slot = !slot && mod.hasClass("pc-statmod-slot6") && ModSlot.Multiplexer || slot;
var primaryStat = _$.find(".statmod-stats-1");
var secondaryStats = _$.find(".statmod-stats-2 > .statmod-stat");
var primary = {
type: primaryStat.find(".statmod-stat-label").text(),
value: primaryStat.find(".statmod-stat-value").text(),
};
var secondary = secondaryStats.map(function (s) {
var ss = $(this);
return {
type: ss.find(".statmod-stat-label").text(),
value: ss.find(".statmod-stat-value").text(),
};
}).get();
return {
character: character,
tier: tier,
description: description,
level: level,
slot: TranslatedModName[slot],
primary: primary,
secondary: secondary,
};
}).get();
return m;
};
var _MOD_PAGES_REGEX = /(?:of )(\d+)$/gm;
var getModPages = function ($) {
var selector = 'li.media.list-group-item.p-a.collection-mod-list > div.pull-right > ul > li > a';
var numPages = $(selector).text();
/* const elements = $(selector);
const e1 = elements[0]; //if first page
const e2 = elements[1]; //if other pages
let numPages = e1.children.length === 1
? e1.children[0].nodeValue
: e2.children[0].nodeValue;*/
var m = _MOD_PAGES_REGEX.exec(numPages);
if (!m) {
return null;
}
return +m[1];
};
var fixNumber = function (txt) { return txt && +txt.replace(/,/g, '') || null; };
var swgohAsset = "https://swgoh.gg/static/img/assets/";
var githubAsset = "https://raw.githubusercontent.com/pikax/swgoh/master/static/img/";
var assetLocation = process.env.SWGOH_ASSET_LOCATION || githubAsset;
var assetUrl = process.env.USE_SWGOH_ASSET && swgohAsset || assetLocation;
function parseShips($) {
return $('body > div.container.p-t-md > div.content-container > div.content-container-primary.character-list > ul > li.media.list-group-item.p-a.collection-char-list > div > div > div')
.map(function (x) {
var _$ = $(this);
var na$ = _$.find('div.collection-ship-name > a'); //name
var m$ = _$.find(".collection-ship-main"); //main
var ship$ = m$.find('div.collection-ship-primary > div > a');
var crew$ = m$.find('div.collection-ship-secondary');
var gp$ = crew$.find("div.collection-char-gp");
var gpTitle = gp$.attr("title");
var gp = gpTitle
? gpTitle.replace(/,/g, '').match(/\d+/g) // fix points
: [undefined, undefined, undefined];
var stars = ship$.find("div.ship-portrait-full-star-inactive").length;
var img = ship$.find(".ship-portrait-full-frame-img").attr("src");
var crewMembers = crew$.find('.collection-ship-crew-member')
.map(function (x) {
var _$ = $(this);
var na$ = _$.find(".char-portrait-full-link");
var a$ = _$.find("a");
var i$ = a$.find("img");
var name = _$.find('.player-char-portrait').attr("title");
var gl = a$.find("div.char-portrait-full-gear-level").text();
// NOTE if the user doesn't have that crew member unlocked it should skip it
if (!na$.attr("href"))
return;
var imgsrc = i$.attr("src").slice(2);
return {
code: na$.attr("href").split('/').reverse()[0],
description: name,
imageSrc: "" + assetUrl + path.basename(imgsrc),
star: 7 - a$.find("div.star-inactive").length,
gearLevel: GearLevel[gl],
level: +(a$.find("div.char-portrait-full-level").text()),
};
})
.get();
var hasShip = na$.attr("href").startsWith('/p');
var imgsrc = img === undefined ? "" + assetUrl + path.basename(ship$.find(".ship-portrait-frame-img").attr("src")) : img;
return {
code: na$.attr("href").split('/').reverse()[0],
description: na$.text(),
imageSrc: imgsrc,
star: hasShip ? 7 - stars : 0,
level: +ship$.find(".ship-portrait-full-frame-level").text(),
crew: crewMembers,
galacticPower: +gp[0],
maxGalacticPower: +gp[1],
};
})
.get();
}
function parseCollection($) {
return $("body > div.container.p-t-md > div.content-container > div.content-container-primary.character-list > ul > li.media.list-group-item.p-a.collection-char-list > div > div > div > div.player-char-portrait")
.map(function (x) {
var _$ = $(this);
var p$ = _$.parent("div");
var n$ = p$.find("div.collection-char-name");
var na$ = n$.find("a");
var a$ = _$.find("a");
var i$ = a$.find("img");
var gp$ = p$.find("div.collection-char-gp");
var gp = gp$.attr("title").replace(/,/g, '').match(/\d+/g); // fix points
var gl = a$.find("div.char-portrait-full-gear-level").text();
var imgsrc = (i$.attr("data-src") || i$.attr("src")).slice(2);
return {
code: na$.attr("href").split('/').reverse()[0],
description: na$.text(),
imageSrc: "" + assetUrl + path.basename(imgsrc),
star: 7 - a$.find("div.star-inactive").length,
gearLevel: GearLevel[gl],
level: +(a$.find("div.char-portrait-full-level").text()),
galacticPower: +gp[0],
maxGalacticPower: +gp[1],
};
})
.get();
}
function parseCollectionPages($) {
var txt = $('body > div.container.p-t-md > div.content-container > div.content-container-primary.character-list > ul > li.media.list-group-item.p-a.collection-char-list > ul > li:nth-child(1) > a').text();
if (!txt) {
return 0;
}
var m = txt.match(/\d+$/);
if (!m) {
return 0;
}
debugger;
return +m[0];
}
function parseProfile($) {
return __assign({}, parseInfo($), parseStats($), parseUser($));
}
var parseUser = function ($) {
var b$ = $("body > div.container.p-t-md > div.content-container > div.content-container-aside > div.panel.panel-default.panel-profile.m-b-sm > div.panel-body");
var username = $("body > div.container.p-t-md > div.content-container > div.content-container-aside > div:nth-child(1) > div.panel-body > h5").text().trim();
var panelMenus = b$.find("ul > li > h5").get().map(function (x) { return +(x.lastChild || {}).nodeValue; });
var p = b$.find("p > strong").slice(1).get().map(function (x) { return x.lastChild.nodeValue; });
var userInfo = b$.find("p")
.map(function (i, x) { return ({
key: x.firstChild.nodeValue || '',
value: x.children[1] && x.children[1].lastChild.nodeValue || null
}); })
.toArray();
var g = b$.find("p > strong > a");
var aGuild = g.text(); //get
var aGuildUrl = g.attr("href");
var lastUpdatedUTC = $('body > div.container.p-t-md > div.content-container > div.content-container-primary.character-list > ul > li.list-group-item.p-a.list-group-header > div.header-text > div > span').attr("data-datetime");
var playername = username; //$('h5.panel-title:nth-child(1) > a:nth-child(1)').text();
var allyCode = userInfo.find(function (x) { return x.key.startsWith("Ally Code"); });
var joined = userInfo.find(function (x) { return x.key.startsWith("Joined"); });
return {
username: username,
playername: playername,
userId: panelMenus[0],
arenaRank: panelMenus[1] || null,
level: panelMenus[2],
allyCode: allyCode && allyCode.value || null,
joined: joined && joined.value || null,
guild: aGuild,
guildUrl: aGuildUrl,
lastUpdatedUTC: lastUpdatedUTC
};
};
var parseStats = function ($) {
var p = $("body > div.container.p-t-md > div.content-container > div.content-container-primary.character-list > ul > li:nth-child(3) > div > div > ul > li > h5")
.get().map(function (x) { return +x.lastChild.nodeValue; });
return {
characters: p[0],
characters7: p[1],
characters6: p[2],
gearXII: p[3],
gearXI: p[4],
gearX: p[5],
gearIX: p[6],
gearVIII: p[7],
};
};
var parseInfo = function ($) {
var p = $("body > div.container.p-t-md > div.content-container > div.content-container-aside > div:nth-child(5) > div > p > strong").get()
.map(function (x) { return +x.lastChild.nodeValue.replace(/,/g, ""); });
return {
galacticPower: p[0],
charactersGalacticPower: p[1],
shipsGalacticPower: p[2],
shipBattlesWon: p[3],
arenaBattlesWon: p[4],
pVEBattlesWon: p[5],
pVEHardBattlesWon: p[6],
galacticWarBattlesWon: p[7],
raidsWon: p[8],
guildCurrencyEarned: p[9],
guildDonatedGear: p[10],
};
};
//TODO change to have information about guild
function parseGuild($) {
return __assign({}, parseGuildInfo($), { users: parseUsers($) });
}
function parseUsers($) {
return $("body > div.container.p-t-md > div.content-container > div.content-container-primary.character-list > ul > li.media.list-group-item.p-0.b-t-0 > div > table > tbody > tr")
.map(function () {
var _$ = $(this);
var a = _$.find('td > a');
var username = a.attr("href").slice(3, -1);
var description = a.find("strong").text();
var tds = _$.find("td").slice(1).contents(); // skip a
var galacticPower = +tds[0].nodeValue;
var arenaRank = +tds[1].nodeValue || undefined;
var arenaAverage = +tds[2].nodeValue;
return {
username: username,
description: description,
galacticPower: galacticPower,
// collectionScore,
arenaRank: arenaRank,
arenaAverage: arenaAverage
};
}).get();
// return {}
}
function parseGuildInfo($) {
var imageSrc = $('body > div.container.p-t-md > div.content-container > div.content-container-primary.character-list > ul > li.list-group-item.p-a > h1 > img').attr('src');
var guildMembers = $('body > div.container.p-t-md > div.content-container > div.content-container-primary.character-list > ul > li.list-group-item.p-a > h1 > small').text();
var description = $("body > div.container.p-t-md > div.content-container > div.content-container-primary.character-list > ul > li.list-group-item.p-a > p > i").text();
var name = $('body > div.container.p-t-md > div.content-container > div.content-container-primary.character-list > ul > li.list-group-item.p-a > h1')
.children()[1].next.nodeValue.trimLeft();
var gp = $('body > div.container.p-t-md > div.content-container > div.content-container-primary.character-list > ul > li.list-group-item.p-a > div:nth-child(4) > div:nth-child(1) > div > div.stat-item-value').text();
var agp = $("body > div.container.p-t-md > div.content-container > div.content-container-primary.character-list > ul > li.list-group-item.p-a > div:nth-child(4) > div:nth-child(2) > div > div.stat-item-value").text();
var rank = $("body > div.container.p-t-md > div.content-container > div.content-container-primary.character-list > ul > li.list-group-item.p-a > div:nth-child(5) > div:nth-child(1) > div > div.stat-item-value").text();
var arank = $("body > div.container.p-t-md > div.content-container > div.content-container-primary.character-list > ul > li.list-group-item.p-a > div:nth-child(5) > div:nth-child(3) > div > div.stat-item-value").text();
var raidPoints = +$("body > div.container.p-t-md > div.content-container > div.content-container-primary.character-list > ul > li.list-group-item.p-a > div:nth-child(5) > div:nth-child(2) > div > div.stat-item-value").text();
var lp = $("body > div.container.p-t-md > div.content-container > div.content-container-primary.character-list > ul > li.list-group-item.p-a > div.media-heading.text-right > small > strong > span").attr("data-datetime");
var galacticPower = fixNumber(gp);
var averageGalacticPower = fixNumber(agp);
var arenaRank = fixNumber(arank);
var m = guildMembers.match(/\d+/g);
var memberCount = +m[0];
var profileCount = +m[1];
var lastUpdated = new Date(lp);
return {
name: name,
imageSrc: imageSrc,
description: description,
galacticPower: galacticPower,
averageGalacticPower: averageGalacticPower,
rank: rank,
raidPoints: raidPoints,
arenaRank: arenaRank,
memberCount: memberCount,
profileCount: profileCount,
lastUpdated: lastUpdated
};
}
var requestretry = require("requestretry");
var Queue = require("promise-queue");
var config = {
simultaneousRequests: 10,
safeQueueSize: 5,
maxQueueSize: 50,
tick: 33
};
var ConcurrentQueue = /** @class */ (function () {
function ConcurrentQueue(_config) {
if (_config === void 0) { _config = config; }
this._config = _config;
this._queue = new Queue(30);
}
ConcurrentQueue.prototype.queue = function (uri) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
/*if (this._queue.getQueueLength() > this._config.maxQueueSize) {
while (this._queue.getQueueLength() < this._config.safeQueueSize) {
await promiseSetTimeout(TICK);
}
}*/
return [2 /*return*/, this._queue.add(function () { return requestretry(uri); })];
});
});
};
return ConcurrentQueue;
}());
/*
export function promiseSetTimeout(ms: number): Promise<any> {
return new Promise((resolve => setTimeout(resolve, ms)));
}
*/
var swgohgg = "https://swgoh.gg";
var swgohJar = request.jar();
request.defaults({
jar: swgohJar
});
var Swgoh = /** @class */ (function () {
function Swgoh(_queue) {
if (_queue === void 0) { _queue = new ConcurrentQueue(); }
this._queue = _queue;
}
Swgoh.prototype.getCheerio = function (uri) {
return this._queue.queue(uri)
.then(this.validateRequest)
.then(function (x) { return cheerio.load(x.body); });
};
Swgoh.prototype.validateRequest = function (request$$1) {
if (request$$1.body.indexOf("<title>Login · SWGOH.GG</title>") >= 0) {
throw new Error('Login is required');
}
return request$$1;
};
//based on https://github.com/bahmutov/csrf-login/blob/master/src/csrf-login.js
Swgoh.prototype.login = function (username, password) {
return __awaiter(this, void 0, void 0, function () {
var uri, jar, host, $login, csrfmiddlewaretoken, csrf, form, r, html;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
uri = url.resolve(swgohgg, "/accounts/login/");
jar = request.jar();
host = "swgoh.gg";
return [4 /*yield*/, this._queue.queue({ uri: uri, jar: jar }).then(function (x) { return cheerio.load(x.body); })];
case 1:
$login = _a.sent();
csrfmiddlewaretoken = $login("input[name=csrfmiddlewaretoken]").attr("value");
csrf = csrfmiddlewaretoken;
form = {
username: username,
password: password,
csrfmiddlewaretoken: csrfmiddlewaretoken,
};
r = {
uri: uri,
form: form,
method: "POST",
jar: jar,
followAllRedirects: true,
headers: {
referer: host
}
};
jar.setCookie(request.cookie('csrftoken=' + csrf), uri);
return [4 /*yield*/, this._queue.queue(r).then(function (x) { return x.body; })];
case 2:
html = _a.sent();
// console.log('html:' + html)
//todo change to regex expression with word probably
return [2 /*return*/, html.indexOf(username) >= 0];
}
});
});
};
// NOTE swgoh.gg changed the default to be ally code
Swgoh.prototype.profile = function (username) {
var uri = url.resolve(swgohgg, "/u/" + username + "/");
return this.getCheerio(uri).then(parseProfile);
};
Swgoh.prototype.profileAlly = function (allyCode) {
var uri = url.resolve(swgohgg, "/p/" + allyCode + "/");
return this.getCheerio(uri).then(parseProfile);
};
Swgoh.prototype.collection = function (username) {
return __awaiter(this, void 0, void 0, function () {
var uri, $, pages, promises, i, collections;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
uri = url.resolve(swgohgg, "/u/" + username + "/characters/");
return [4 /*yield*/, this.getCheerio(uri)];
case 1:
$ = _a.sent();
pages = parseCollectionPages($);
promises = [Promise.resolve(parseCollection($))];
for (i = 2; i <= pages; i++) {
promises.push(this.getCheerio(url.resolve(uri, "?page=" + i)).then(parseCollection));
}
return [4 /*yield*/, Promise.all(promises)];
case 2:
collections = _a.sent();
return [2 /*return*/, collections.reduce(function (v, c) {
c.push.apply(c, v);
return c;
}, [])];
}
});
});
};
Swgoh.prototype.collectionAlly = function (allyCode) {
return __awaiter(this, void 0, void 0, function () {
var uri, $, pages, promises, i, collections;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
uri = url.resolve(swgohgg, "/p/" + allyCode + "/characters/");
return [4 /*yield*/, this.getCheerio(uri)];
case 1:
$ = _a.sent();
pages = parseCollectionPages($);
promises = [Promise.resolve(parseCollection($))];
for (i = 2; i <= pages; i++) {
promises.push(this.getCheerio(url.resolve(uri, "?page=" + i)).then(parseCollection));
}
return [4 /*yield*/, Promise.all(promises)];
case 2:
collections = _a.sent();
return [2 /*return*/, collections.reduce(function (v, c) {
c.push.apply(c, v);
return c;
}, [])];
}
});
});
};
Swgoh.prototype.mods = function (username) {
return __awaiter(this, void 0, void 0, function () {
var modsUri, uri, $, modsPage, promises, pMods;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
modsUri = "/u/" + username + "/mods/";
uri = url.resolve(swgohgg, modsUri);
return [4 /*yield*/, this.getCheerio(uri)];
case 1:
$ = _a.sent();
modsPage = getModPages($) - 1;
promises = Array.from({ length: modsPage }, function (k, i) { return i + 2; })
.map(function (x) { return _this.getCheerio(uri + ("?page=" + x))
.then(function (x) { return parseModCollection(x); }); });
return [4 /*yield*/, Promise.all(promises.slice())];
case 2:
pMods = _a.sent();
pMods.unshift(parseModCollection($)); //insert at the beginning
return [2 /*return*/, [].concat.apply([], pMods)]; //flat
}
});
});
};
Swgoh.prototype.modsAlly = function (allyCode) {
return __awaiter(this, void 0, void 0, function () {
var modsUri, uri, $, modsPage, promises, pMods;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
modsUri = "/p/" + allyCode + "/mods/";
uri = url.resolve(swgohgg, modsUri);
return [4 /*yield*/, this.getCheerio(uri)];
case 1:
$ = _a.sent();
modsPage = getModPages($) - 1;
promises = Array.from({ length: modsPage }, function (k, i) { return i + 2; })
.map(function (x) { return _this.getCheerio(uri + ("?page=" + x))
.then(function (x) { return parseModCollection(x); }); });
return [4 /*yield*/, Promise.all(promises.slice())];
case 2:
pMods = _a.sent();
pMods.unshift(parseModCollection($)); //insert at the beginning
return [2 /*return*/, [].concat.apply([], pMods)]; //flat
}
});
});
};
Swgoh.prototype.ship = function (username) {
var uri = url.resolve(swgohgg, "/u/" + username + "/ships/");
return this.getCheerio(uri).then(parseShips);
};
Swgoh.prototype.shipAlly = function (allyCode) {
var uri = url.resolve(swgohgg, "/p/" + allyCode + "/ships/");
return this.getCheerio(uri).then(parseShips);
};
Swgoh.prototype.guild = function (opts) {
var uri;
if (typeof opts === "string") {
var m = opts.match(/\d+/);
if (!m) {
throw new Error("Error: \"" + opts + "\" is not a valid guild url");
}
uri = url.resolve(swgohgg, opts);
}
else {
var id = opts.id;
if (isNaN(id) || !util.isNumber(id)) {
throw new Error("Error: Unable to parse guild id from \"" + opts + "\"");
}
var name = opts.name;
if (!name || name === '') {
throw new Error("Error: Unable to parse guild name from \"" + opts + "\"");
}
uri = url.resolve(swgohgg, "/g/" + id + "/" + name + "/");
}
return this.getCheerio(uri).then(parseGuild);
};
Swgoh.prototype.units = function (opts) {
var id;
if (typeof opts === "string") {
var m = opts.match(/\d+/);
if (!m) {
throw new Error("Error: \"" + opts + "\" is not a valid guild url");
}
id = +m[0];
}
else {
id = opts.id;
}
if (isNaN(id) || !util.isNumber(id)) {
throw new Error("Error: Unable to parse guild id from url \"" + opts + "\"");
}
var uri = url.resolve(swgohgg, "/api/guilds/" + id + "/units/");
return this._queue.queue(uri).then(function (x) { return x.body; });
};
return Swgoh;
}());
var swgoh = new Swgoh();
var requestretry$1 = require("requestretry");
var baseurl = "https://raw.githubusercontent.com/pikax/swgoh/master/static/";
function getCharacters(cached) {
if (cached === void 0) { cached = true; }
if (cached) {
return require("../static/characters.json");
}
return requestretry$1(url.resolve(baseurl, "characters.json"))
.then(function (x) { return x.body; });
}
function getShips(cached) {
if (cached === void 0) { cached = true; }
if (cached) {
return require("../static/ships.json");
}
return requestretry$1(url.resolve(baseurl, "ships.json"))
.then(function (x) { return x.body; });
}
exports.swgoh = swgoh;
exports.Swgoh = Swgoh;
exports.getCharacters = getCharacters;
exports.getShips = getShips;
//# sourceMappingURL=index.cjs.js.map