vector-im-hydrogen-web/src/matrix/session.js

66 lines
1.7 KiB
JavaScript
Raw Normal View History

2019-02-10 21:25:29 +01:00
import Room from "./room/room.js";
2019-02-26 20:49:45 +01:00
import { ObservableMap } from "../observable/index.js";
2019-02-10 21:25:29 +01:00
export default class Session {
2019-02-07 01:20:27 +01:00
constructor(storage) {
this._storage = storage;
2019-02-07 01:20:27 +01:00
this._session = null;
2019-02-20 23:48:16 +01:00
this._rooms = new ObservableMap();
2019-02-24 19:25:06 +01:00
this._roomUpdateCallback = (room, params) => this._rooms.update(room.id, params);
2019-02-07 01:20:27 +01:00
}
// should be called before load
2019-02-07 02:03:47 +01:00
// loginData has device_id, user_id, home_server, access_token
2019-02-07 01:20:27 +01:00
async setLoginData(loginData) {
2019-02-10 21:25:29 +01:00
console.log("session.setLoginData");
const txn = await this._storage.readWriteTxn([this._storage.storeNames.session]);
2019-02-07 01:20:27 +01:00
const session = {loginData};
txn.session.set(session);
await txn.complete();
2018-12-21 14:35:24 +01:00
}
2019-02-07 01:20:27 +01:00
async load() {
const txn = await this._storage.readTxn([
2019-02-07 01:51:48 +01:00
this._storage.storeNames.session,
this._storage.storeNames.roomSummary,
2019-02-10 21:25:29 +01:00
this._storage.storeNames.roomState,
this._storage.storeNames.roomTimeline,
2019-02-07 01:51:48 +01:00
]);
// restore session object
2019-02-07 01:20:27 +01:00
this._session = await txn.session.get();
if (!this._session) {
throw new Error("session store is empty");
}
// load rooms
2019-02-07 01:51:48 +01:00
const rooms = await txn.roomSummary.getAll();
2019-02-10 21:25:29 +01:00
await Promise.all(rooms.map(summary => {
const room = this.createRoom(summary.roomId);
return room.load(summary, txn);
2019-02-07 01:51:48 +01:00
}));
2018-12-21 14:35:24 +01:00
}
2019-02-20 23:48:16 +01:00
get rooms() {
return this._rooms;
}
createRoom(roomId) {
2019-02-24 19:25:06 +01:00
const room = new Room(roomId, this._storage, this._roomUpdateCallback);
2019-02-20 23:48:16 +01:00
this._rooms.add(roomId, room);
return room;
}
2018-12-21 14:35:24 +01:00
applySync(syncToken, accountData, txn) {
2019-02-16 02:59:10 +01:00
if (syncToken !== this._session.syncToken) {
this._session.syncToken = syncToken;
txn.session.set(this._session);
}
2019-02-07 01:20:27 +01:00
}
get syncToken() {
return this._session.syncToken;
}
get accessToken() {
return this._session.loginData.access_token;
2018-12-21 14:35:24 +01:00
}
2019-02-20 23:48:16 +01:00
}