-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcloudsave.js
598 lines (516 loc) · 21.1 KB
/
cloudsave.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
// anti dupe code:
if (window.saveloader) {
throw new error("CloudSave already loaded");
} else {
window.saveloader = true;
}
// Server libs
async function saveToServer(variableName, content) {
var serverURL = 'https://snapextensions.uni-goettingen.de/handleTextfile.php';
var url = serverURL + '?type=write' + '&content=' + encodeURIComponent(content) + '&filename=./textfiles/' + encodeURIComponent(variableName);
try {
let response = await fetch(url);
return (await response.text()) === 'ok';
} catch (error) {
console.error('Error saving', variableName, error);
return false;
}
}
async function loadFromServer(variableName) {
var serverURL = 'https://snapextensions.uni-goettingen.de/handleTextfile.php';
var url = serverURL + '?type=read' + '&filename=./textfiles/' + encodeURIComponent(variableName);
try {
let response = await fetch(url);
return (await response.text()).slice(0, -1);
} catch (error) {
console.error('Error loading', variableName, error);
return "ERROR: file does not exist";
}
}
async function loadUserData(filename) {
var passwordMD5hash = document.cookie.split('; ').find(row => row.startsWith('rufflesave=')).split('=')[1];
return await loadFromServer("Rufflesavedatafromid" + passwordMD5hash + filename);
}
async function saveUserData(filename, txtdata) {
var passwordMD5hash = document.cookie.split('; ').find(row => row.startsWith('rufflesave=')).split('=')[1];
return await saveToServer("Rufflesavedatafromid" + passwordMD5hash + filename, txtdata);
}
// ruffle vars
var rufflecontainer = document.body;
var shadowRoot = document;
setTimeout(function(){
var shadowHost = document.querySelector('#gameContainer > ruffle-object:nth-child(1)');
shadowRoot = shadowHost.shadowRoot;
rufflecontainer = shadowRoot.querySelector('#container');
addSaveIcon();
}, 500);
setTimeout(function(){
var shadowHost = document.querySelector('#gameContainer > ruffle-object:nth-child(1)');
shadowRoot = shadowHost.shadowRoot;
rufflecontainer = shadowRoot.querySelector('#container');
addSaveIcon();
}, 1500);
setTimeout(function(){
var shadowHost = document.querySelector('#gameContainer > ruffle-object:nth-child(1)');
shadowRoot = shadowHost.shadowRoot;
rufflecontainer = shadowRoot.querySelector('#container');
addSaveIcon();
}, 4000);
// everything else
function showNotification(message, color, time) {
let notification = document.createElement('div');
notification.id = 'saveNotification';
notification.textContent = message;
notification.style.position = 'fixed';
notification.style.bottom = '10px';
notification.style.left = '50%';
notification.style.transform = 'translateX(-50%)';
notification.style.backgroundColor = color;
notification.style.color = '#000';
notification.style.padding = '10px 20px';
notification.style.border = '1px solid #ccc';
notification.style.borderRadius = '5px';
notification.style.zIndex = '9999999999999999';
notification.style.opacity = '0';
notification.style.transition = 'opacity 1s ease-in-out';
notification.style.fontSize = '16px';
rufflecontainer.appendChild(notification);
setTimeout(() => {
notification.style.opacity = '1';
}, 10);
setTimeout(() => {
notification.style.opacity = '0';
setTimeout(() => notification.remove(), 1000);
}, time || 2000);
}
var savekeydebounce = false;
// Floppy disk save button
function addSaveIcon() {
const saveButton = document.createElement('div');
saveButton.textContent = '💾'; // Floppy disc emoji
saveButton.style.position = 'fixed';
saveButton.style.top = '10px';
saveButton.style.left = '10px';
saveButton.style.padding = '5px';
saveButton.style.fontSize = '30px';
saveButton.style.cursor = 'pointer';
saveButton.style.zIndex = '999999999';
saveButton.style.opacity = '1';
saveButton.style.transition = 'opacity 0.5s ease-in-out';
window.saveButton = saveButton;
saveButton.addEventListener('click', async function() {
if (savekeydebounce) {
showNotification("Spamming may corrupt your save data!", "#ffbaba");
return;
}
savekeydebounce = true;
saveButton.style.display = 'none';
showSaveProgressBar();
await savePackedData();
saveButton.style.display = 'block';
});
if (false) { // replaced by context menu button
rufflecontainer.appendChild(saveButton);
} else {
setTimeout(function(){
// showNotification("Always save with the context menu before leaving!", "#fff");
}, 1000);
}
}
// does not work on all games
document.addEventListener('keydown', async function(e) {
if (e.ctrlKey && e.key === 's') {
if (savekeydebounce) {
showNotification("Spamming may corrupt your save data!", "#ffbaba");
return;
}
savekeydebounce = true;
e.preventDefault();
showSaveProgressBar();
await savePackedData();
}
});
document.addEventListener('contextmenu', function(e) {
function addButton(text, onClick) {
const contextMenu = shadowRoot.querySelector('#context-menu');
if (contextMenu) {
const menuItem = document.createElement('li');
menuItem.className = 'menu-item';
menuItem.textContent = text;
menuItem.addEventListener('click', async function(e) {
e.preventDefault();
await onClick(e);
});
contextMenu.appendChild(menuItem);
}
}
function addSeparator() {
const contextMenu = shadowRoot.querySelector('#context-menu');
if (contextMenu) {
const separator = document.createElement('li');
separator.className = 'menu-separator';
separator.innerHTML = '<hr>';
contextMenu.appendChild(separator);
}
}
const contextMenu = shadowRoot.querySelector('#context-menu');
if (contextMenu && contextMenu.lastElementChild) {
contextMenu.removeChild(contextMenu.lastElementChild);
}
addButton('Back to games', async function() {
shadowRoot.querySelector('#context-menu-overlay').classList.add("hidden");
window.location.href = "/";
});
if (window.screen.height >= 300) {
addButton('Save data to cloud', async function() {
shadowRoot.querySelector('#context-menu-overlay').classList.add("hidden");
if (savekeydebounce) {
showNotification("Spamming may corrupt your save data!", "#ffbaba");
return;
}
savekeydebounce = true;
showSaveProgressBar();
await savePackedData();
});
}
});
setTimeout(function(){
const modalAreaDiv = shadowRoot.querySelector('#modal-area > div');
if (modalAreaDiv) {
const modalButton = document.createElement('span');
modalButton.className = 'modal-button';
modalButton.textContent = 'Save data to cloud';
modalButton.style.marginLeft = '5px';
modalButton.addEventListener('click', async function(e) {
e.preventDefault();
if (savekeydebounce) {
showNotification("Spamming may corrupt your save data!", "#ffbaba");
return;
}
savekeydebounce = true;
showSaveProgressBar();
await savePackedData();
});
modalAreaDiv.appendChild(modalButton);
}
}, 900);
// Save data in chunks of 1000 chars
async function savePackedData() {
console.log("Saving user data");
let allData = [];
Object.keys(localStorage).forEach(key => {
let solData = localStorage.getItem(key);
if (isB64SOL(solData, key)) {
allData.push({ key: key, value: solData });
}
});
let packedData = JSON.stringify(allData);
let chunks = packedData.match(/.{1,1000}/g); // Split into 1000-character chunks
try {
for (let i = 0; i < chunks.length; i++) {
await saveUserData(`completeSave_part${i + 1}`, chunks[i]);
updateSaveProgressBar((i + 1) / chunks.length * 50);
}
updateSaveProgressBar(50);
await saveUserData(`completeSave_part${chunks.length + 1}`, "end");
console.log("Checking save data...");
let partIndex = 0;
let allPartCheck = [];
let parsedData
try {
while (true) {
partIndex += 1;
updateSaveProgressBar((partIndex) / chunks.length * 50 + 50);
let partData = await loadUserData(`completeSave_part${partIndex}`);
if (partData === "end") break;
if (partData === "ERROR: file does not exist") {
showNotification("Failed to check save data: server responded with a 404", "#ffbaba");
hideSaveProgressBar();
savekeydebounce = false;
return;
} else {
allPartCheck.push(partData);
}
}
let combinedData = allPartCheck.join('');
parsedData = JSON.parse(combinedData).map(item => item.value);
} catch (error) {
showNotification("Failed to save packed data: " + error, "#ffbaba");
hideSaveProgressBar();
savekeydebounce = false;
return;
} finally {
let combinedData = allPartCheck.join('');
let parsedData = JSON.parse(combinedData);
let index = 0;
parsedData.forEach(item => {
index += 1;
if (!localStorage.getItem(item.key) == item.value) {
throw new Error(`Item "${index}: ${item.key}" saved incorrectly`);
}
});
hideSaveProgressBar();
savekeydebounce = false;
console.log("Data save finished.");
return true;
}
} catch (error) {
showNotification("Failed to save packed data: " + error, "#ffbaba");
console.error("Failed to save packed data: " + error);
}
}
// Show save progress bar
function showSaveProgressBar() {
hideSaveProgressBar();
const progressBarContainer = document.createElement('div');
progressBarContainer.id = 'saveProgressBarContainer';
progressBarContainer.style.position = 'absolute';
progressBarContainer.style.top = '0';
progressBarContainer.style.left = '0';
progressBarContainer.style.width = '100%';
progressBarContainer.style.height = '10px';
// progressBarContainer.style.backgroundColor = '#5475ba';
progressBarContainer.style.backgroundColor = 'rgba(255, 255, 255, 0.2)';
progressBarContainer.style.pointerEvents = "none";
progressBarContainer.style.zIndex = '99999999999';
progressBarContainer.style.border = '1px solid rgba(0, 0, 0, 0.2)';
progressBarContainer.style.opacity = '0'; // Start hidden
progressBarContainer.style.transform = 'translateY(-100%)'; // Slide up
progressBarContainer.style.transition = 'opacity 0.7s ease-in-out, transform 0.7s ease-in-out';
const progressBar = document.createElement('div');
progressBar.style.height = '100%';
progressBar.style.backgroundColor = '#4caf50';
progressBar.style.width = '0%';
progressBar.style.transition = 'width 0.5s ease-in-out';
progressBarContainer.appendChild(progressBar);
rufflecontainer.appendChild(progressBarContainer);
// Trigger the animation to show the bar
setTimeout(() => {
progressBarContainer.style.opacity = '1';
progressBarContainer.style.transform = 'translateY(0)'; // Slide down
}, 0);
window.saveProgressBar = progressBar; // Make progress bar accessible globally
}
// Update save progress bar
function updateSaveProgressBar(percentage) {
const progressBarContainer = shadowRoot.getElementById('saveProgressBarContainer');
if (progressBarContainer) {
const progressBar = progressBarContainer.firstChild;
progressBar.style.width = percentage + '%';
progressBarContainer.style.opacity = '1';
progressBarContainer.style.transform = 'translateY(0)';
}
}
// Hide save progress bar
function hideSaveProgressBar() {
const progressBarContainer = shadowRoot.getElementById('saveProgressBarContainer');
if (progressBarContainer) {
const progressBar = progressBarContainer.firstChild;
progressBar.style.width = '100%';
}
setTimeout(() => {
const progressBarContainer = shadowRoot.getElementById('saveProgressBarContainer');
if (progressBarContainer) {
progressBarContainer.style.opacity = '0'; // Fade out
progressBarContainer.style.transform = 'translateY(-100%)'; // Slide up
setTimeout(() => {
if (progressBarContainer.style.opacity == '0') {
progressBarContainer.remove();
window.saveProgressBar = null; // Clear reference to avoid issues
}
}, 500); // Wait for animation to finish
}
}, 700);
}
// Load data and refresh the page
async function loadPackedData() {
let allParts = [];
let partIndex = 1;
let partData;
// Object.keys(localStorage).forEach(key => {
// let solData = localStorage.getItem(key);
// if (isB64SOL(solData, key)) {
// localStorage.removeItem(key);
// }
// });
showLoadingBar();
try {
while (true) {
partData = await loadUserData(`completeSave_part${partIndex}`);
if (partData === "end") break;
if (partData === "ERROR: file does not exist") {
if (confirm("Data load error, continue?")) {
break
} else {
if (confirm("Replace cloud data with local data?")) {
const overlay = document.createElement('div');
overlay.id = 'loadingOverlay';
overlay.style.position = 'fixed';
overlay.style.top = '0';
overlay.style.left = '0';
overlay.style.width = '100%';
overlay.style.height = '100%';
overlay.style.backgroundColor = '#37528c';
overlay.style.zIndex = '99999999';
overlay.style.transition = 'opacity 0.5s ease-in-out';
document.body.appendChild(overlay);
setTimeout(async function(){
let ruffleObject = document.querySelector('#gameContainer > ruffle-object:nth-child(1)');
if (ruffleObject) {
ruffleObject.remove();
}
showSaveProgressBar();
await savePackedData();
setTimeout(() => {
window.location.reload();
}, 1000);
}, 100);
return;
} else {
window.location.href = "/";
}
}
}
allParts.push(partData);
partIndex++;
updateLoadingBar((partIndex - 1) / partIndex * 100); // Update loading progress
}
let combinedData = allParts.join('');
let parsedData = JSON.parse(combinedData);
parsedData.forEach(item => {
localStorage.setItem(item.key, item.value);
});
console.log("Data loaded successfully.");
} catch (error) {
console.error("Failed to load packed data", error);
} finally {
hideLoadingBar(); // Hide loading bar after loading
}
}
// Show loading progress bar in Ruffle container
function showLoadingBar() {
const loadingBarContainer = document.createElement('div');
loadingBarContainer.id = 'loadingProgressBarContainer';
loadingBarContainer.style.position = 'absolute';
loadingBarContainer.style.top = '0';
loadingBarContainer.style.left = '0';
loadingBarContainer.style.width = '100%';
loadingBarContainer.style.height = '10px';
// loadingBarContainer.style.backgroundColor = '#5475ba';
// loadingBarContainer.style.backgroundColor = 'rgba(255, 255, 255, 0.2)';
loadingBarContainer.style.pointerEvents = "none";
loadingBarContainer.style.zIndex = '99999999999';
loadingBarContainer.style.opacity = '0'; // Start hidden
loadingBarContainer.style.transform = 'translateY(-100%)'; // Slide up
loadingBarContainer.style.transition = 'opacity 0.7s ease-in-out, transform 0.7s ease-in-out';
const loadingBar = document.createElement('div');
loadingBar.style.height = '100%';
loadingBar.style.backgroundColor = '#fff';
loadingBar.style.width = '0%';
loadingBar.style.transition = 'width 0.5s ease-in-out';
loadingBarContainer.appendChild(loadingBar);
rufflecontainer.appendChild(loadingBarContainer);
// Trigger the animation to show the bar
setTimeout(() => {
loadingBarContainer.style.opacity = '1';
loadingBarContainer.style.transform = 'translateY(0)'; // Slide down
}, 100);
window.loadingProgressBar = loadingBar; // Make loading progress bar accessible globally
}
// Update loading progress bar
function updateLoadingBar(percentage) {
if (window.loadingProgressBar) {
window.loadingProgressBar.style.width = percentage + '%';
}
}
// Hide loading progress bar
function hideLoadingBar() {
window.loadingProgressBar.style.width = '100%';
setTimeout(() => {
const loadingBarContainer = document.getElementById('loadingProgressBarContainer');
if (loadingBarContainer) {
loadingBarContainer.style.opacity = '0'; // Fade out
loadingBarContainer.style.transform = 'translateY(-100%)'; // Slide up
setTimeout(() => {
loadingBarContainer.remove();
window.loadingProgressBar = null; // Clear reference to avoid issues
}, 700); // Wait for animation to finish
}
}, 300);
}
// Automatically load data when the page starts, then reload
async function autoLoadAndReload() {
if (!document.cookie.split('; ').find(row => row.startsWith('dataLoaded='))) {
const overlay = document.createElement('div');
overlay.id = 'loadingOverlay';
overlay.style.position = 'fixed';
overlay.style.top = '0';
overlay.style.left = '0';
overlay.style.width = '100%';
overlay.style.height = '100%';
overlay.style.backgroundColor = '#37528c';
overlay.style.zIndex = '9999999999';
overlay.style.transition = 'opacity 0.5s ease-in-out';
document.body.appendChild(overlay);
// Remove current Ruffle instance
let ruffleObject = document.querySelector('#gameContainer > ruffle-object:nth-child(1)');
if (ruffleObject) {
ruffleObject.remove();
} setTimeout(function(){
ruffleObject = document.querySelector('#gameContainer > ruffle-object:nth-child(1)');
if (ruffleObject) {
ruffleObject.remove();
}
}, 1000);
await loadPackedData();
document.cookie = 'dataLoaded=true; max-age=60'; // Prevent endless reloading
setTimeout(() => {
location.reload();
}, 700);
}
}
// Utility function to check if the data is Base64 SOL
function isB64SOL(str, name) {// return true;
try {
let decodedData = atob(str);
return decodedData.slice(6, 10) === 'TCSO' || name != "loadedData";
} catch(e) {
return name != "loadedData";
}
}
// Initialize the automatic load and reload process
if (!new URLSearchParams(window.location.search).get('transfer')) {
if (window.location.hash) { // disables auto load / save for local games
autoLoadAndReload();
setInterval(async function(){
if (!shadowRoot.getElementById('saveProgressBarContainer') && document.hasFocus()){
showSaveProgressBar();
await savePackedData();
}
}, 60 * (3) * 1000); // 3 mins save interval
}
} else {
const overlay = document.createElement('div');
overlay.id = 'loadingOverlay';
overlay.style.position = 'fixed';
overlay.style.top = '0';
overlay.style.left = '0';
overlay.style.width = '100%';
overlay.style.height = '100%';
// overlay.style.backgroundColor = 'rgba(255, 255, 255, 1)';
overlay.style.backgroundColor = '#37528c';
overlay.style.zIndex = '99999999';
overlay.style.transition = 'opacity 0.5s ease-in-out';
document.body.appendChild(overlay);
setTimeout(async function(){
let ruffleObject = document.querySelector('#gameContainer > ruffle-object:nth-child(1)');
if (ruffleObject) {
ruffleObject.remove();
}
showSaveProgressBar();
await savePackedData();
setTimeout(() => {
window.location.href = "/";
}, 700);
}, 100);
}