Implement hybrid saving for optimization

pull/841/head
Flashfyre 2024-05-13 18:17:57 -04:00
parent 7e5c7fb4f7
commit b45cd2f7e7
2 changed files with 48 additions and 58 deletions

View File

@ -775,7 +775,7 @@ export class EncounterPhase extends BattlePhase {
this.scene.ui.setMode(Mode.MESSAGE).then(() => { this.scene.ui.setMode(Mode.MESSAGE).then(() => {
if (!this.loaded) { if (!this.loaded) {
this.scene.gameData.saveAll(this.scene, true).then(success => { this.scene.gameData.saveAll(this.scene, true, battle.waveIndex % 5 === 1).then(success => {
this.scene.disableMenu = false; this.scene.disableMenu = false;
if (!success) if (!success)
return this.scene.reset(true); return this.scene.reset(true);

View File

@ -277,7 +277,7 @@ export class GameData {
const maxIntAttrValue = Math.pow(2, 31); const maxIntAttrValue = Math.pow(2, 31);
const systemData = JSON.stringify(data, (k: any, v: any) => typeof v === 'bigint' ? v <= maxIntAttrValue ? Number(v) : v.toString() : v); const systemData = JSON.stringify(data, (k: any, v: any) => typeof v === 'bigint' ? v <= maxIntAttrValue ? Number(v) : v.toString() : v);
if (!bypassLogin) { if (!bypassLogin && !localStorage.getItem('data')) {
Utils.apiPost(`savedata/update?datatype=${GameDataType.SYSTEM}`, systemData, undefined, true) Utils.apiPost(`savedata/update?datatype=${GameDataType.SYSTEM}`, systemData, undefined, true)
.then(response => response.text()) .then(response => response.text())
.then(error => { .then(error => {
@ -293,12 +293,15 @@ export class GameData {
console.error(error); console.error(error);
return resolve(false); return resolve(false);
} }
localStorage.removeItem('data');
resolve(true); resolve(true);
}); });
} else { } else {
localStorage.setItem('data_bak', localStorage.getItem('data')); const encFunc = bypassLogin
? (data: string) => btoa(data)
: (data: string) => AES.encrypt(data, saveKey);
localStorage.setItem('data', btoa(systemData)); localStorage.setItem('data', encFunc(systemData));
this.scene.ui.savingIcon.hide(); this.scene.ui.savingIcon.hide();
@ -309,7 +312,7 @@ export class GameData {
public loadSystem(): Promise<boolean> { public loadSystem(): Promise<boolean> {
return new Promise<boolean>(resolve => { return new Promise<boolean>(resolve => {
if (bypassLogin && !localStorage.hasOwnProperty('data')) if (bypassLogin && !localStorage.getItem('data'))
return resolve(false); return resolve(false);
const handleSystemData = (systemDataStr: string) => { const handleSystemData = (systemDataStr: string) => {
@ -421,7 +424,7 @@ export class GameData {
} }
} }
if (!bypassLogin) { if (!bypassLogin && !localStorage.getItem('data')) {
Utils.apiFetch(`savedata/get?datatype=${GameDataType.SYSTEM}`, true) Utils.apiFetch(`savedata/get?datatype=${GameDataType.SYSTEM}`, true)
.then(response => response.text()) .then(response => response.text())
.then(response => { .then(response => {
@ -439,8 +442,12 @@ export class GameData {
handleSystemData(response); handleSystemData(response);
}); });
} else } else {
handleSystemData(atob(localStorage.getItem('data'))); const decFunc = bypassLogin
? (data: string) => atob(data)
: (data: string) => AES.decrypt(data, saveKey).toString(enc.Utf8);
handleSystemData(decFunc(localStorage.getItem('data')));
}
}); });
} }
@ -557,40 +564,6 @@ export class GameData {
} as SessionSaveData; } as SessionSaveData;
} }
saveSession(scene: BattleScene, skipVerification?: boolean): Promise<boolean> {
return new Promise<boolean>(resolve => {
Utils.executeIf(!skipVerification, updateUserInfo).then(success => {
if (success !== null && !success)
return resolve(false);
const sessionData = this.getSessionSaveData(scene);
if (!bypassLogin) {
Utils.apiPost(`savedata/update?datatype=${GameDataType.SESSION}&slot=${scene.sessionSlotId}&trainerId=${this.trainerId}&secretId=${this.secretId}`, JSON.stringify(sessionData), undefined, true)
.then(response => response.text())
.then(error => {
if (error) {
if (error.startsWith('session out of date')) {
this.scene.clearPhaseQueue();
this.scene.unshiftPhase(new ReloadSessionPhase(this.scene));
}
console.error(error);
return resolve(false);
}
console.debug('Session data saved');
resolve(true);
});
} else {
localStorage.setItem(`sessionData${scene.sessionSlotId ? scene.sessionSlotId : ''}`, btoa(JSON.stringify(sessionData)));
console.debug('Session data saved');
resolve(true);
}
});
});
}
getSession(slotId: integer): Promise<SessionSaveData> { getSession(slotId: integer): Promise<SessionSaveData> {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
if (slotId < 0) if (slotId < 0)
@ -605,7 +578,7 @@ export class GameData {
} }
}; };
if (!bypassLogin) { if (!bypassLogin && !localStorage.getItem(`sessionData${slotId ? slotId : ''}`)) {
Utils.apiFetch(`savedata/get?datatype=${GameDataType.SESSION}&slot=${slotId}`, true) Utils.apiFetch(`savedata/get?datatype=${GameDataType.SESSION}&slot=${slotId}`, true)
.then(response => response.text()) .then(response => response.text())
.then(async response => { .then(async response => {
@ -618,9 +591,12 @@ export class GameData {
}); });
} else { } else {
const sessionData = localStorage.getItem(`sessionData${slotId ? slotId : ''}`); const sessionData = localStorage.getItem(`sessionData${slotId ? slotId : ''}`);
if (sessionData) if (sessionData) {
await handleSessionData(atob(sessionData)); const decFunc = bypassLogin
else ? (data: string) => atob(data)
: (data: string) => AES.decrypt(data, saveKey).toString(enc.Utf8);
await handleSessionData(decFunc(sessionData));
} else
return resolve(null); return resolve(null);
} }
}); });
@ -731,7 +707,7 @@ export class GameData {
deleteSession(slotId: integer): Promise<boolean> { deleteSession(slotId: integer): Promise<boolean> {
return new Promise<boolean>(resolve => { return new Promise<boolean>(resolve => {
if (bypassLogin) { if (bypassLogin) {
localStorage.removeItem('sessionData'); localStorage.removeItem(`sessionData${this.scene.sessionSlotId ? this.scene.sessionSlotId : ''}`);
return resolve(true); return resolve(true);
} }
@ -741,6 +717,7 @@ export class GameData {
Utils.apiFetch(`savedata/delete?datatype=${GameDataType.SESSION}&slot=${slotId}`, true).then(response => { Utils.apiFetch(`savedata/delete?datatype=${GameDataType.SESSION}&slot=${slotId}`, true).then(response => {
if (response.ok) { if (response.ok) {
loggedInUser.lastSessionSlot = -1; loggedInUser.lastSessionSlot = -1;
localStorage.removeItem(`sessionData${this.scene.sessionSlotId ? this.scene.sessionSlotId : ''}`);
resolve(true); resolve(true);
} }
return response.text(); return response.text();
@ -771,8 +748,10 @@ export class GameData {
return resolve([false, false]); return resolve([false, false]);
const sessionData = this.getSessionSaveData(scene); const sessionData = this.getSessionSaveData(scene);
Utils.apiPost(`savedata/clear?slot=${slotId}&trainerId=${this.trainerId}&secretId=${this.secretId}`, JSON.stringify(sessionData), undefined, true).then(response => { Utils.apiPost(`savedata/clear?slot=${slotId}&trainerId=${this.trainerId}&secretId=${this.secretId}`, JSON.stringify(sessionData), undefined, true).then(response => {
if (response.ok) if (response.ok) {
loggedInUser.lastSessionSlot = -1; loggedInUser.lastSessionSlot = -1;
localStorage.removeItem(`sessionData${this.scene.sessionSlotId ? this.scene.sessionSlotId : ''}`);
}
return response.json(); return response.json();
}).then(jsonResponse => { }).then(jsonResponse => {
if (!jsonResponse.error) if (!jsonResponse.error)
@ -825,13 +804,12 @@ export class GameData {
}) as SessionSaveData; }) as SessionSaveData;
} }
saveAll(scene: BattleScene, skipVerification?: boolean): Promise<boolean> { saveAll(scene: BattleScene, skipVerification: boolean = false, sync: boolean = false): Promise<boolean> {
return new Promise<boolean>(resolve => { return new Promise<boolean>(resolve => {
Utils.executeIf(!skipVerification, updateUserInfo).then(success => { Utils.executeIf(!skipVerification, updateUserInfo).then(success => {
if (success !== null && !success) if (success !== null && !success)
return resolve(false); return resolve(false);
this.scene.ui.savingIcon.show(); this.scene.ui.savingIcon.show();
const data = this.getSystemSaveData();
const sessionData = this.getSessionSaveData(scene); const sessionData = this.getSessionSaveData(scene);
const maxIntAttrValue = Math.pow(2, 31); const maxIntAttrValue = Math.pow(2, 31);
@ -843,7 +821,7 @@ export class GameData {
sessionSlotId: scene.sessionSlotId sessionSlotId: scene.sessionSlotId
}; };
if (!bypassLogin) { if (!bypassLogin && sync) {
Utils.apiPost('savedata/updateall', JSON.stringify(request, (k: any, v: any) => typeof v === 'bigint' ? v <= maxIntAttrValue ? Number(v) : v.toString() : v), undefined, true) Utils.apiPost('savedata/updateall', JSON.stringify(request, (k: any, v: any) => typeof v === 'bigint' ? v <= maxIntAttrValue ? Number(v) : v.toString() : v), undefined, true)
.then(response => response.text()) .then(response => response.text())
.then(error => { .then(error => {
@ -859,14 +837,18 @@ export class GameData {
console.error(error); console.error(error);
return resolve(false); return resolve(false);
} }
localStorage.removeItem('data');
localStorage.removeItem(`sessionData${scene.sessionSlotId ? scene.sessionSlotId : ''}`);
resolve(true); resolve(true);
}); });
} else { } else {
localStorage.setItem('data_bak', localStorage.getItem('data')); const encFunc = bypassLogin
? (data: string) => btoa(data)
: (data: string) => AES.encrypt(data, saveKey);
localStorage.setItem('data', btoa(JSON.stringify(systemData, (k: any, v: any) => typeof v === 'bigint' ? v <= maxIntAttrValue ? Number(v) : v.toString() : v))); localStorage.setItem('data', encFunc(JSON.stringify(systemData, (k: any, v: any) => typeof v === 'bigint' ? v <= maxIntAttrValue ? Number(v) : v.toString() : v)));
localStorage.setItem(`sessionData${scene.sessionSlotId ? scene.sessionSlotId : ''}`, btoa(JSON.stringify(sessionData))); localStorage.setItem(`sessionData${scene.sessionSlotId ? scene.sessionSlotId : ''}`, encFunc(JSON.stringify(sessionData)));
console.debug('Session data saved'); console.debug('Session data saved');
@ -910,8 +892,12 @@ export class GameData {
}); });
} else { } else {
const data = localStorage.getItem(dataKey); const data = localStorage.getItem(dataKey);
if (data) if (data) {
handleData(atob(data)); const decFunc = bypassLogin
? (data: string) => atob(data)
: (data: string) => AES.decrypt(data, saveKey).toString(enc.Utf8);
handleData(decFunc(data));
}
resolve(!!data); resolve(!!data);
} }
}); });
@ -979,7 +965,7 @@ export class GameData {
return this.scene.ui.showText(`Your ${dataName} data could not be loaded. It may be corrupted.`, null, () => this.scene.ui.showText(null, 0), Utils.fixedInt(1500)); return this.scene.ui.showText(`Your ${dataName} data could not be loaded. It may be corrupted.`, null, () => this.scene.ui.showText(null, 0), Utils.fixedInt(1500));
this.scene.ui.showText(`Your ${dataName} data will be overridden and the page will reload. Proceed?`, null, () => { this.scene.ui.showText(`Your ${dataName} data will be overridden and the page will reload. Proceed?`, null, () => {
this.scene.ui.setOverlayMode(Mode.CONFIRM, () => { this.scene.ui.setOverlayMode(Mode.CONFIRM, () => {
if (!bypassLogin && dataType < GameDataType.SETTINGS) { if (!bypassLogin && dataType < GameDataType.SETTINGS && localStorage.getItem(dataKey)) {
updateUserInfo().then(success => { updateUserInfo().then(success => {
if (!success) if (!success)
return displayError(`Could not contact the server. Your ${dataName} data could not be imported.`); return displayError(`Could not contact the server. Your ${dataName} data could not be imported.`);
@ -990,11 +976,15 @@ export class GameData {
console.error(error); console.error(error);
return displayError(`An error occurred while updating ${dataName} data. Please contact the administrator.`); return displayError(`An error occurred while updating ${dataName} data. Please contact the administrator.`);
} }
localStorage.removeItem(dataKey);
window.location = window.location; window.location = window.location;
}); });
}); });
} else { } else {
localStorage.setItem(dataKey, btoa(dataStr)); const encFunc = bypassLogin || dataType === GameDataType.SETTINGS
? (data: string) => btoa(data)
: (data: string) => AES.encrypt(data, saveKey);
localStorage.setItem(dataKey, encFunc(dataStr));
window.location = window.location; window.location = window.location;
} }
}, () => { }, () => {