-
Notifications
You must be signed in to change notification settings - Fork 82
/
savedata.js
414 lines (348 loc) · 14.4 KB
/
savedata.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
const saveSyncSlotId = 1;
function initSaveSyncControls() {
document.getElementById('clearSaveSyncButton').onclick = function () {
showConfirmModal(localizedMessages.saveSync.confirmClearSaveSync, () => {
const button = this;
clearSaveSyncData().then(success => {
if (success)
button.setAttribute('disabled', true);
})
});
};
if (getCookie(sessionIdKey)) {
apiFetch('savesync?command=timestamp')
.then(response => {
if (!response.ok)
throw new Error('Failed to retrieve timestamp for save sync data');
return response.text();
})
.then(timestamp => {
const clearSaveSyncButton = document.getElementById('clearSaveSyncButton');
if (timestamp)
clearSaveSyncButton.removeAttribute('disabled');
else
clearSaveSyncButton.setAttribute('disabled', true);
});
}
}
function initSaveDataControls() {
document.getElementById('saveButton').onclick = () => {
updateSaveSlotList();
openModal('saveModal');
};
document.getElementById('saveModalReloadButton').onclick = () => window.location = window.location;
}
function updateSaveSlotList() {
const saveSlotList = document.getElementById('saveSlotList');
saveSlotList.innerHTML = '';
for (let s = 1; s <= 15; s++) {
saveSlotList.appendChild(getSaveSlotListEntry(s));
}
}
function getSaveSlotListEntry(slotId) {
const slot = document.createElement('div');
slot.classList.add('saveSlotListEntry', 'listEntry');
slot.dataset.slotId = slotId;
updateThemedContainer(slot);
const title = document.createElement('label');
title.innerHTML = getMassagedLabel(localizedMessages.save.slot.title, true).replace('{SLOT_ID}', slotId);
slot.appendChild(title);
const content = document.createElement('div');
content.classList.add('saveSlotListEntryContent');
const contentLabel = document.createElement('label');
contentLabel.innerHTML = getMassagedLabel(localizedMessages.save.slot.readingLabel, true);
content.appendChild(contentLabel);
const buttonsContainer = document.createElement('div');
buttonsContainer.classList.add('saveSlotButtonsContainer');
const uploadButton = getSvgIcon('saveUpload');
uploadButton.classList.add('saveSlotUploadButton', 'saveSlotButton', 'unselectable', 'iconButton');
uploadButton.onclick = () => {
let saveFile = document.getElementById('saveFile');
if (saveFile)
saveFile.remove();
saveFile = document.createElement('input');
saveFile.type = 'file';
saveFile.id = 'saveFile';
saveFile.style.display = 'none';
saveFile.addEventListener('change',
e => uploadSaveFile(e.target.files[0], formatSaveSlotId(slotId))
.then(success => {
const reloadButton = document.getElementById('saveModalReloadButton');
if (success) {
if (reloadButton.classList.contains('hidden'))
setTimeout(() => reloadButton.classList.remove('hidden'), 100);
slot.insertAdjacentElement('afterend', getSaveSlotListEntry(slotId));
slot.remove();
}
})
);
saveFile.click();
};
addTooltip(uploadButton, getMassagedLabel(localizedMessages.save.upload.tooltip, true), true, true);
const downloadButton = getSvgIcon('saveDownload');
downloadButton.classList.add('saveSlotDownloadButton', 'saveSlotButton', 'unselectable', 'iconButton', 'hidden');
downloadButton.onclick = () => downloadSaveFile(formatSaveSlotId(slotId));
addTooltip(downloadButton, getMassagedLabel(localizedMessages.save.download.tooltip, true), true, true);
const deleteButton = getSvgIcon('delete');
deleteButton.classList.add('saveSlotDeleteButton', 'saveSlotButton', 'unselectable', 'iconButton', 'hidden');
deleteButton.onclick = () => deleteSaveFile(formatSaveSlotId(slotId))
.then(success => {
const reloadButton = document.getElementById('saveModalReloadButton');
if (success) {
if (reloadButton.classList.contains('hidden'))
setTimeout(() => reloadButton.classList.remove('hidden'), 100);
slot.insertAdjacentElement('afterend', getSaveSlotListEntry(slotId));
slot.remove();
}
});
addTooltip(deleteButton, getMassagedLabel(localizedMessages.save.delete.tooltip, true), true, true);
buttonsContainer.appendChild(uploadButton);
buttonsContainer.appendChild(downloadButton);
buttonsContainer.appendChild(deleteButton);
content.appendChild(buttonsContainer);
slot.appendChild(content);
getSaveSlotData(slotId)
.then(saveData => {
contentLabel.innerHTML = saveData == null
? getMassagedLabel(localizedMessages.save.slot.emptyLabel, true)
: saveData.timestamp.toLocaleString(globalConfig.lang === 'en' ? [] : globalConfig.lang, { "dateStyle": "short", "timeStyle": "short" });
if (saveData != null) {
contentLabel.classList.add('altText');
downloadButton.classList.remove('hidden');
deleteButton.classList.remove('hidden');
}
})
.catch(err => {
contentLabel.innerHTML = getMassagedLabel(localizedMessages.save.slot.errorLabel, true);
console.error(err);
})
return slot;
}
function uploadSaveFile(file, saveSlot) {
return new Promise(resolve => {
if (!file || !saveSlot)
return resolve(false);
if (!/\.lsd$/i.test(file.name)) {
alert(localizedMessages.io.upload.invalidSaveFile);
document.getElementById('uploadButton').click();
return;
}
const request = indexedDB.open(`/easyrpg/${ynoGameId}/Save`);
request.onsuccess = function (_e) {
const reader = new FileReader();
let readerResult;
reader.onload = file => {
readerResult = file.currentTarget.result;
const saveFile = { timestamp: new Date(), mode: 33206, contents: new Uint8Array(readerResult) };
const db = request.result;
const transaction = db.transaction(['FILE_DATA'], 'readwrite');
const objectStorePutRequest = transaction.objectStore('FILE_DATA').put(saveFile, `/easyrpg/${ynoGameId}/Save/Save${saveSlot}.lsd`);
objectStorePutRequest.onsuccess = () => resolve(true);
objectStorePutRequest.onerror = () => resolve(false);
};
reader.onerror = () => resolve(false);
reader.readAsArrayBuffer(file);
};
request.onerror = () => resolve(false);
});
}
function downloadSaveFile(saveSlot) {
return new Promise(resolve => {
if (!saveSlot)
return resolve(false);
const request = indexedDB.open(`/easyrpg/${ynoGameId}/Save`);
request.onsuccess = function (_e) {
const db = request.result;
const transaction = db.transaction(['FILE_DATA'], 'readwrite');
const objectStore = transaction.objectStore('FILE_DATA');
const objectStoreRequest = objectStore.get(`/easyrpg/${ynoGameId}/Save/Save${saveSlot}.lsd`);
objectStoreRequest.onsuccess = function (_e) {
const record = objectStoreRequest.result;
if (!record) {
alert(localizedMessages.io.download.emptySlot);
resolve(false);
}
const blob = new Blob([record.contents], {type: 'text/json'});
const date = record.timestamp;
const link = document.createElement('a');
const [month, day, year, hour, minute, second] = [date.getMonth(), date.getDate(), date.getFullYear(), date.getHours(), date.getMinutes(), date.getSeconds()];
const formattedDate = `${year}-${(month + 1).toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}-${hour.toString().padStart(2, '0')}h${minute.toString().padStart(2, '0')}m${second.toString().padStart(2, '0')}s`;
link.href = window.URL.createObjectURL(blob);
link.download = `${ynoGameId}_Save${saveSlot}_${formattedDate}.lsd`;
link.click();
link.remove();
resolve(true);
};
objectStoreRequest.onerror = () => resolve(false);
};
request.onerror = () => resolve(false);
});
}
function deleteSaveFile(saveSlot) {
return new Promise(resolve => {
if (!saveSlot)
return resolve(false);
showConfirmModal(localizedMessages.save.delete.confirmDelete.replace('{SLOT_ID}', parseInt(saveSlot)), () => {
const request = indexedDB.open(`/easyrpg/${ynoGameId}/Save`);
request.onsuccess = function (_e) {
const db = request.result;
const transaction = db.transaction(['FILE_DATA'], 'readwrite');
const objectStoreDeleteRequest = transaction.objectStore('FILE_DATA').delete(`/easyrpg/${ynoGameId}/Save/Save${saveSlot}.lsd`);
objectStoreDeleteRequest.onsuccess = () => resolve(true);
objectStoreDeleteRequest.onerror = () => resolve(false);
};
request.onerror = () => resolve(false);
}, () => resolve(false));
});
}
function getSaveSlotData(saveSlotId) {
return new Promise(resolve => {
if (!saveSlotId)
resolve(null);
const slotId = saveSlotId < 10 ? `0${saveSlotId}` : saveSlotId.toString();
const request = indexedDB.open(`/easyrpg/${ynoGameId}/Save`);
request.onupgradeneeded = e => e.target.result.createObjectStore('FILE_DATA');
request.onsuccess = function (_e) {
const db = request.result;
const transaction = db.transaction(['FILE_DATA'], 'readwrite');
const objectStore = transaction.objectStore('FILE_DATA');
const objectStoreRequest = objectStore.get(`/easyrpg/${ynoGameId}/Save/Save${slotId}.lsd`);
objectStoreRequest.onsuccess = () => resolve(objectStoreRequest.result);
objectStoreRequest.onerror = () => resolve(null);
};
});
}
function formatSaveSlotId(saveSlotId) {
if (saveSlotId < 1)
saveSlotId = 1;
else if (saveSlotId > 15)
saveSlotId = 15;
return saveSlotId < 10 ? `0${saveSlotId}` : saveSlotId.toString();
}
// EXTERNAL
function onSaveSlotUpdated(slotId) {
if (loginToken && slotId == saveSyncSlotId)
getAndUploadSaveSyncData();
}
function hasSaveDataForSync() {
return new Promise(resolve => {
const request = indexedDB.open(`/easyrpg/${ynoGameId}/Save`);
request.onsuccess = function (_e) {
const db = request.result;
const transaction = db.transaction(['FILE_DATA'], 'readwrite');
const objectStore = transaction.objectStore('FILE_DATA');
const objectStoreRequest = objectStore.get(`/easyrpg/${ynoGameId}/Save/Save${saveSyncSlotId}.lsd`);
objectStoreRequest.onsuccess = () => resolve(true);
objectStoreRequest.onerror = () => resolve(false);
};
});
}
function getSaveDataForSync() {
return getSaveSlotData(saveSyncSlotId);
}
function uploadSaveSyncData(saveData) {
return new Promise(resolve => {
if (!loginToken)
resolve(false);
showSaveSyncToastMessage('saveUploading', 'saveUpload', saveSyncSlotId);
apiPost('savesync?command=push', saveData.contents)
.then(_ => {
showSaveSyncToastMessage('saveUploaded', 'save', saveSyncSlotId);
resetSaveReminder();
resolve(true);
})
.catch(_err => resolve(false));
});
}
function getAndUploadSaveSyncData() {
return new Promise(resolve => {
getSaveDataForSync().then(saveData => uploadSaveSyncData(saveData).then(success => resolve(success)));
});
}
function trySyncSave() {
return new Promise(resolve => {
apiFetch('savesync?command=timestamp')
.then(response => {
if (!response.ok)
throw new Error('Failed to retrieve timestamp for save sync data');
return response.text();
})
.then(timestamp => {
getSaveDataForSync().then(saveData => {
if (timestamp && (timestamp = new Date(timestamp)) && (!saveData || saveData.timestamp < timestamp)) {
apiFetch('savesync?command=get').then(response => {
if (!response.ok)
throw new Error('Failed to get save sync data');
return response.arrayBuffer();
})
.then(saveSyncData => {
if (saveSyncData) {
saveSyncData = new Uint8Array(saveSyncData);
const request = indexedDB.open(`/easyrpg/${ynoGameId}/Save`);
request.onsuccess = function (_e) {
const slotId = saveSyncSlotId < 10 ? `0${saveSyncSlotId}` : saveSyncSlotId.toString();
const db = request.result;
const transaction = db.transaction(['FILE_DATA'], 'readwrite');
const objectStorePutRequest = transaction.objectStore('FILE_DATA').put({ timestamp: timestamp, mode: 33206, contents: new Uint8Array(saveSyncData) }, `/easyrpg/${ynoGameId}/Save/Save${slotId}.lsd`);
objectStorePutRequest.onsuccess = _e => {
showSaveSyncToastMessage('saveDownloaded', 'save', saveSyncSlotId);
resolve(true);
};
objectStorePutRequest.onerror = _err => resolve(false);
};
request.onerror = _err => resolve(false);
} else
resolve(false);
})
.catch(err => {
console.error(err);
resolve(false);
})
} else {
showSaveSyncToastMessage('saveUpToDate', 'save', saveSyncSlotId);
resolve(false);
}
});
})
.catch(err => {
console.error(err);
resolve(false);
});
})
}
function clearSaveSyncData() {
return new Promise(resolve => {
if (!loginToken)
resolve(false);
apiFetch(`savesync?command=clear`)
.then(_ => {
showSaveSyncToastMessage('saveCleared', 'save');
resolve(true);
})
.catch(_err => resolve(false));
});
}
let saveDataToastQueue = [];
let saveDataToastTimer = null;
function showSaveSyncToastMessage(key, icon, slotId) {
if (!notificationConfig.saveSync.all || !notificationConfig.saveSync[key])
return;
if (typeof localizedMessages !== 'undefined' && localizedMessages) {
let message = getMassagedLabel(localizedMessages.toast.saveSync[key], true);
if (slotId !== undefined)
message = message.replace('{SLOT}', slotId);
showToastMessage(message, icon);
} else {
if (!saveDataToastTimer) {
saveDataToastTimer = setInterval(() => {
if (typeof localizedMessages !== 'undefined' && localizedMessages) {
for (let toast of saveDataToastQueue)
showSaveSyncToastMessage(toast.key, toast.icon, toast.slotId);
clearInterval(saveDataToastTimer);
saveDataToastTimer = null;
}
}, 100);
}
saveDataToastQueue.push({ key: key, icon: icon, slotId: slotId });
}
}