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

67 lines
1.9 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 {
// sessionInfo contains deviceId, userId and homeServer
2019-05-12 20:26:46 +02:00
constructor({storage, hsApi, sessionInfo}) {
this._storage = storage;
this._hsApi = hsApi;
2019-05-12 20:26:46 +02:00
this._session = null;
this._sessionInfo = sessionInfo;
2019-05-12 20:26:46 +02:00
this._rooms = new ObservableMap();
2019-02-24 19:25:06 +01:00
this._roomUpdateCallback = (room, params) => this._rooms.update(room.id, params);
2019-05-12 20:26:46 +02:00
}
2018-12-21 14:35:24 +01:00
2019-05-12 20:26:46 +02:00
async load() {
const txn = await this._storage.readTxn([
this._storage.storeNames.session,
this._storage.storeNames.roomSummary,
this._storage.storeNames.roomState,
this._storage.storeNames.timelineEvents,
2019-05-19 20:49:46 +02:00
this._storage.storeNames.timelineFragments,
2019-05-12 20:26:46 +02:00
]);
// restore session object
this._session = await txn.session.get();
if (!this._session) {
this._session = {};
2019-05-12 20:26:46 +02:00
return;
}
// load rooms
const rooms = await txn.roomSummary.getAll();
await Promise.all(rooms.map(summary => {
const room = this.createRoom(summary.roomId);
return room.load(summary, txn);
}));
}
2018-12-21 14:35:24 +01:00
2019-02-20 23:48:16 +01:00
get rooms() {
return this._rooms;
}
2019-05-12 20:26:46 +02:00
createRoom(roomId) {
const room = new Room({
roomId,
storage: this._storage,
emitCollectionChange: this._roomUpdateCallback,
hsApi: this._hsApi,
});
2019-05-12 20:26:46 +02:00
this._rooms.add(roomId, room);
return room;
}
2018-12-21 14:35:24 +01:00
2019-05-12 20:26:46 +02:00
persistSync(syncToken, accountData, txn) {
if (syncToken !== this._session.syncToken) {
this._session.syncToken = syncToken;
txn.session.set(this._session);
}
}
2019-02-07 01:20:27 +01:00
2019-05-12 20:26:46 +02:00
get syncToken() {
return this._session.syncToken;
}
2019-06-16 10:53:23 +02:00
get userId() {
return this._sessionInfo.userId;
}
2019-02-20 23:48:16 +01:00
}