All files / app/store video.ts

30.3% Statements 10/33
0% Branches 0/8
10% Functions 1/10
35.71% Lines 10/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60158x   158x   279x 279x 279x 279x 279x 279x     279x           279x                                                                                  
import { makeAutoObservable, observable } from 'mobx';
 
export class VideoStore {
 
  enabled = false;
  stream?: MediaStream = {} as any;
  activeSpeaker = '';
  peers = new Map<string, RTCPeerConnection>();
  streams = new Map<string, { playing?: boolean, stream: MediaStream }[]>();
  hungup = new Map<string, boolean>();
 
  constructor() {
    makeAutoObservable(this, {
      stream: observable.ref,
      peers: observable.shallow,
      streams: observable.shallow,
      hungup: observable.shallow,
    });
    this.stream = undefined;
  }
 
  call(user: string, peer: RTCPeerConnection) {
    this.peers.set(user, peer);
    this.streams.set(user, []);
  }
 
  addStream(user: string, stream: MediaStream) {
    if (!this.streams.get(user)?.length) {
      this.streams.set(user, [{ stream }]);
    } else {
      console.warn('adding second stream');
      this.streams.set(user, [{ stream }, ...this.streams.get(user)!.filter(s => s.stream.id !== stream.id)]);
    }
  }
 
  playing(user: string, id: string) {
    this.streams.get(user)!.find(s => s.stream.id === id)!.playing = true;
  }
 
  reset(user: string) {
    this.remove(user);
    this.streams.set(user, []);
  }
 
  remove(user: string) {
    const peer = this.peers.get(user);
    if (peer) peer.close();
    this.peers.delete(user);
    this.streams.delete(user);
  }
 
  hangup() {
    for (const peer of this.peers.values()) peer.close();
    this.peers.clear();
    this.streams.clear();
    this.hungup.clear();
    this.stream?.getTracks().forEach(t => t.stop());
  }
}