96 lines
2.4 KiB
TypeScript
96 lines
2.4 KiB
TypeScript
import EventEmitter from "eventemitter3";
|
|
import Peer, { PeerConnectOption, PeerJSOption } from "peerjs";
|
|
import MockDataConnection from "./MockDataConnection";
|
|
|
|
export class MockPeer extends EventEmitter {
|
|
public connections: Record<string, MockDataConnection[]>;
|
|
public id: string;
|
|
public options: PeerJSOption;
|
|
public disconnected: boolean;
|
|
public destroyed: boolean;
|
|
public prototype: unknown;
|
|
private mocks: Record<string, MockPeer>;
|
|
|
|
public constructor(
|
|
mockSource: Record<string, MockPeer>,
|
|
id: string,
|
|
options?: PeerJSOption
|
|
) {
|
|
super();
|
|
this.id = id;
|
|
this.options = options ? options : {};
|
|
this.connections = {};
|
|
this.disconnected = false;
|
|
this.destroyed = false;
|
|
this.mocks = mockSource;
|
|
this.mocks[id] = this;
|
|
}
|
|
|
|
public connect(id: string, options?: PeerConnectOption): MockDataConnection {
|
|
let connection = new MockDataConnection(id, this, options);
|
|
// hacky way to avoid race conditions
|
|
setTimeout(() => connection._configureDataChannel(this.mocks, options), 1);
|
|
this._addConnection(id, connection);
|
|
return connection;
|
|
}
|
|
|
|
public disconnect() {
|
|
this.disconnected = true;
|
|
this.emit("disconnected", this.id);
|
|
this.id = "";
|
|
}
|
|
|
|
public destroy() {
|
|
this.destroyed = true;
|
|
this.emit("destroyed", this.id);
|
|
this.disconnect();
|
|
}
|
|
|
|
private _addConnection(peer: string, connection: MockDataConnection) {
|
|
if (!this.connections[peer]) {
|
|
this.connections[peer] = [];
|
|
}
|
|
this.connections[peer].push(connection);
|
|
}
|
|
|
|
public _negotiate(
|
|
peer: string,
|
|
remoteConnection: MockDataConnection,
|
|
options?: PeerConnectOption
|
|
) {
|
|
let localConnection = new MockDataConnection(peer, this, options);
|
|
localConnection._setRemote(remoteConnection);
|
|
this._addConnection(peer, localConnection);
|
|
this.emit("connection", localConnection);
|
|
return localConnection;
|
|
}
|
|
|
|
public call(
|
|
id: string,
|
|
stream: MediaStream,
|
|
options?: Peer.CallOption
|
|
): Peer.MediaConnection {
|
|
throw new Error("unimplemented");
|
|
}
|
|
|
|
public reconnect() {}
|
|
|
|
public getConnection(
|
|
peerId: string,
|
|
connectionId: string
|
|
): MockDataConnection | null {
|
|
if (peerId in this.mocks) {
|
|
let map = this.mocks[peerId].connections;
|
|
if (connectionId in map) {
|
|
return map[connectionId][0];
|
|
}
|
|
return null;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public listAllPeers() {}
|
|
}
|
|
|
|
export default MockPeer;
|