-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathapiClient.ts
More file actions
615 lines (543 loc) · 17.2 KB
/
apiClient.ts
File metadata and controls
615 lines (543 loc) · 17.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
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
import type { Recording, WorldConfig, WorldInfo } from "./types";
import type { ToolSet, HealthCheck, MapInfo, JobInfo } from "../pages/map-manager/types";
// ─── Response types for endpoints not covered in types.ts ───
export interface CustomizeConfig {
websiteURL?: string;
websiteLogo?: string;
websiteLogoSize?: string;
disableKillCount?: boolean;
headerTitle?: string;
headerSubtitle?: string;
cssOverrides?: Record<string, string>;
}
export interface BuildInfo {
BuildVersion: string;
BuildCommit: string;
BuildDate: string;
}
export interface AuthState {
authenticated: boolean;
role?: string;
steamId?: string;
steamName?: string;
steamAvatar?: string;
}
// ─── Error types ───
export class ApiError extends Error {
constructor(
message: string,
public readonly status: number,
public readonly statusText: string,
) {
super(message);
this.name = "ApiError";
}
}
// ─── Raw server response shape (snake_case from Go JSON tags) ───
interface RawRecording {
id: number;
world_name: string;
mission_name: string;
mission_duration: number;
filename: string;
date: string;
tag?: string;
storageFormat?: string;
conversionStatus?: string;
schemaVersion?: number;
chunkCount?: number;
player_count?: number;
kill_count?: number;
player_kill_count?: number;
side_composition?: Record<string, { players: number; units: number; dead: number; kills: number }>;
focusStart?: number;
focusEnd?: number;
}
function mapRecording(raw: RawRecording): Recording {
return {
id: String(raw.id),
worldName: raw.world_name,
missionName: raw.mission_name,
missionDuration: raw.mission_duration,
date: raw.date,
tag: raw.tag,
filename: raw.filename,
storageFormat: raw.storageFormat,
conversionStatus: raw.conversionStatus,
schemaVersion: raw.schemaVersion,
chunkCount: raw.chunkCount,
playerCount: raw.player_count,
killCount: raw.kill_count,
playerKillCount: raw.player_kill_count,
sideComposition: raw.side_composition,
focusStart: raw.focusStart ?? undefined,
focusEnd: raw.focusEnd ?? undefined,
};
}
// ─── Query filter parameters for recordings endpoint ───
export interface RecordingFilters {
tag?: string;
name?: string;
newer?: string;
older?: string;
}
// ─── API Client ───
// ─── JWT token store ───
const TOKEN_KEY = "ocap_token";
let authToken: string | null = sessionStorage.getItem(TOKEN_KEY);
export function setAuthToken(token: string | null): void {
authToken = token;
if (token) {
sessionStorage.setItem(TOKEN_KEY, token);
} else {
sessionStorage.removeItem(TOKEN_KEY);
}
}
export function getAuthToken(): string | null {
return authToken;
}
function authHeaders(): Record<string, string> {
return authToken ? { Authorization: `Bearer ${authToken}` } : {};
}
// ─── API Client ───
export class ApiClient {
private readonly baseUrl: string;
/**
* @param baseUrl - Base URL prefix for all API calls (default: "").
* Matches the Go server's prefixURL setting. A trailing slash is normalised internally.
*/
constructor(baseUrl?: string) {
// Default to the server-injected base path (set in index.html by the Go backend).
// Falls back to empty string when not behind a prefix or in tests.
const raw = baseUrl ?? ((globalThis as Record<string, unknown>).__BASE_PATH__ as string) ?? "";
// Ensure no trailing slash so we can append /api/... cleanly
this.baseUrl = raw.replace(/\/+$/, "");
}
// ─── Public helpers ───
/**
* Fetch the list of recordings, optionally filtered.
* GET {baseUrl}/api/v1/operations
*/
async getRecordings(filters?: RecordingFilters): Promise<Recording[]> {
const params = new URLSearchParams();
if (filters?.tag) params.set("tag", filters.tag);
if (filters?.name) params.set("name", filters.name);
if (filters?.newer) params.set("newer", filters.newer);
if (filters?.older) params.set("older", filters.older);
const qs = params.toString();
const url = `${this.baseUrl}/api/v1/operations${qs ? `?${qs}` : ""}`;
const data = await this.fetchJson<RawRecording[]>(url);
return data.map(mapRecording);
}
/**
* Fetch a single recording by ID or filename.
* GET {baseUrl}/api/v1/operations/{id}
*/
async getRecording(id: string): Promise<Recording> {
const url = `${this.baseUrl}/api/v1/operations/${encodeURIComponent(id)}`;
const data = await this.fetchJson<RawRecording>(url);
return mapRecording(data);
}
/**
* Fetch raw recording data (gzipped JSON served as a static file).
* GET {baseUrl}/data/{filename}.json.gz
*/
async getRecordingData(filename: string): Promise<ArrayBuffer> {
const url = `${this.baseUrl}/data/${encodeURIComponent(filename)}.json.gz`;
return this.fetchBuffer(url);
}
/**
* Fetch UI customization config.
* GET {baseUrl}/api/v1/customize
*/
async getCustomize(): Promise<CustomizeConfig> {
const response = await fetch(`${this.baseUrl}/api/v1/customize`, {
cache: "no-cache",
});
if (response.status === 204) {
return {};
}
if (!response.ok) {
throw new ApiError(
`GET customize failed: ${response.status} ${response.statusText}`,
response.status,
response.statusText,
);
}
return response.json() as Promise<CustomizeConfig>;
}
/**
* Fetch server build/version info.
* GET {baseUrl}/api/version
*/
async getVersion(): Promise<BuildInfo> {
return this.fetchJson<BuildInfo>(`${this.baseUrl}/api/version`);
}
/**
* Fetch installed world metadata (name + display name).
* GET {baseUrl}/api/v1/worlds
*/
async getWorlds(): Promise<WorldInfo[]> {
return this.fetchJson<WorldInfo[]>(`${this.baseUrl}/api/v1/worlds`);
}
/**
* Probe for per-world map configuration with fallback chain:
* 1. Local server: /images/maps/{worldName}/map.json
* 2. PMTiles CDN: https://pmtiles.ocap2.com/{worldName}/map.json
* 3. Legacy raster CDN: https://maps.ocap2.com/{worldName}/map.json
* 4. Blank placeholder if nothing found
*/
async getWorldConfig(worldName: string): Promise<WorldConfig> {
const defaults: WorldConfig = {
worldName,
worldSize: 16384,
imageSize: 16384,
multiplier: 1,
maxZoom: 6,
minZoom: 0,
};
const normalizedName = worldName.toLowerCase();
// 1. Try local map data
try {
const localUrl = `${this.baseUrl}/images/maps/${encodeURIComponent(normalizedName)}/map.json`;
const local = await this.fetchJson<Partial<WorldConfig>>(localUrl);
return {
...defaults,
...local,
tileBaseUrl: `${this.baseUrl}/images/maps/${encodeURIComponent(normalizedName)}`,
worldName,
};
} catch {
// Local not available, try CDN
}
// 2. Try PMTiles CDN (MapLibre-capable)
try {
const pmtilesUrl = `https://pmtiles.ocap2.com/${encodeURIComponent(normalizedName)}/map.json`;
const res = await fetch(pmtilesUrl, { cache: "no-store" });
if (res.ok) {
const data = (await res.json()) as Partial<WorldConfig>;
return {
...defaults,
...data,
maplibre: true,
tileBaseUrl: `https://pmtiles.ocap2.com/${encodeURIComponent(normalizedName)}`,
worldName,
};
}
} catch {
// PMTiles CDN not available
}
// 3. Try legacy raster CDN
try {
const rasterUrl = `https://maps.ocap2.com/${encodeURIComponent(normalizedName)}/map.json`;
const res = await fetch(rasterUrl, { cache: "no-store" });
if (res.ok) {
const data = (await res.json()) as Partial<WorldConfig>;
return {
...defaults,
...data,
tileBaseUrl: `https://maps.ocap2.com/${encodeURIComponent(normalizedName)}`,
worldName,
};
}
} catch {
// Raster CDN not available
}
// 4. Fallback — blank placeholder
console.warn(`Map for world "${worldName}" not found locally or on CDN, using placeholder`);
return { ...defaults, worldSize: 30720, imageSize: 30720 };
}
/**
* Fetch a protobuf manifest as raw bytes (static file).
* GET {baseUrl}/data/{filename}/manifest.pb
*/
async getManifest(filename: string): Promise<ArrayBuffer> {
const url = `${this.baseUrl}/data/${encodeURIComponent(filename)}/manifest.pb`;
return this.fetchBuffer(url);
}
/**
* Fetch a protobuf chunk as raw bytes (static file).
* GET {baseUrl}/data/{filename}/chunks/{NNNN}.pb
*/
async getChunk(
filename: string,
chunkIndex: number,
): Promise<ArrayBuffer> {
const idx = String(chunkIndex).padStart(4, "0");
const url = `${this.baseUrl}/data/${encodeURIComponent(filename)}/chunks/${idx}.pb`;
return this.fetchBuffer(url);
}
// ─── Auth methods ───
getSteamLoginUrl(returnTo?: string): string {
if (returnTo) {
sessionStorage.setItem("ocap_return_to", returnTo);
}
return `${this.baseUrl}/api/v1/auth/steam`;
}
/**
* Pops the saved return-to path (if any) from sessionStorage.
* Returns null if nothing was saved.
*/
popReturnTo(): string | null {
const path = sessionStorage.getItem("ocap_return_to");
if (path) {
sessionStorage.removeItem("ocap_return_to");
}
return path;
}
consumeAuthToken(params: URLSearchParams): boolean {
const token = params.get("auth_token");
if (!token) return false;
setAuthToken(token);
return true;
}
async getMe(): Promise<AuthState> {
const response = await fetch(`${this.baseUrl}/api/v1/auth/me`, {
headers: authHeaders(),
cache: "no-cache",
});
if (!response.ok) {
return { authenticated: false };
}
return response.json() as Promise<AuthState>;
}
async logout(): Promise<void> {
await fetch(`${this.baseUrl}/api/v1/auth/logout`, {
method: "POST",
headers: authHeaders(),
});
setAuthToken(null);
}
// ─── Admin recording methods ───
async editRecording(
id: string,
data: { missionName?: string; tag?: string; date?: string; focusStart?: number | null; focusEnd?: number | null },
): Promise<Recording> {
const response = await fetch(
`${this.baseUrl}/api/v1/operations/${encodeURIComponent(id)}`,
{
method: "PATCH",
headers: { "Content-Type": "application/json", ...authHeaders() },
body: JSON.stringify(data),
},
);
if (!response.ok) {
throw new ApiError(
`Edit failed: ${response.status} ${response.statusText}`,
response.status,
response.statusText,
);
}
const raw = (await response.json()) as RawRecording;
return mapRecording(raw);
}
async deleteRecording(id: string): Promise<void> {
const response = await fetch(
`${this.baseUrl}/api/v1/operations/${encodeURIComponent(id)}`,
{
method: "DELETE",
headers: authHeaders(),
},
);
if (!response.ok) {
throw new ApiError(
`Delete failed: ${response.status} ${response.statusText}`,
response.status,
response.statusText,
);
}
}
async retryConversion(id: string): Promise<void> {
const response = await fetch(
`${this.baseUrl}/api/v1/operations/${encodeURIComponent(id)}/retry`,
{
method: "POST",
headers: authHeaders(),
},
);
if (!response.ok) {
throw new ApiError(
`Retry failed: ${response.status} ${response.statusText}`,
response.status,
response.statusText,
);
}
}
async uploadRecording(formData: FormData): Promise<void> {
const response = await fetch(`${this.baseUrl}/api/v1/operations/add`, {
method: "POST",
headers: authHeaders(),
body: formData,
});
if (!response.ok) {
throw new ApiError(
`Upload failed: ${response.status} ${response.statusText}`,
response.status,
response.statusText,
);
}
}
// ─── Marker blacklist methods ───
async getMarkerBlacklist(operationId: string): Promise<number[]> {
return this.fetchJson<number[]>(
`${this.baseUrl}/api/v1/operations/${encodeURIComponent(operationId)}/marker-blacklist`,
);
}
async addMarkerBlacklist(
operationId: string,
playerEntityId: number,
): Promise<void> {
return this.fetchBlacklistUpdate(operationId, playerEntityId, "PUT");
}
async removeMarkerBlacklist(
operationId: string,
playerEntityId: number,
): Promise<void> {
return this.fetchBlacklistUpdate(operationId, playerEntityId, "DELETE");
}
private async fetchBlacklistUpdate(
operationId: string,
playerEntityId: number,
method: "PUT" | "DELETE",
): Promise<void> {
const response = await fetch(
`${this.baseUrl}/api/v1/operations/${encodeURIComponent(operationId)}/marker-blacklist/${playerEntityId}`,
{
method,
headers: authHeaders(),
},
);
if (!response.ok) {
const action = method === "PUT" ? "Add" : "Remove";
throw new ApiError(
`${action} blacklist failed: ${response.status} ${response.statusText}`,
response.status,
response.statusText,
);
}
}
// ─── MapTool methods ───
async getMapToolHealth(): Promise<HealthCheck[]> {
return this.fetchJsonAuth<HealthCheck[]>(`${this.baseUrl}/api/v1/maptool/health`);
}
async getMapToolTools(): Promise<ToolSet> {
return this.fetchJsonAuth<ToolSet>(`${this.baseUrl}/api/v1/maptool/tools`);
}
async getMapToolMaps(): Promise<MapInfo[]> {
return this.fetchJsonAuth<MapInfo[]>(`${this.baseUrl}/api/v1/maptool/maps`);
}
async deleteMapToolMap(name: string): Promise<void> {
const response = await fetch(
`${this.baseUrl}/api/v1/maptool/maps/${encodeURIComponent(name)}`,
{ method: "DELETE", headers: authHeaders() },
);
if (!response.ok) {
throw new ApiError(
`Delete map failed: ${response.status} ${response.statusText}`,
response.status,
response.statusText,
);
}
}
async importMapToolZip(
file: File,
onProgress?: (loaded: number, total: number) => void,
): Promise<JobInfo> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("POST", `${this.baseUrl}/api/v1/maptool/maps/import`);
const token = getAuthToken();
if (token) xhr.setRequestHeader("Authorization", `Bearer ${token}`);
if (onProgress) {
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) onProgress(e.loaded, e.total);
};
}
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(JSON.parse(xhr.responseText) as JobInfo);
} else {
reject(
new ApiError(
`Upload failed: ${xhr.status} ${xhr.statusText}`,
xhr.status,
xhr.statusText,
),
);
}
};
xhr.onerror = () =>
reject(new ApiError("Upload network error", 0, "Network Error"));
const formData = new FormData();
formData.append("file", file);
xhr.send(formData);
});
}
async restyleMapToolAll(): Promise<JobInfo> {
return this.fetchJsonAuth<JobInfo>(
`${this.baseUrl}/api/v1/maptool/maps/restyle`,
"POST",
);
}
async getMapToolJobs(): Promise<JobInfo[]> {
return this.fetchJsonAuth<JobInfo[]>(`${this.baseUrl}/api/v1/maptool/jobs`);
}
async cancelMapToolJob(id: string): Promise<void> {
const response = await fetch(
`${this.baseUrl}/api/v1/maptool/jobs/${encodeURIComponent(id)}/cancel`,
{ method: "POST", headers: authHeaders() },
);
if (!response.ok) {
throw new ApiError(
`Cancel job failed: ${response.status} ${response.statusText}`,
response.status,
response.statusText,
);
}
}
getMapToolEventsUrl(): string {
const token = getAuthToken();
return `${this.baseUrl}/api/v1/maptool/events${token ? `?token=${encodeURIComponent(token)}` : ""}`;
}
// ─── Internal fetch helpers ───
private async fetchJsonAuth<T>(
url: string,
method: string = "GET",
): Promise<T> {
const response = await fetch(url, {
method,
headers: authHeaders(),
cache: "no-cache",
});
if (!response.ok) {
throw new ApiError(
`${method} ${url} failed: ${response.status} ${response.statusText}`,
response.status,
response.statusText,
);
}
return response.json() as Promise<T>;
}
private async fetchJson<T>(url: string): Promise<T> {
const response = await fetch(url, { cache: "no-store" });
if (!response.ok) {
throw new ApiError(
`GET ${url} failed: ${response.status} ${response.statusText}`,
response.status,
response.statusText,
);
}
return response.json() as Promise<T>;
}
private async fetchBuffer(url: string): Promise<ArrayBuffer> {
const response = await fetch(url);
if (!response.ok) {
throw new ApiError(
`GET ${url} failed: ${response.status} ${response.statusText}`,
response.status,
response.statusText,
);
}
return response.arrayBuffer();
}
}