This repository has been archived on 2022-08-19. You can view files and clone it, but cannot push or open issues or pull requests.
hydrogen-web/src/matrix/calls/CallHandler.ts

229 lines
9.5 KiB
TypeScript
Raw Normal View History

2022-02-14 21:44:21 +05:30
/*
Copyright 2022 The Matrix.org Foundation C.I.C.
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 {ObservableMap} from "../../observable/map/ObservableMap";
2022-03-10 19:23:31 +05:30
import {WebRTC, PeerConnection, PeerConnectionHandler} from "../../platform/types/WebRTC";
2022-04-13 22:04:01 +05:30
import {MediaDevices, Track, AudioTrack} from "../../platform/types/MediaDevices";
2022-03-10 19:23:31 +05:30
import {handlesEventType} from "./PeerCall";
import {EventType, CallIntent} from "./callEventTypes";
2022-03-10 19:23:31 +05:30
import {GroupCall} from "./group/GroupCall";
import {makeId} from "../common";
2022-02-14 21:44:21 +05:30
import type {LocalMedia} from "./LocalMedia";
2022-02-14 21:44:21 +05:30
import type {Room} from "../room/Room";
2022-03-09 23:23:51 +05:30
import type {MemberChange} from "../room/members/RoomMember";
2022-02-14 21:44:21 +05:30
import type {StateEvent} from "../storage/types";
2022-03-25 19:13:02 +05:30
import type {ILogItem, ILogger} from "../../logging/types";
2022-03-09 23:23:51 +05:30
import type {Platform} from "../../platform/web/Platform";
2022-03-10 19:23:31 +05:30
import type {BaseObservableMap} from "../../observable/map/BaseObservableMap";
2022-03-09 23:23:51 +05:30
import type {SignallingMessage, MGroupCallBase} from "./callEventTypes";
2022-03-10 19:23:31 +05:30
import type {Options as GroupCallOptions} from "./group/GroupCall";
import type {Transaction} from "../storage/idb/Transaction";
import type {CallEntry} from "../storage/idb/stores/CallStore";
import type {Clock} from "../../platform/web/dom/Clock";
2022-02-16 21:31:02 +05:30
export type Options = Omit<GroupCallOptions, "emitUpdate" | "createTimeout"> & {
logger: ILogger,
clock: Clock
2022-03-25 19:13:02 +05:30
};
2022-03-09 23:23:51 +05:30
2022-03-17 16:01:12 +05:30
export class CallHandler {
2022-02-15 21:35:20 +05:30
// group calls by call id
2022-03-10 19:23:31 +05:30
private readonly _calls: ObservableMap<string, GroupCall> = new ObservableMap<string, GroupCall>();
2022-03-09 23:23:51 +05:30
// map of userId to set of conf_id's they are in
private memberToCallIds: Map<string, Set<string>> = new Map();
2022-03-10 19:23:31 +05:30
private groupCallOptions: GroupCallOptions;
private sessionId = makeId("s");
2022-02-14 21:44:21 +05:30
2022-03-10 19:23:31 +05:30
constructor(private readonly options: Options) {
this.groupCallOptions = Object.assign({}, this.options, {
emitUpdate: (groupCall, params) => this._calls.update(groupCall.id, params),
createTimeout: this.options.clock.createTimeout,
sessionId: this.sessionId
});
}
async loadCalls(intent: CallIntent = CallIntent.Ring) {
const txn = await this._getLoadTxn();
const callEntries = await txn.calls.getByIntent(intent);
this._loadCallEntries(callEntries, txn);
}
async loadCallsForRoom(intent: CallIntent, roomId: string) {
const txn = await this._getLoadTxn();
const callEntries = await txn.calls.getByIntentAndRoom(intent, roomId);
this._loadCallEntries(callEntries, txn);
}
private async _getLoadTxn(): Promise<Transaction> {
const names = this.options.storage.storeNames;
const txn = await this.options.storage.readTxn([
names.calls,
names.roomState
]);
return txn;
}
private async _loadCallEntries(callEntries: CallEntry[], txn: Transaction): Promise<void> {
return this.options.logger.run("loading calls", async log => {
log.set("entries", callEntries.length);
await Promise.all(callEntries.map(async callEntry => {
if (this._calls.get(callEntry.callId)) {
return;
}
const event = await txn.roomState.get(callEntry.roomId, EventType.GroupCall, callEntry.callId);
if (event) {
const logItem = this.options.logger.child({l: "call", loaded: true});
const call = new GroupCall(event.event.state_key, false, event.event.content, event.roomId, this.groupCallOptions, logItem);
this._calls.set(call.id, call);
}
}));
const roomIds = Array.from(new Set(callEntries.map(e => e.roomId)));
await Promise.all(roomIds.map(async roomId => {
// const ownCallsMemberEvent = await txn.roomState.get(roomId, EventType.GroupCallMember, this.options.ownUserId);
// if (ownCallsMemberEvent) {
// this.handleCallMemberEvent(ownCallsMemberEvent.event, log);
// }
const callsMemberEvents = await txn.roomState.getAllForType(roomId, EventType.GroupCallMember);
for (const entry of callsMemberEvents) {
this.handleCallMemberEvent(entry.event, log);
}
// TODO: we should be loading the other members as well at some point
}));
log.set("newSize", this._calls.size);
2022-03-10 19:23:31 +05:30
});
2022-02-14 21:44:21 +05:30
}
2022-04-14 01:38:47 +05:30
async createCall(roomId: string, localMedia: LocalMedia, name: string, intent: CallIntent = CallIntent.Ring): Promise<GroupCall> {
2022-03-25 19:13:02 +05:30
const logItem = this.options.logger.child({l: "call", incoming: false});
const call = new GroupCall(makeId("conf-"), true, {
"m.name": name,
2022-04-14 01:38:47 +05:30
"m.intent": intent
}, roomId, this.groupCallOptions, logItem);
this._calls.set(call.id, call);
try {
await call.create(localMedia);
// store call info so it will ring again when reopening the app
const txn = await this.options.storage.readWriteTxn([this.options.storage.storeNames.calls]);
txn.calls.add({
intent: call.intent,
callId: call.id,
timestamp: this.options.clock.now(),
roomId: roomId
});
await txn.complete();
} catch (err) {
//if (err.name === "ConnectionError") {
// if we're offline, give up and remove the call again
2022-03-25 19:13:02 +05:30
call.dispose();
this._calls.remove(call.id);
//}
throw err;
}
return call;
}
2022-03-10 19:23:31 +05:30
get calls(): BaseObservableMap<string, GroupCall> { return this._calls; }
2022-02-25 21:24:00 +05:30
// TODO: check and poll turn server credentials here
2022-03-10 19:23:31 +05:30
/** @internal */
handleRoomState(room: Room, events: StateEvent[], txn: Transaction, log: ILogItem) {
2022-02-14 21:44:21 +05:30
// first update call events
for (const event of events) {
2022-03-09 23:23:51 +05:30
if (event.type === EventType.GroupCall) {
this.handleCallEvent(event, room.id, txn, log);
2022-02-14 21:44:21 +05:30
}
}
2022-03-10 19:23:31 +05:30
// then update members
2022-02-14 21:44:21 +05:30
for (const event of events) {
2022-03-09 23:23:51 +05:30
if (event.type === EventType.GroupCallMember) {
2022-03-25 19:13:02 +05:30
this.handleCallMemberEvent(event, log);
2022-03-09 23:23:51 +05:30
}
}
}
2022-03-10 19:23:31 +05:30
/** @internal */
2022-03-09 23:23:51 +05:30
updateRoomMembers(room: Room, memberChanges: Map<string, MemberChange>) {
// TODO: also have map for roomId to calls, so we can easily update members
// we will also need this to get the call for a room
2022-03-09 23:23:51 +05:30
}
2022-03-10 19:23:31 +05:30
/** @internal */
handlesDeviceMessageEventType(eventType: string): boolean {
return handlesEventType(eventType);
}
/** @internal */
handleDeviceMessage(message: SignallingMessage<MGroupCallBase>, userId: string, deviceId: string, log: ILogItem) {
// TODO: buffer messages for calls we haven't received the state event for yet?
const call = this._calls.get(message.content.conf_id);
call?.handleDeviceMessage(message, userId, deviceId, log);
}
private handleCallEvent(event: StateEvent, roomId: string, txn: Transaction, log: ILogItem) {
2022-03-09 23:23:51 +05:30
const callId = event.state_key;
2022-03-10 19:23:31 +05:30
let call = this._calls.get(callId);
2022-03-09 23:23:51 +05:30
if (call) {
2022-03-25 19:13:02 +05:30
call.updateCallEvent(event.content, log);
2022-03-09 23:23:51 +05:30
if (call.isTerminated) {
2022-03-25 19:13:02 +05:30
call.dispose();
2022-03-10 19:23:31 +05:30
this._calls.remove(call.id);
txn.calls.remove(call.intent, roomId, call.id);
2022-03-09 23:23:51 +05:30
}
} else {
2022-03-25 19:13:02 +05:30
const logItem = this.options.logger.child({l: "call", incoming: true});
call = new GroupCall(event.state_key, false, event.content, roomId, this.groupCallOptions, logItem);
2022-03-10 19:23:31 +05:30
this._calls.set(call.id, call);
txn.calls.add({
intent: call.intent,
callId: call.id,
timestamp: event.origin_server_ts,
roomId: roomId
});
2022-03-09 23:23:51 +05:30
}
}
2022-03-25 19:13:02 +05:30
private handleCallMemberEvent(event: StateEvent, log: ILogItem) {
2022-03-10 19:23:31 +05:30
const userId = event.state_key;
2022-03-09 23:23:51 +05:30
const calls = event.content["m.calls"] ?? [];
2022-03-24 18:22:19 +05:30
for (const call of calls) {
2022-03-09 23:23:51 +05:30
const callId = call["m.call_id"];
2022-03-10 19:23:31 +05:30
const groupCall = this._calls.get(callId);
// TODO: also check the member when receiving the m.call event
2022-03-30 18:48:46 +05:30
groupCall?.updateMembership(userId, call, log);
2022-03-24 18:22:19 +05:30
};
const newCallIdsMemberOf = new Set<string>(calls.map(call => call["m.call_id"]));
2022-03-10 19:23:31 +05:30
let previousCallIdsMemberOf = this.memberToCallIds.get(userId);
// remove user as member of any calls not present anymore
2022-03-09 23:23:51 +05:30
if (previousCallIdsMemberOf) {
for (const previousCallId of previousCallIdsMemberOf) {
if (!newCallIdsMemberOf.has(previousCallId)) {
2022-03-10 19:23:31 +05:30
const groupCall = this._calls.get(previousCallId);
2022-03-30 18:48:46 +05:30
groupCall?.removeMembership(userId, log);
2022-02-14 21:44:21 +05:30
}
}
}
2022-03-09 23:23:51 +05:30
if (newCallIdsMemberOf.size === 0) {
2022-03-10 19:23:31 +05:30
this.memberToCallIds.delete(userId);
2022-03-09 23:23:51 +05:30
} else {
2022-03-10 19:23:31 +05:30
this.memberToCallIds.set(userId, newCallIdsMemberOf);
2022-03-09 23:23:51 +05:30
}
2022-02-14 21:44:21 +05:30
}
}