diff --git a/src/Hydrogen.ts b/src/Hydrogen.ts index 697fcfe7f4e3398a4f67d165d601a4fc6a6e5548..d597955ba927ff6cc3680682a2e95985509a5578 100644 --- a/src/Hydrogen.ts +++ b/src/Hydrogen.ts @@ -60,6 +60,20 @@ export class Hydrogen { this._container.appendChild(view.mount()); } + /** + * Try to start Hydrogen based on an existing hydrogen session. + * If multiple sessions exist, this method chooses the most recent one. + */ + async attemptStartWithExistingSession(): Promise<boolean> { + const sessionIds = await this._platform.sessionInfoStorage.getAll(); + const { id } = sessionIds.pop(); + if (id) { + await this._client.startWithExistingSession(id); + return true; + } + return false; + } + private async _joinRoom(roomId: string): Promise<any> { await this._session.joinRoom(roomId); // even though we've joined the room, we need to wait till the next sync for the actual room diff --git a/src/main.ts b/src/main.ts index 08b8d87cab0592f9ca9e14ba84127be97f3d0323..35cc726034a5956588de7c5baf44a6c1b920bee5 100644 --- a/src/main.ts +++ b/src/main.ts @@ -20,14 +20,23 @@ async function main() { const root = document.querySelector("#chatterbox") as HTMLDivElement; const { homeserver, auto_join_room } = await fetchConfig(); const hydrogen = new Hydrogen(homeserver, root); - const username = generateRandomString(7); - const password = generateRandomString(10); - console.log(`Attempting to register with username = ${username} and password = ${password}`); - await hydrogen.register(username, password, "Chatterbox"); - console.log("Registration done"); - console.log("Attempting to login with same credentials"); - await hydrogen.login(username, password); - console.log("Login successful"); + console.log("Checking if session already exists"); + const sessionAlreadyExists = await hydrogen.attemptStartWithExistingSession(); + if (sessionAlreadyExists) { + console.log("Starting Hydrogen with existing session"); + } + else { + console.log("Session does not exist!"); + const username = generateRandomString(7); + const password = generateRandomString(10); + console.log(`Attempting to register with username = ${username} and password = ${password}`); + await hydrogen.register(username, password, "Chatterbox"); + console.log("Registration done"); + console.log("Attempting to login with same credentials"); + await hydrogen.login(username, password); + console.log("Login successful"); + } + console.log("Attempting to mount Timeline"); await hydrogen.showRoom(auto_join_room); console.log("Mounted Timeline");