port LoginViewModel over to SessionContainer

This commit is contained in:
Bruno Windels 2020-04-20 22:29:34 +02:00
parent bb7fca0592
commit a5965ad378

View file

@ -1,11 +1,15 @@
import {EventEmitter} from "../utils/EventEmitter.js";
import {LoadStatus} from "../matrix/SessionContainer.js";
import {AbortError} from "../utils/error.js";
export class LoginViewModel extends EventEmitter {
constructor({loginCallback, defaultHomeServer, createHsApi}) {
constructor({sessionCallback, defaultHomeServer, createSessionContainer}) {
super();
this._loginCallback = loginCallback;
this._createSessionContainer = createSessionContainer;
this._sessionCallback = sessionCallback;
this._defaultHomeServer = defaultHomeServer;
this._createHsApi = createHsApi;
this._sessionContainer = null;
this._loadWaitHandle = null;
this._loading = false;
this._error = null;
}
@ -18,13 +22,25 @@ export class LoginViewModel extends EventEmitter {
get loading() { return this._loading; }
async login(username, password, homeserver) {
const hsApi = this._createHsApi(homeserver);
try {
this._loading = true;
this.emit("change", "loading");
const loginData = await hsApi.passwordLogin(username, password).response();
loginData.homeServerUrl = homeserver;
this._loginCallback(loginData);
this._sessionContainer = this._createSessionContainer();
this._sessionContainer.startWithLogin(homeserver, username, password);
this._loadWaitHandle = this._sessionContainer.loadStatus.waitFor(s => {
this.emit("change", "loadStatus");
return s === LoadStatus.Ready;
});
try {
await this._loadWaitHandle.promise;
} catch (err) {
if (err instanceof AbortError) {
// login was cancelled
return;
}
}
this._loadWaitHandle = null;
this._sessionCallback(this._sessionContainer);
// wait for parent view model to switch away here
} catch (err) {
this._error = err;
@ -33,7 +49,39 @@ export class LoginViewModel extends EventEmitter {
}
}
get loadStatus() {
return this._sessionContainer && this._sessionContainer.loadStatus;
}
get loadError() {
if (this._sessionContainer) {
const error = this._sessionContainer.loadError;
if (error) {
return error.message;
}
}
return null;
}
async cancelLogin() {
if (!this._loading) {
return;
}
this._loading = false;
this.emit("change", "loading");
if (this._sessionContainer) {
this._sessionContainer.stop();
await this._sessionContainer.deleteSession();
this._sessionContainer = null;
}
if (this._loadWaitHandle) {
// rejects with AbortError
this._loadWaitHandle.dispose();
this._loadWaitHandle = null;
}
}
cancel() {
this._loginCallback();
this._sessionCallback();
}
}