-
Notifications
You must be signed in to change notification settings - Fork 0
/
sipphone.ts
497 lines (445 loc) · 15.9 KB
/
sipphone.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
/*
* @Description: main sipphone class
* @Author: lushevol
* @Date: 2019-08-27 17:53:38
* @LastEditors: lushevol
* @LastEditTime: 2019-09-17 22:21:22
*/
import SIP, { Transport } from 'sip.js'
import { ISipAddress, ISipAccount, ISessionParams, ICallbackObj, IErrorMsg, OutgoingSession, IncomingSession, IMediaDom, IModifiers } from './sipphone.declar'
import { EventEmitter } from "./EventEmitter";
class sipphone {
public sipServers: ISipAddress[] = [];
public sipAccount: ISipAccount = {
name: 'unkown user',
no: '',
pwd: ''
};
public SipUA: any;
public currentSession: IncomingSession| OutgoingSession | null = null;
private currentSessionParams: ISessionParams = {
audio: true,
video: true
};
private videoTrack: MediaStreamTrack[] = [];
public callback: ICallbackObj = {};
public mediaDom!: IMediaDom;
public modifiersParams: IModifiers = { ptime: '20', capturerate: '24000', bitrate: '30000' };
public EventEmitter = new EventEmitter()
public on = this.EventEmitter.on
public emit = this.EventEmitter.emit
constructor(account: ISipAccount, server: ISipAddress[]) {
this.sipAccount = account
this.sipServers = server
this.registerDefaultEvents()
}
// initial sip instance
public init(md: IMediaDom) {
const config = this.sipConfig
this.SipUA = new SIP.UA(config)
this.bindSipUAEvents()
this.initialMediaDom(md)
return this.SipUA
}
public initialMediaDom(md: IMediaDom) {
if(md.remoteAudio) {
this.mediaDom.remoteAudio = md.remoteAudio
}
if(md.remoteVideo) {
this.mediaDom.remoteVideo = md.remoteVideo
}
if(md.localVideo) {
this.mediaDom.localVideo = md.localVideo
}
}
// bind callback events on sipua
private bindSipUAEvents() {
// 当UA被其他用户拨打时(Call In)
this.SipUA.on('invite', (session: IncomingSession) => {
this.onInviteEvent(session)
})
// 当连接到server时的回调
this.SipUA.on('connecting', () => {
console.log(`[sipcall] on connecting`)
})
// 当完成连接时的回调
this.SipUA.on('connected', () => {
// 如果用户已注册,则发出"已准备好"信号,否则发出"未准备好"
console.log(`[sipcall] on connected`)
})
// 当用户退出登录时
this.SipUA.on('unregistered', (response: string, cause: string) => {
console.log(`[sipcall] on unregistered ${response} ${cause}`)
})
// 当用户以登录时
this.SipUA.on('registered', () => {
console.log(`[sipcall] on registered`)
})
// 当用户断开连接时
this.SipUA.on('disconnected', () => {
console.log(`[sipcall] on disconnected`)
})
// 当注册失败时
this.SipUA.on('registrationFailed', (response: string, cause: string) => {
console.log(`[sipcall] on registrationFailed`)
})
this.SipUA.on('transportCreated', (transport: Transport) => {
transport.on('transportError', this.onTransportError.bind(this))
})
this.SipUA.on('message', (message: string) => {
console.log('[sipcall] on receive message')
})
}
// when someone invite you , tigger this function.
private onInviteEvent(session: IncomingSession) {
// if is talking
if (this.currentSession !== null) {
(session as SIP.ServerContext).reject({
statusCode: 486
})
return false
}
this.currentSession = session
this.setParamsBySessionMediaType(this.currentSession)
this.bindIncomingCallSessionEvent(this.currentSession)
if (this.isIncomingCallFromInternal(this.currentSession)) {
this.emit('callIn', this.currentSession)
} else {
this.emit('callOutBack', this.currentSession)
}
}
/**
* @description: SDP modifiers
* @param {type}
* @return:
*/
private generateModifiers(modifiers: IModifiers = { ptime: '20', capturerate: '24000', bitrate: '30000' }) {
const myModifier = (description: RTCSessionDescriptionInit) => {
description.sdp = (description as RTCSessionDescription).sdp.replace(/a=fmtp:111 minptime=10;useinbandfec=1/img, `a=fmtp:111 ptime=${modifiers.ptime}; useinbandfec=1; maxplaybackrate=${modifiers.bitrate}; sprop-maxcapturerate=${modifiers.capturerate}; maxaveragebitrate=${modifiers.bitrate}; usedtx=1`);
return Promise.resolve(description);
};
const modifierArray = [myModifier, SIP.Web.Modifiers.stripTelephoneEvent];
return modifierArray;
}
/**
* 呼叫其他用户
* @params: number 用户号码, mediaType 媒体类型(audio音频/video视频)
*/
invite(number: string, mediaType: string = 'audio', password?: string) {
// 如果是视频
const video = (mediaType === 'video')
this.setCurrentSessionParams({ video })
// uri
const uri = new SIP.URI('', number, this.sipServers[0].server)
// 如果有密码,则在params中传入密码
if (password) {
uri.setParam('aaa', 'bbb') // 应后端需要,增加占位参数
uri.setParam('matrix_conference_pin', password)
}
// descriptionModifier
const modifiers = this.generateModifiers(this.modifiersParams);
// 呼叫其他用户,并返回该通话的session
this.currentSession = this.SipUA.invite(uri, this.SessionParams)
// 绑定当前session
this.bindOutgoingCallSessionEvent(this.currentSession as OutgoingSession)
// 呼出回调
this.emit('callOut')
}
// is this coming call from internal (means outcall 's callback)
private isIncomingCallFromInternal(session: IncomingSession) {
// 如果呼入方是internal(内部),则是回呼
if (session && session.request && session.request.from && session.request.from.displayName === 'internal') {
return false
} else {
return true
}
}
private onTransportError() {
}
private bindOutgoingCallSessionEvent(session: OutgoingSession) {
// 同意通话时
session.on('accepted', (response: SIP.IncomingResponse, cause: string) => {
console.log(`[sipcall] session accepted \n ${response} ${cause}`)
this.emit('accepted', { response, cause })
})
// 被拒绝时
// Fired each time an unsuccessful final (300-699) response is received. Note: This will also emit a failed event, followed by a terminated event.
session.on('rejected', (response: SIP.IncomingResponse, cause: string) => {
console.log(`[sipcall] session rejected ${response} ${cause}`)
this.emit('stopTracks')
// 被动挂断
this.emit('hungup', { response, cause })
this.emit('callEnd')
})
session.on('failed', (response: SIP.IncomingResponse, cause: string) => {
console.log('[sipcall debug]', response)
const error = this.parseError(response)
this.emit('error', error)
})
}
// bind event on session
private bindIncomingCallSessionEvent(session: IncomingSession) {
// 被结束时
session.on('bye', (request: SIP.IncomingRequest) => {
console.log(`[sipcall] session bye`, request)
this.emit('stopTracks')
// 被动挂断
this.emit('hungup', { request })
this.emit('callEnd')
})
// 通话被取消时
session.on('cancel', () => {
console.log(`[sipcall] session cancel`)
this.emit('stopTracks')
// 被动挂断
this.emit('hungup')
this.emit('callEnd')
});
(session as SIP.ServerContext).on('failed', (request: SIP.IncomingRequest, cause: string) => {
console.log('[sipcall debug]', request)
const error = this.parseError(request)
this.emit('error', error)
})
// 有音视频流加入时
// 仅展示的媒体类型
session.on('trackAdded', () => {
if (this.currentSessionParams.video) {
console.log('[sipcall] video track comming ...')
// localVideo.muted = true;
// We need to check the peer connection to determine which track was added
const pc = (session as any).sessionDescriptionHandler.peerConnection
// Gets remote tracks
const remoteStream = new MediaStream()
pc.getReceivers().forEach(function(receiver: RTCRtpReceiver) {
remoteStream.addTrack(receiver.track)
});
(this.mediaDom.remoteVideo as HTMLAudioElement).srcObject = remoteStream;
(this.mediaDom.remoteVideo as HTMLAudioElement).play()
// Gets local tracks
// const localStream = new MediaStream();
// pc.getSenders().forEach(function(sender) {
// localStream.addTrack(sender.track);
// });
// localVideo.srcObject = localStream;
// localVideo.play();
const constraints = { audio: false, video: true }
navigator.mediaDevices
.getUserMedia(constraints)
.then((stream) => {
// 获取track句柄,方便结束时关闭
this.videoTrack = this.videoTrack.concat(stream.getTracks());
(this.mediaDom.localVideo as HTMLVideoElement).srcObject = stream;
(this.mediaDom.localVideo as HTMLVideoElement).onloadedmetadata = (e) => {
(this.mediaDom.localVideo as HTMLVideoElement).play()
}
})
.catch((err) => {
console.log(`[trackAdd local video] ${err.name}:${err.message}`)
})
} else if (this.currentSessionParams.audio) {
console.log('[sipcall] audio track comming ...')
// We need to check the peer connection to determine which track was added
const pc = (session as any).sessionDescriptionHandler.peerConnection
// Gets remote tracks
const remoteStream = new MediaStream()
pc.getReceivers().forEach(function(receiver: RTCRtpReceiver) {
remoteStream.addTrack(receiver.track)
});
// 普通电话在remoteAudio直接播放
(this.mediaDom.remoteAudio as HTMLAudioElement).srcObject = remoteStream;
(this.mediaDom.remoteAudio as HTMLAudioElement).play()
// this.RTCAnalysis({ peerConnection: pc, callbackFn: this.emit('RTCAnalysisCallback })
}
})
}
/**
* @description: 分析WebRTC数据
* @param {type}
* @return:
*/
// private RTCAnalysis({ peerConnection, repeatInterval = 10000, callbackFn }) {
// getStats(peerConnection, function (result) {
// const audioLatency = Number(result.audio.latency);
// const audioPacketsLost = Number(result.audio.packetsLost);
// const audioBytesReceived = Number(result.audio.bytesReceived);
// const audioBytesSent = Number(result.audio.bytesSent);
// // const speed = result.bandwidth.speed; // bandwidth download speed (bytes per second)
// let googSent = null
// let googReceived = null
// // result.results.forEach(function (item) {
// // if (item.type === 'ssrc'/* && item.transportId === 'Channel-audio-1'*/) {
// // if (item.hasOwnProperty('packetsSent')) {
// // googSent = item
// // } else if (item.hasOwnProperty('packetsReceived')) {
// // googReceived = item
// // }
// // }
// // });
// // 时间戳
// const timestamp = parseTime(Date.now())
// callbackFn.call(this, {
// timestamp,
// audioLatency,
// audioPacketsLost,
// audioBytesReceived,
// audioBytesSent
// })
// }, repeatInterval);
// }
private stopTracks() {
if (this.videoTrack.length) {
this.videoTrack.map(track => {
track.stop()
})
this.videoTrack.splice(0)
}
}
parseError(response: any) {
const reason = response.reasonPhrase
const code = response.statusCode
let message = ''
const messageType = 'warning'
if (reason === SIP.C.causes.BUSY) {
message = '对方正忙,请稍后再拨'
} else if (reason === SIP.C.causes.REJECTED) {
message = '您的呼叫被拒绝'
} else if (reason === SIP.C.causes.REDIRECTED) {
message = '对方号码可能被迁移'
} else if (reason === SIP.C.causes.UNAVAILABLE) {
message = '用户无法访问'
} else if (reason === SIP.C.causes.NOT_FOUND) {
message = '找不到该用户'
} else if (reason === SIP.C.causes.ADDRESS_INCOMPLETE) {
message = '地址不全'
} else if (reason === SIP.C.causes.INCOMPATIBLE_SDP) {
message = '不可用'
} else if (reason === SIP.C.causes.AUTHENTICATION_ERROR) {
message = '无授权'
// } else if (cause === SIP.C.causes.INVALID_TARGET) {
// message = 'SIP URI 错误';
} else if (reason === SIP.C.causes.CONNECTION_ERROR) {
message = 'SIP Websocket 连接错误'
} else if (reason === SIP.C.causes.REQUEST_TIMEOUT) {
message = 'SIP 请求超时'
} else if (code === 487) {
// Request Terminated
// message = '呼叫取消';
} else if (code === 480) {
// Temporarily Unavailable
message = '对方暂时无法接听'
} else {
message = reason
}
return { message, messageType, reason, code }
}
private setParamsBySessionMediaType(session: IncomingSession | OutgoingSession) {
// 需要wsc指定媒体类型
if (session.body) {
const sessionBody = session.body
if (sessionBody.indexOf('video') > 0) {
this.setCurrentSessionParams({ video: true })
console.log('set options media to video')
} else if (sessionBody.indexOf('audio') > 0) {
this.setCurrentSessionParams({ audio: true })
console.log('set options media to audio')
}
}
}
/**
* 设置用户配置
* params: {
* video: true,
* audio: true, 音频应该始终为true
* type: 'common' 普通电话 'meeting' 会议
* }
*/
private setCurrentSessionParams({ audio = true, video = false }) {
// 设置音频
this.currentSessionParams.audio = audio
// 设置视频
this.currentSessionParams.video = video
return this.currentSession
}
/**
* 全部回调
* TODO: 做成订阅/发布
*/
registerDefaultEvents() {
this.on('callEnd', () => {
// 通话结束的收尾工作
this.currentSession = null
this.emit('RTCAnalysisCallback', null)
})
this.on('error', (error: IErrorMsg) => {
console.log(`[sipcall] error ${error.code}`)
})
this.on('stopTracks', () => {
this.stopTracks()
})
}
private get SessionParams() {
const { audio, video } = this.currentSessionParams
const params = {
media: {
constraints: {
audio,
video
},
// stream: this.silentStream,
render: {}
},
sessionDescriptionHandlerOptions: {
constraints: {
audio,
video
}
}
}
return params
}
// get sip config , depends on wsServers and sip account
private get sipConfig() {
const uri = `${this.sipAccount.no}@${this.sipServers[0].server}`
const wsServers = this.sipServers.map(item => `${item.protocol}://${item.server}:${item.port}`)
const authorizationUser = this.sipAccount.no
const password = this.sipAccount.pwd
const config = {
uri,
transportOptions: {
wsServers,
maxReconnectionAttempts: 99999999, // 两年
reconnectionTimeout: 5
},
sessionDescriptionHandlerFactoryOptions: {
peerConnectionOptions: {
rtcConfiguration: {
iceServers: [
{ urls: 'stun:stun1.l.google.com:19302' },
{ urls: 'stun:stun.fwdnet.net' },
{ urls: 'stun:stun.ekiga.net' },
{ urls: 'stun:stun.ideasip.com' }
]
}
}
},
authorizationUser,
password,
allowLegacyNotifications: true,
autostart: true,
register: true,
registerExpires: 60,
traceSip: true,
log: {
builtinEnabled: true,
connector: (level: string, category: string, label: string | undefined, content: any) => `${level} ${category} ${label} ${content}`,
level: 'debug' // "debug", "log", "warn", "error"
},
rel100: SIP.C.supported.SUPPORTED
}
return config
}
// login to server
login() {
}
}
export { sipphone }