2023-12-30 18:41:25 -05:00
import { bypassLogin } from "./battle-scene" ;
import * as Utils from "./utils" ;
2023-12-31 18:30:37 -05:00
export interface UserInfo {
username : string ;
2024-03-14 21:49:49 -04:00
lastSessionSlot : integer ;
2023-12-31 18:30:37 -05:00
}
export let loggedInUser : UserInfo = null ;
2024-06-17 02:44:07 +01:00
// This is a random string that is used to identify the client session - unique per session (tab or window) so that the game will only save on the one that the server is expecting
2024-05-15 00:52:06 -04:00
export const clientSessionId = Utils . randomString ( 32 ) ;
2023-12-30 18:41:25 -05:00
2024-06-13 14:42:25 +02:00
export function initLoggedInUser ( ) : void {
loggedInUser = { username : "Guest" , lastSessionSlot : - 1 } ;
}
2024-04-10 01:32:49 -04:00
export function updateUserInfo ( ) : Promise < [ boolean , integer ] > {
return new Promise < [ boolean , integer ] > ( resolve = > {
2023-12-30 18:41:25 -05:00
if ( bypassLogin ) {
2024-05-23 17:03:10 +02:00
loggedInUser = { username : "Guest" , lastSessionSlot : - 1 } ;
2024-03-14 21:49:49 -04:00
let lastSessionSlot = - 1 ;
2024-05-15 10:55:17 -04:00
for ( let s = 0 ; s < 5 ; s ++ ) {
2024-05-23 17:03:10 +02:00
if ( localStorage . getItem ( ` sessionData ${ s ? s : "" } _ ${ loggedInUser . username } ` ) ) {
2024-03-14 21:49:49 -04:00
lastSessionSlot = s ;
break ;
}
}
2024-05-15 01:42:36 -04:00
loggedInUser . lastSessionSlot = lastSessionSlot ;
2024-05-15 10:55:17 -04:00
// Migrate old data from before the username was appended
2024-05-23 17:03:10 +02:00
[ "data" , "sessionData" , "sessionData1" , "sessionData2" , "sessionData3" , "sessionData4" ] . map ( d = > {
2024-05-15 10:55:17 -04:00
if ( localStorage . hasOwnProperty ( d ) ) {
2024-05-23 17:03:10 +02:00
if ( localStorage . hasOwnProperty ( ` ${ d } _ ${ loggedInUser . username } ` ) ) {
2024-05-15 10:55:17 -04:00
localStorage . setItem ( ` ${ d } _ ${ loggedInUser . username } _bak ` , localStorage . getItem ( ` ${ d } _ ${ loggedInUser . username } ` ) ) ;
2024-05-23 17:03:10 +02:00
}
2024-05-15 10:55:17 -04:00
localStorage . setItem ( ` ${ d } _ ${ loggedInUser . username } ` , localStorage . getItem ( d ) ) ;
localStorage . removeItem ( d ) ;
}
} ) ;
2024-04-10 01:32:49 -04:00
return resolve ( [ true , 200 ] ) ;
2023-12-30 18:41:25 -05:00
}
2024-05-23 17:03:10 +02:00
Utils . apiFetch ( "account/info" , true ) . then ( response = > {
2023-12-30 18:41:25 -05:00
if ( ! response . ok ) {
2024-04-10 01:32:49 -04:00
resolve ( [ false , response . status ] ) ;
2023-12-30 18:41:25 -05:00
return ;
}
return response . json ( ) ;
} ) . then ( jsonResponse = > {
loggedInUser = jsonResponse ;
2024-04-10 01:32:49 -04:00
resolve ( [ true , 200 ] ) ;
} ) . catch ( err = > {
console . error ( err ) ;
resolve ( [ false , 500 ] ) ;
2023-12-30 18:41:25 -05:00
} ) ;
} ) ;
2024-05-23 17:03:10 +02:00
}