-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathsession.ts
212 lines (180 loc) · 5.49 KB
/
session.ts
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import Promise from 'bluebird';
import TransactionManager from './tx/transaction-manager';
import JanusError from './misc/error';
import Timer from './misc/timer';
import Transaction from './tx/transaction';
import Plugin from './plugin';
import Connection from './connection';
import JanusMessage from './misc/message';
import { isNaturalNumber } from './misc/utils';
import { MediaDevices } from '../plugin/base/shims/definitions';
import { WebRTC } from '../plugin/base/shims/definitions';
class Session extends TransactionManager {
private connection: Connection | null;
private plugins: { [key: string]: Plugin };
private keepAlivePeriod: number;
private keepAliveTimer?: Timer | null;
constructor(
connection: Connection,
private readonly id: string,
private readonly mediaDevices: MediaDevices,
private readonly webRTC: WebRTC
) {
super();
this.connection = connection;
this.plugins = {};
this.keepAlivePeriod = 30000;
if (this.connection.getOptions().keepalive) {
this.startKeepAlive();
}
connection.on('close', () => this._destroy());
}
getConnection(): Connection | null {
return this.connection;
}
getId(): string {
return this.id;
}
send(message: any): Promise<any> {
if (!this.connection) {
return Promise.reject(new Error(`Can not send message over destroyed ${this}.`));
}
message['session_id'] = this.id;
if (this.keepAliveTimer) {
this.keepAliveTimer.reset();
}
return this.connection.send(message);
}
attachPlugin(name: string): Promise<Plugin> {
return this.sendSync({ janus: 'attach', plugin: name }, this);
}
destroy(): Promise<any> {
return this.sendSync({ janus: 'destroy' }, this);
}
cleanup(): Promise<any> {
return this._destroy();
}
hasPlugin(pluginId: string): boolean {
return !!this.getPlugin(pluginId);
}
getPlugin(pluginId: string): Plugin {
return this.plugins[pluginId];
}
getPluginList(): Plugin[] {
return Object.keys(this.plugins).map(id => this.plugins[id]);
}
addPlugin(plugin: Plugin) {
this.plugins[plugin.getId()] = plugin;
plugin.once('detach', () => this.removePlugin(plugin.getId()));
}
removePlugin(pluginId: string) {
delete this.plugins[pluginId];
}
processOutcomeMessage(message: any): Promise<any> {
let janusMessage = message['janus'];
if ('attach' === janusMessage) {
return this.onAttach(message);
}
if ('destroy' === janusMessage) {
return this.onDestroy(message);
}
let pluginId = message['handle_id'];
if (pluginId) {
if (this.hasPlugin(pluginId)) {
return this.getPlugin(pluginId).processOutcomeMessage(message);
} else {
return Promise.reject(new Error(`Invalid plugin [${pluginId}].`));
}
}
return Promise.resolve(message);
}
processIncomeMessage(msg: JanusMessage): Promise<any> {
let pluginId = msg.get('handle_id') ?? msg.get('sender');
if (pluginId && this.hasPlugin(pluginId)) {
return this.getPlugin(pluginId).processIncomeMessage(msg);
}
return Promise.try(() => {
if (pluginId && !this.hasPlugin(pluginId)) {
throw new Error(`Invalid plugin [${pluginId}].`);
}
if ('timeout' === msg.get('janus')) {
return this.onTimeout(msg);
}
return this.defaultProcessIncomeMessage(msg);
})
.then(() => this.emit('message', msg))
.catch(error => this.emit('error', error));
}
toString() {
return `[Session] ${JSON.stringify({ id: this.id })}`;
}
private startKeepAlive() {
let keepAlive = this.connection?.getOptions().keepalive;
//@ts-ignore
if (keepAlive && isNaturalNumber(keepAlive) && keepAlive < 59000) {
this.keepAlivePeriod = keepAlive as number;
} else {
this.keepAlivePeriod = 30000;
}
this.keepAliveTimer = new Timer(() => {
this.send({ janus: 'keepalive' }).catch(error => {
if (this.connection?.isClosed()) {
this.stopKeepAlive();
}
throw error;
});
}, this.keepAlivePeriod);
this.keepAliveTimer.start();
}
private stopKeepAlive() {
if (this.keepAliveTimer) {
this.keepAliveTimer.stop();
this.keepAliveTimer = null;
}
}
private _destroy(): Promise<any> {
if (!this.connection) {
return Promise.resolve();
}
this.stopKeepAlive();
return Promise.map(this.getPluginList(), plugin => plugin.cleanup()).finally(() => {
this.plugins = {};
this.connection = null;
this.emit('destroy');
});
}
//@ts-ignore
private onTimeout(msg): Promise<any> {
return this._destroy().return(msg);
}
//@ts-ignore
private onDestroy(outMsg): Promise<any> {
this.addTransaction(
//@ts-ignore
new Transaction(outMsg['transaction'], msg => {
if ('success' === msg.get('janus')) {
return this._destroy().return(msg);
} else {
throw new JanusError(msg);
}
})
);
return Promise.resolve(outMsg);
}
private onAttach(outMsg: any): Promise<any> {
this.addTransaction(
//@ts-ignore
new Transaction(outMsg['transaction'], msg => {
if ('success' === msg.get('janus')) {
let pluginId = msg.get('data', 'id');
this.addPlugin(Plugin.create(this, outMsg['plugin'], pluginId, this.mediaDevices, this.webRTC));
return this.getPlugin(pluginId);
} else {
throw new JanusError(msg);
}
})
);
return Promise.resolve(outMsg);
}
}
export default Session;