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

275 lines
9.3 KiB
JavaScript
Raw Normal View History

2020-08-05 18:38:55 +02:00
/*
Copyright 2020 Bruno Windels <bruno@windels.cloud>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import {Room} from "./room/Room.js";
2019-02-26 20:49:45 +01:00
import { ObservableMap } from "../observable/index.js";
import { SendScheduler, RateLimitingBackoff } from "./SendScheduler.js";
import {User} from "./User.js";
import {Account as E2EEAccount} from "./e2ee/Account.js";
2020-08-31 14:13:21 +02:00
import {DeviceTracker} from "./e2ee/DeviceTracker.js";
const PICKLE_KEY = "DEFAULT_KEY";
2019-02-10 21:25:29 +01:00
export class Session {
// sessionInfo contains deviceId, userId and homeServer
2020-08-27 13:24:55 +02:00
constructor({storage, hsApi, sessionInfo, olm}) {
2019-05-12 20:26:46 +02:00
this._storage = storage;
this._hsApi = hsApi;
this._syncInfo = null;
this._sessionInfo = sessionInfo;
2019-05-12 20:26:46 +02:00
this._rooms = new ObservableMap();
this._sendScheduler = new SendScheduler({hsApi, backoff: new RateLimitingBackoff()});
2019-02-24 19:25:06 +01:00
this._roomUpdateCallback = (room, params) => this._rooms.update(room.id, params);
this._user = new User(sessionInfo.userId);
2020-08-27 13:24:55 +02:00
this._olm = olm;
this._e2eeAccount = null;
2020-08-31 14:13:21 +02:00
this._deviceTracker = olm ? new DeviceTracker({
storage,
getSyncToken: () => this.syncToken,
olm,
}) : null;
}
async beforeFirstSync(isNewLogin) {
if (this._olm) {
if (isNewLogin && this._e2eeAccount) {
throw new Error("there should not be an e2ee account already on a fresh login");
}
if (!this._e2eeAccount) {
const txn = await this._storage.readWriteTxn([
this._storage.storeNames.session
]);
try {
this._e2eeAccount = await E2EEAccount.create({
hsApi: this._hsApi,
olm: this._olm,
pickleKey: PICKLE_KEY,
userId: this._sessionInfo.userId,
deviceId: this._sessionInfo.deviceId,
txn
});
} catch (err) {
txn.abort();
throw err;
}
await txn.complete();
}
await this._e2eeAccount.generateOTKsIfNeeded(this._storage);
2020-08-27 19:13:24 +02:00
await this._e2eeAccount.uploadKeys(this._storage);
}
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.roomMembers,
2019-05-12 20:26:46 +02:00
this._storage.storeNames.timelineEvents,
2019-05-19 20:49:46 +02:00
this._storage.storeNames.timelineFragments,
this._storage.storeNames.pendingEvents,
2019-05-12 20:26:46 +02:00
]);
// restore session object
this._syncInfo = await txn.session.get("sync");
// restore e2ee account, if any
if (this._olm) {
this._e2eeAccount = await E2EEAccount.load({
hsApi: this._hsApi,
olm: this._olm,
pickleKey: PICKLE_KEY,
userId: this._sessionInfo.userId,
deviceId: this._sessionInfo.deviceId,
txn
});
}
const pendingEventsByRoomId = await this._getPendingEventsByRoom(txn);
2019-05-12 20:26:46 +02:00
// load rooms
const rooms = await txn.roomSummary.getAll();
await Promise.all(rooms.map(summary => {
const room = this.createRoom(summary.roomId, pendingEventsByRoomId.get(summary.roomId));
2019-05-12 20:26:46 +02:00
return room.load(summary, txn);
}));
}
2018-12-21 14:35:24 +01:00
get isStarted() {
return this._sendScheduler.isStarted;
}
2020-04-18 19:16:16 +02:00
stop() {
this._sendScheduler.stop();
}
async start(lastVersionResponse) {
if (lastVersionResponse) {
// store /versions response
const txn = await this._storage.readWriteTxn([
this._storage.storeNames.session
]);
txn.session.set("serverVersions", lastVersionResponse);
// TODO: what can we do if this throws?
await txn.complete();
}
this._sendScheduler.start();
for (const [, room] of this._rooms) {
2019-07-26 22:40:39 +02:00
room.resumeSending();
}
}
async _getPendingEventsByRoom(txn) {
const pendingEvents = await txn.pendingEvents.getAll();
return pendingEvents.reduce((groups, pe) => {
const group = groups.get(pe.roomId);
if (group) {
group.push(pe);
} else {
groups.set(pe.roomId, [pe]);
}
return groups;
}, new Map());
}
2019-02-20 23:48:16 +01:00
get rooms() {
return this._rooms;
}
createRoom(roomId, pendingEvents) {
2019-05-12 20:26:46 +02:00
const room = new Room({
roomId,
storage: this._storage,
emitCollectionChange: this._roomUpdateCallback,
hsApi: this._hsApi,
sendScheduler: this._sendScheduler,
pendingEvents,
user: this._user,
});
2019-05-12 20:26:46 +02:00
this._rooms.add(roomId, room);
return room;
}
2018-12-21 14:35:24 +01:00
2020-08-31 14:13:21 +02:00
async writeSync(syncResponse, syncFilterId, roomChanges, txn) {
2020-08-28 13:56:44 +02:00
const changes = {};
const syncToken = syncResponse.next_batch;
const deviceOneTimeKeysCount = syncResponse.device_one_time_keys_count;
if (this._e2eeAccount && deviceOneTimeKeysCount) {
changes.e2eeAccountChanges = this._e2eeAccount.writeSync(deviceOneTimeKeysCount, txn);
}
if (syncToken !== this.syncToken) {
const syncInfo = {token: syncToken, filterId: syncFilterId};
// don't modify `this` because transaction might still fail
txn.session.set("sync", syncInfo);
2020-08-28 13:56:44 +02:00
changes.syncInfo = syncInfo;
}
2020-08-31 14:13:21 +02:00
if (this._deviceTracker) {
const deviceLists = syncResponse.device_lists;
if (deviceLists) {
await this._deviceTracker.writeDeviceChanges(deviceLists, txn);
}
for (const {room, changes} of roomChanges) {
if (room.isTrackingMembers && changes.memberChanges?.size) {
await this._deviceTracker.writeMemberChanges(room, changes.memberChanges, txn);
}
}
}
2020-08-28 13:56:44 +02:00
return changes;
}
2020-08-28 13:56:44 +02:00
afterSync({syncInfo, e2eeAccountChanges}) {
if (syncInfo) {
// sync transaction succeeded, modify object state now
this._syncInfo = syncInfo;
2019-05-12 20:26:46 +02:00
}
2020-08-28 13:56:44 +02:00
if (this._e2eeAccount && e2eeAccountChanges) {
this._e2eeAccount.afterSync(e2eeAccountChanges);
}
2019-05-12 20:26:46 +02:00
}
2019-02-07 01:20:27 +01:00
async afterSyncCompleted() {
const needsToUploadOTKs = await this._e2eeAccount.generateOTKsIfNeeded(this._storage);
if (needsToUploadOTKs) {
// TODO: we could do this in parallel with sync if it proves to be too slow
// but I'm not sure how to not swallow errors in that case
await this._e2eeAccount.uploadKeys(this._storage);
}
}
2019-05-12 20:26:46 +02:00
get syncToken() {
return this._syncInfo?.token;
2019-05-12 20:26:46 +02:00
}
2019-06-16 10:53:23 +02:00
2019-10-12 20:24:09 +02:00
get syncFilterId() {
return this._syncInfo?.filterId;
2019-10-12 20:24:09 +02:00
}
get user() {
return this._user;
2019-06-16 10:53:23 +02:00
}
2019-02-20 23:48:16 +01:00
}
export function tests() {
2020-03-14 21:38:37 +01:00
function createStorageMock(session, pendingEvents = []) {
return {
readTxn() {
return Promise.resolve({
session: {
get(key) {
return Promise.resolve(session[key]);
}
},
pendingEvents: {
getAll() {
return Promise.resolve(pendingEvents);
}
2020-03-14 21:38:37 +01:00
},
roomSummary: {
getAll() {
return Promise.resolve([]);
}
}
});
2020-03-14 21:38:37 +01:00
},
storeNames: {}
};
}
return {
"session data is not modified until after sync": async (assert) => {
const session = new Session({storage: createStorageMock({
sync: {token: "a", filterId: 5}
2020-03-14 21:38:37 +01:00
}), sessionInfo: {userId: ""}});
await session.load();
let syncSet = false;
const syncTxn = {
session: {
set(key, value) {
if (key === "sync") {
assert.equal(value.token, "b");
assert.equal(value.filterId, 6);
syncSet = true;
}
}
}
};
const newSessionData = session.writeSync("b", 6, {}, syncTxn);
assert(syncSet);
2020-03-14 21:38:37 +01:00
assert.equal(session.syncToken, "a");
assert.equal(session.syncFilterId, 5);
session.afterSync(newSessionData);
2020-03-14 21:38:37 +01:00
assert.equal(session.syncToken, "b");
assert.equal(session.syncFilterId, 6);
}
}
}