Welcome to mirror list, hosted at ThFree Co, Russian Federation.

CallManager.ts « src - github.com/jsxc/jsxc.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0ccf7cdf0cc5937bdfd4dc5aff40d0aa004e5c02 (plain)
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import JingleHandler from '@connection/JingleHandler';
import Log from '@util/Log';
import Account from './Account';
import { Call } from './Call';
import { IContact } from './Contact.interface';
import { JINGLE_FEATURES } from './JingleAbstractSession';
import { JingleCallFactory } from './JingleCallFactory';
import JingleCallSession from './JingleCallSession';

export enum CallState {
   Pending,
   Accepted,
   Declined,
   Aborted,
   Ignored,
   Failed,
}
export type CallType = 'audio' | 'video' | 'stream';

function cancelAllOtherSessions(sessions: JingleCallSession[], exception: JingleCallSession) {
   sessions.forEach((session, index) => {
      if (index !== sessions.indexOf(exception)) {
         session.cancel();
      }
   });
}

export default class CallManager {
   private incomingCalls: { [sessionId: string]: Call } = {};

   constructor(private account: Account) {}

   public onIncomingCall(type: CallType, sessionId: string, peer: IContact) {
      //@TODO decline calls if there is an active call

      if (!this.incomingCalls[sessionId]) {
         this.incomingCalls[sessionId] = new Call(type, sessionId, peer);

         const storage = this.account.getSessionStorage();
         const key = storage.generateKey('call', sessionId);

         storage.registerHook(key, (newValue: CallState) => {
            if (
               newValue !== CallState.Pending &&
               this.incomingCalls[sessionId].getCurrentState() === CallState.Pending
            ) {
               this.incomingCalls[sessionId].abort();
            }
         });
      } else if (this.incomingCalls[sessionId].getPeer().getUid() !== peer.getUid()) {
         throw new Error('Duplicated call session id');
      }

      return this.incomingCalls[sessionId];
   }

   public async call(
      contact: IContact,
      type: 'video' | 'audio' | 'screen',
      stream: MediaStream
   ): Promise<JingleCallSession | CallState | false> {
      let resources = await contact.getCapableResources(JINGLE_FEATURES[type]);

      if (resources.length === 0) {
         return false;
      }

      let sessionId: string;
      const jingleHandler = this.account.getConnection().getJingleHandler();
      const initiateCall = JingleCallFactory(jingleHandler, stream, type, contact);

      [, , resources, sessionId] = await this.account
         .getPipe<[IContact, 'video' | 'audio' | 'screen', string[], string]>('call')
         .run(contact, type, resources, undefined);

      if (resources.length === 0) {
         if (sessionId) {
            return CallState.Declined;
         } else {
            // call timed out
            return CallState.Aborted;
         }
      }

      const sessions: JingleCallSession[] = [];

      for (let resource of resources) {
         try {
            sessions.push(await initiateCall(resource, sessionId));
         } catch (err) {
            Log.warn(`Error while calling ${resource}`, err);
         }
      }

      if (sessions.length === 0) {
         Log.warn('Could not establish a single session');

         return false;
      }

      const respondPromises: Promise<CallState | JingleCallSession>[] = [];

      for (let session of sessions) {
         respondPromises.push(
            new Promise(resolve => {
               session.on('accepted', () => {
                  cancelAllOtherSessions(sessions, session);

                  resolve(session);
               });

               session.on('terminated', ({ condition }) => {
                  if (condition === 'decline') {
                     cancelAllOtherSessions(sessions, session);

                     resolve(CallState.Declined);
                  }
               });
            })
         );
      }

      return Promise.race(respondPromises);
   }

   public terminateAll() {
      JingleHandler.terminateAll('success');

      this.account.getPipe<[sessionId?: string]>('terminateCall').run();
   }
}