-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathbadgepresetio.js
More file actions
418 lines (367 loc) · 12.8 KB
/
Copy pathbadgepresetio.js
File metadata and controls
418 lines (367 loc) · 12.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
const PRESET_FILE_EXT = '.badgepreset';
const PRESET_FILE_ACCEPT = '.badgepreset,.json';
const PRESET_FILE_MAX_BYTES = 64 * 1024;
const PRESET_FILE_MAX_ROWS = 10; // max badge slot rows based on server
const PRESET_FILE_MAX_COLS = 7;
const BADGE_ID_PATTERN = /^[a-zA-Z0-9_]+$/;
let badgePresetImportInProgress = false; // lock import in progress
function getPresetIoMessage(key, fallback) {
return i18next.t(`modal.badgePreset.io.${key}`, fallback);
}
function showPresetIoSuccess(message) {
if (typeof showToastMessage === 'function')
showToastMessage(getMassagedLabel(message, true), 'info', true);
}
function getCurrentGridDimensions(fallbackSlots) {
const rows = typeof badgeSlotRows === 'number' && badgeSlotRows > 0
? badgeSlotRows
: (fallbackSlots?.length || 1);
const cols = typeof badgeSlotCols === 'number' && badgeSlotCols > 0
? badgeSlotCols
: (fallbackSlots?.[0]?.length || 3);
return { rows, cols };
}
function validateBadgeSlots(badgeSlots, maxRows, maxCols) {
if (!Array.isArray(badgeSlots))
return false;
if (maxRows && badgeSlots.length > maxRows)
return false;
const badgeIds = new Set();
for (const row of badgeSlots) {
if (!Array.isArray(row))
return false;
if (maxCols && row.length > maxCols)
return false;
for (const badgeId of row) {
if (badgeId === null || badgeId === 'null')
continue;
if (typeof badgeId !== 'string')
return false;
if (!BADGE_ID_PATTERN.test(badgeId))
return false;
if (badgeIds.has(badgeId)) // check for duplicate badge
return false;
badgeIds.add(badgeId);
}
}
return true;
}
function parsePresetFile(rawText, maxRows, maxCols) {
const parsed = JSON.parse(rawText);
let badgeSlots;
if (Array.isArray(parsed))
badgeSlots = parsed;
else if (parsed && Array.isArray(parsed.badgeSlots))
badgeSlots = parsed.badgeSlots;
else
return null;
if (!validateBadgeSlots(badgeSlots, maxRows, maxCols))
return null;
return badgeSlots;
}
function hasNonNullBadgeOutsideGrid(badgeSlots, rows, cols) {
for (let r = 0; r < badgeSlots.length; r++) {
const row = badgeSlots[r];
if (!Array.isArray(row))
continue;
for (let c = 0; c < row.length; c++) {
if (r >= rows || c >= cols) {
const badgeId = row[c];
if (badgeId != null && badgeId !== 'null')
return true;
}
}
}
return false;
}
function expandBadgeSlotsToGrid(badgeSlots, rows, cols) {
const expanded = [];
for (let r = 0; r < rows; r++) {
const expandedRow = [];
for (let c = 0; c < cols; c++) {
const badgeId = badgeSlots?.[r]?.[c];
if (badgeId == null || badgeId === 'null')
expandedRow.push('null');
else
expandedRow.push(badgeId);
}
expanded.push(expandedRow);
}
return expanded;
}
function computeChanges(targetSlots, currentSlots, rows, cols) {
const changes = [];
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const targetId = targetSlots[r]?.[c] ?? 'null';
const currentId = currentSlots[r]?.[c] ?? 'null';
if (targetId !== currentId)
changes.push({ r, c, targetId, currentId });
}
}
return changes;
}
function fetchSlotSet(badgeId, row, col) {
const encodedBadgeId = encodeURIComponent(badgeId);
return apiFetch(`badge?command=slotSet&id=${encodedBadgeId}&row=${row}&col=${col}`);
}
async function clearChangedSlotsFromChanges(changes) {
const tasks = changes
.filter(({ currentId }) => currentId !== 'null')
.map(({ r, c }) =>
fetchSlotSet('null', r + 1, c + 1)
.then(response => ({ ok: response.ok }))
.catch(() => ({ ok: false }))
);
return Promise.all(tasks);
}
async function placeNonNullSlots(changes) {
const skippedBadges = [];
const tasks = changes
.filter(({ targetId }) => targetId !== 'null')
.map(({ r, c, targetId }) => async () => {
try {
const response = await fetchSlotSet(targetId, r + 1, c + 1);
if (response.ok)
return { ok: true };
const message = await response.text();
if (message.includes('unknown badge') || message.includes('specified badge is locked')) {
const nullResponse = await fetchSlotSet('null', r + 1, c + 1);
if (nullResponse.ok) {
skippedBadges.push({
badgeId: targetId,
row: r + 1,
col: c + 1,
reason: message.includes('unknown badge') ? 'unknown' : 'locked'
});
}
return { ok: nullResponse.ok };
}
return { ok: false };
} catch {
return { ok: false };
}
});
const results = await Promise.all(tasks.map(task => task()));
return { results, skippedBadges };
}
function warnSkippedPresetBadges(skippedBadges) {
if (!skippedBadges.length)
return;
for (const skip of skippedBadges) {
const reason = skip.reason === 'locked'
? 'not unlocked'
: 'not owned or no longer exists!';
console.warn(`Badge preset import: omitted ${skip.badgeId} at row ${skip.row}, col ${skip.col} (${reason})`);
}
console.warn(`Badge preset import: ${skippedBadges.length} badge(s) were set to null.`);
}
async function rollbackSlots(backupSlots) {
if (!Array.isArray(backupSlots))
return true;
const promises = [];
for (let r = 0; r < backupSlots.length; r++) {
for (let c = 0; c < backupSlots[r].length; c++) {
const badgeId = backupSlots[r]?.[c] || 'null';
promises.push(
fetchSlotSet(badgeId, r + 1, c + 1)
.then(response => response.ok)
.catch(() => false)
);
}
}
const results = await Promise.all(promises);
return results.every(ok => ok);
}
async function getPresetData(presetId) {
const response = await apiFetch(`badge?command=presetGet&preset=${presetId}`);
if (!response.ok)
return null;
return response.json();
}
function formatExportFilename(presetIndex) {
const now = new Date();
const year = now.getFullYear();
const month = `${now.getMonth() + 1}`.padStart(2, '0');
const day = `${now.getDate()}`.padStart(2, '0');
const hour = `${now.getHours()}`.padStart(2, '0');
const minute = `${now.getMinutes()}`.padStart(2, '0');
const second = `${now.getSeconds()}`.padStart(2, '0');
const formattedDate = `${year}-${month}-${day}-${hour}h${minute}m${second}s`;
const presetNumber = `${(parseInt(presetIndex, 10) || 0) + 1}`.padStart(2, '0');
return `badge_preset_${presetNumber}-${formattedDate}${PRESET_FILE_EXT}`;
}
const PRESET_FILE_SAVE_TYPES = [{
description: 'Badge Preset',
accept: { 'application/json': ['.badgepreset', '.json'] }
}];
function downloadJSON(data, filename) {
const json = JSON.stringify(data, null, 2);
const blob = new Blob([json], { type: 'application/json' });
const blobUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = blobUrl;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(blobUrl);
}
async function handleExport() {
const presetSelection = document.getElementById('badgePresetSelection');
if (!presetSelection) {
alert(getPresetIoMessage('exportFailed', 'Export failed.'));
return;
}
try {
const presetId = presetSelection.value;
const filename = formatExportFilename(presetId);
let fileHandle;
if (typeof showSaveFilePicker === 'function') {
try {
fileHandle = await showSaveFilePicker({
suggestedName: filename,
types: PRESET_FILE_SAVE_TYPES
});
} catch (error) {
if (error instanceof DOMException && error.name === 'AbortError')
return;
throw error;
}
}
const presetSlots = await getPresetData(presetId);
if (!presetSlots) {
alert(getPresetIoMessage('exportFailed', 'Export failed.'));
return;
}
if (isEmptyBadgeSlots(presetSlots)) {
alert(getPresetIoMessage('empty', 'This preset is empty.'));
return;
}
const { rows, cols } = getCurrentGridDimensions(presetSlots);
const clampedRows = Math.min(rows, maxBadgeSlotRows);
const clampedCols = Math.min(cols, maxBadgeSlotCols);
const fullGridSlots = expandBadgeSlotsToGrid(presetSlots, clampedRows, clampedCols);
const exportData = { badgeSlots: fullGridSlots };
if (fileHandle) {
const writable = await fileHandle.createWritable();
await writable.write(JSON.stringify(exportData, null, 2));
await writable.close();
} else {
downloadJSON(exportData, filename);
}
showPresetIoSuccess(getPresetIoMessage('exportSuccess', 'Badge preset exported successfully.'));
} catch (error) {
console.error('Export failed:', error);
alert(getPresetIoMessage('exportFailed', 'Export failed.'));
}
}
async function applyPresetToSlot(badgeSlots) {
const presetModal = document.getElementById('badgePresetModal');
const presetSelection = document.getElementById('badgePresetSelection');
if (!presetSelection || typeof apiFetch !== 'function')
return false;
let backupSlots = null;
let changedServerSlots = false;
let success = false;
try {
if (presetModal && typeof addLoader === 'function')
addLoader(presetModal, true);
const backupResponse = await apiFetch('badge?command=slotList');
if (!backupResponse.ok)
return false;
backupSlots = await backupResponse.json();
const playerRows = backupSlots.length;
const playerCols = backupSlots[0]?.length || 0;
if (hasNonNullBadgeOutsideGrid(badgeSlots, playerRows, playerCols))
return false;
const normalizedSlots = expandBadgeSlotsToGrid(badgeSlots, playerRows, playerCols);
const changes = computeChanges(normalizedSlots, backupSlots, playerRows, playerCols);
const clearResults = await clearChangedSlotsFromChanges(changes);
const { results: placeResults, skippedBadges } = await placeNonNullSlots(changes);
changedServerSlots = true;
const allResults = [...clearResults, ...placeResults];
if (allResults.some(result => !result.ok))
return false;
const saveResponse = await apiFetch(`badge?command=presetSave&preset=${presetSelection.value}`);
if (!saveResponse.ok)
return false;
if (typeof initBadgePresetModal === 'function')
initBadgePresetModal();
success = true;
warnSkippedPresetBadges(skippedBadges);
return true;
} finally {
try {
if (changedServerSlots && backupSlots) {
const rolledBack = await rollbackSlots(backupSlots);
if (!rolledBack)
console.error('Badge preset import rollback failed');
}
} catch (error) {
console.error('Badge preset import rollback failed:', error);
} finally {
if (presetModal && typeof removeLoader === 'function')
removeLoader(presetModal);
}
if (success)
showPresetIoSuccess(getPresetIoMessage('importSuccess', 'Badge preset imported successfully.'));
}
}
function handleImport() {
const input = document.createElement('input');
input.type = 'file';
input.accept = PRESET_FILE_ACCEPT;
input.onchange = (event) => {
const file = event.target.files[0];
if (!file)
return;
if (file.size > PRESET_FILE_MAX_BYTES) {
alert(getPresetIoMessage('invalidFile', 'Invalid preset file.'));
return;
}
const reader = new FileReader();
reader.onload = async (loadEvent) => {
if (badgePresetImportInProgress) {
console.warn('Badge preset import already in progress.');
return;
}
badgePresetImportInProgress = true;
try {
const badgeSlots = parsePresetFile(loadEvent.target.result, PRESET_FILE_MAX_ROWS, PRESET_FILE_MAX_COLS);
if (!badgeSlots) {
alert(getPresetIoMessage('invalidFile', 'Invalid preset file.'));
return;
}
if (isEmptyBadgeSlots(badgeSlots)) {
alert(getPresetIoMessage('empty', 'This preset is empty.'));
return;
}
const imported = await applyPresetToSlot(badgeSlots);
if (!imported)
alert(getPresetIoMessage('importFailed', 'Import failed.'));
} catch (error) {
console.error('Import failed:', error);
alert(getPresetIoMessage('importFailed', 'Import failed.'));
} finally {
badgePresetImportInProgress = false;
}
};
reader.onerror = () => {
alert(getPresetIoMessage('invalidFile', 'Invalid preset file.'));
};
reader.readAsText(file);
};
input.click();
}
function initBadgePresetIO() {
const exportButton = document.getElementById('badgePresetExport');
const importButton = document.getElementById('badgePresetImport');
if (!exportButton || !importButton)
return;
if (exportButton.dataset.initialized === 'true')
return;
exportButton.onclick = handleExport;
importButton.onclick = handleImport;
exportButton.dataset.initialized = 'true';
}