forked from LiveSplit/LiveSplitOne
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpeedrunCom.ts
More file actions
448 lines (388 loc) · 10.8 KB
/
SpeedrunCom.ts
File metadata and controls
448 lines (388 loc) · 10.8 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
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
import { Option, map } from "../util/OptionUtil";
const BASE_URI = "https://www.speedrun.com/api/v1/";
export interface Game {
"id": string;
"names": Names;
"abbreviation": string;
"weblink": string;
"released": number;
"release-date": string;
"assets": Assets;
"ruleset": Rules;
"platforms": string[];
"regions": string[];
"variables"?: Variables;
}
export interface Rules {
"show-milliseconds": boolean;
"require-verification": boolean;
"require-video": boolean;
"run-times": TimingMethod[];
"default-time": TimingMethod;
"emulators-allowed": boolean;
}
export type TimingMethod = "realtime" | "realtime_noloads" | "ingame";
export interface Variables {
data: Variable[];
}
export interface Variable {
"id": string;
"name": string;
"category": Option<string>;
"scope": VariableScope;
"values": VariableValues;
"mandatory": boolean;
"is-subcategory": boolean;
}
export interface VariableScope {
type: "global" | "full-game" | "all-levels" | "single-level";
}
export interface VariableValues {
values: { [id: string]: VariableValue };
default: Option<string>;
}
export interface VariableValue {
label: string;
rules?: Option<string>;
}
export interface GameHeader {
id: string;
names: Names;
abbreviation: string;
weblink: string;
}
export interface Names {
international: string;
japanese: Option<string>;
twitch?: Option<string>;
}
export interface Assets {
"logo": Asset;
"cover-tiny": Asset;
"cover-small": Asset;
"cover-medium": Asset;
"cover-large": Asset;
"icon": Asset;
"trophy-1st": Asset;
"trophy-2nd": Asset;
"trophy-3rd": Asset;
"trophy-4th": Option<Asset>;
"background": Asset;
"foreground": Option<Asset>;
}
export interface Asset {
uri: string;
width: number;
height: number;
}
export interface Category {
id: string;
weblink: string;
name: string;
type: "per-game" | "per-level";
rules: Option<string>;
}
export interface Leaderboard {
weblink: string;
runs: Record[];
players?: PlayerData;
}
export interface PlayerData {
data: User[];
}
export interface User {
"id": string;
"names": Names;
"weblink": string;
"name-style": NameStyleSolid | NameStyleGradient;
"location": Option<UserLocation>;
}
export interface PlayerUser extends User {
rel: "user";
}
export interface UserLocation {
country: UserCountry;
}
export interface UserCountry {
code: string;
}
export interface NameStyleSolid {
style: "solid";
color: Color;
}
export interface NameStyleGradient {
"style": "gradient";
"color-from": Color;
"color-to": Color;
}
export interface Color {
light: string;
dark: string;
}
export interface Record {
place: number;
run: Run;
}
export type PlayersNotEmbedded = Array<PlayerUserRef | PlayerGuest>;
export interface PlayersEmbedded {
data: Array<PlayerUser | PlayerGuest>;
}
export interface Run<PlayerEmbedding = PlayersNotEmbedded> {
id: string;
weblink: string;
game: string;
category: string;
videos: Option<Videos>;
comment: Option<string>;
players: PlayerEmbedding;
date: Option<string>;
submitted: Option<string>;
times: Times;
system: RunSystem;
splits: Option<Splits>;
values: { [key: string]: string | undefined };
}
export interface RunSystem {
emulated: boolean;
platform: string;
region: Option<string>;
}
export interface Videos {
links: Option<Video[]>;
}
export interface Video {
uri: string;
}
export interface PlayerUserRef {
rel: "user";
id: string;
}
export interface PlayerGuest {
rel: "guest";
name: string;
}
export interface Times {
primary: string;
primary_t: number;
}
export interface Splits {
uri: string;
}
export interface Platform {
id: string;
name: string;
}
export interface Region {
id: string;
name: string;
}
export type RunStatus = "new" | "verified" | "rejected";
function evaluateParameters(parameters: string[]): string {
const filtered = parameters.filter((p) => p.trim() !== "");
if (filtered.length !== 0) {
return `?${filtered.join("&")}`;
} else {
return "";
}
}
function getGamesUri(subUri: string): string {
const GAMES_URI = "games";
return `${BASE_URI}${GAMES_URI}${subUri}`;
}
function getLeaderboardsUri(subUri: string): string {
const LEADERBOARDS_URI = "leaderboards";
return `${BASE_URI}${LEADERBOARDS_URI}${subUri}`;
}
function getPlatformsUri(subUri: string): string {
const PLATFORMS_URI = "platforms";
return `${BASE_URI}${PLATFORMS_URI}${subUri}`;
}
function getRegionsUri(subUri: string): string {
const REGIONS_URI = "regions";
return `${BASE_URI}${REGIONS_URI}${subUri}`;
}
function getRunsUri(subUri: string): string {
const RUNS_URI = "runs";
return `${BASE_URI}${RUNS_URI}${subUri}`;
}
async function executeRequest<T>(uri: string): Promise<T> {
const response = await fetch(uri);
if (!response.ok) {
throw new Error("Error fetching data.");
}
const responseData = await response.json();
return responseData.data as T;
}
export class Page<T> {
public constructor(
public elements: T[],
public next: Option<() => Promise<Page<T>>>,
) { }
public async evaluateAll(): Promise<T[]> {
const elements = this.elements;
let next = this.next;
while (next != null) {
try {
const page = await next();
elements.push(...page.elements);
next = page.next;
} catch {
break;
}
}
return elements;
}
public async iterElementsWith(
closure: (element: T) => boolean | undefined | void,
) {
let elements = this.elements;
let next = this.next;
while (true) {
for (const element of elements) {
if (closure(element) === false) {
break;
}
}
if (next != null) {
const page = await next();
elements = page.elements;
next = page.next;
} else {
break;
}
}
}
public map<R>(closure: (element: T) => R): Page<R> {
const next = map(this.next, (nextFn) => async () => {
const awaited = await nextFn();
return awaited.map(closure);
});
return new Page(this.elements.map(closure), next);
}
}
async function executePaginatedRequest<T>(uri: string): Promise<Page<T>> {
const response = await fetch(uri);
const { data, pagination } = await response.json();
let next = null;
if (pagination.links != null) {
const nextLink = pagination.links.find((l: any) => l.rel === "next");
if (nextLink != null) {
const link = new URL(nextLink.uri as string);
link.protocol = "https:"; // Ensure HTTPS, their API seems to return HTTP links.
next = () => executePaginatedRequest<T>(link.toString());
}
}
return new Page(data as T[], next);
}
export async function getGame(
gameId: string,
embeds?: Array<"variables">,
): Promise<Game> {
const parameters = [];
if (embeds !== undefined) {
parameters.push(`embed=${embeds.join(",")}`);
}
const uri = getGamesUri(`/${gameId}${evaluateParameters(parameters)}`);
return executeRequest<Game>(uri);
}
export async function getGames(name?: string): Promise<Page<Game>> {
const parameters = [];
if (name !== undefined && name !== "") {
parameters.push(`name=${encodeURIComponent(name)}`);
}
// TODO Remaining parameters
const uri = getGamesUri(evaluateParameters(parameters));
return executePaginatedRequest<Game>(uri);
}
export async function getGameHeaders(
elementsPerPage: number = 1000,
): Promise<Page<GameHeader>> {
const parameters = ["_bulk=yes", `max=${elementsPerPage}`];
// TODO Remaining parameters
const uri = getGamesUri(evaluateParameters(parameters));
return executePaginatedRequest<GameHeader>(uri);
}
export async function getCategories(gameId: string): Promise<Category[]> {
// TODO Remaining parameters
const uri = getGamesUri(`/${gameId}/categories`);
return executeRequest<Category[]>(uri);
}
export async function getLeaderboard(
gameId: string,
categoryId: string,
embeds?: Array<"players">,
): Promise<Leaderboard> {
const parameters = [];
if (embeds !== undefined) {
parameters.push(`embed=${embeds.join(",")}`);
}
const uri = getLeaderboardsUri(
`/${gameId}/category/${categoryId}${evaluateParameters(parameters)}`,
);
return executeRequest<Leaderboard>(uri);
}
export async function getPlatforms(
elementsPerPage?: number,
): Promise<Page<Platform>> {
const parameters = [];
if (elementsPerPage !== undefined) {
parameters.push(`max=${elementsPerPage}`);
}
const uri = getPlatformsUri(evaluateParameters(parameters));
return executePaginatedRequest<Platform>(uri);
}
export async function getRegions(
elementsPerPage?: number,
): Promise<Page<Region>> {
const parameters = [];
if (elementsPerPage !== undefined) {
parameters.push(`max=${elementsPerPage}`);
}
const uri = getRegionsUri(evaluateParameters(parameters));
return executePaginatedRequest<Region>(uri);
}
export async function getRuns(
embedPlayers: true,
categoryId?: string,
elementsPerPage?: number,
status?: RunStatus,
): Promise<Page<Run<PlayersEmbedded>>>;
export async function getRuns(
embedPlayers: false,
categoryId?: string,
elementsPerPage?: number,
status?: RunStatus,
): Promise<Page<Run<PlayersNotEmbedded>>>;
export async function getRuns(
embedPlayers: boolean,
categoryId?: string,
elementsPerPage?: number,
status?: RunStatus,
): Promise<Page<Run<PlayersEmbedded | PlayersNotEmbedded>>> {
const parameters = [];
if (categoryId !== undefined) {
parameters.push(`category=${categoryId}`);
}
if (elementsPerPage !== undefined) {
parameters.push(`max=${elementsPerPage}`);
}
if (embedPlayers) {
parameters.push(`embed=${["players"].join(",")}`);
}
if (status !== undefined) {
parameters.push(`status=${status}`);
}
parameters.push("orderby=submitted", "direction=desc");
const uri = getRunsUri(evaluateParameters(parameters));
return executePaginatedRequest<Run<PlayersEmbedded | PlayersNotEmbedded>>(
uri,
);
}
export async function getRun(runId: string, embeds?: never[]): Promise<Run> {
const parameters = [];
if (embeds !== undefined) {
parameters.push(`embed=${embeds.join(",")}`);
}
const uri = getRunsUri(`/${runId}${evaluateParameters(parameters)}`);
return executeRequest<Run>(uri);
}