-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
74 lines (70 loc) · 2.71 KB
/
index.js
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
import RingCentral from '@ringcentral/sdk'
import Subscriptions from '@ringcentral/subscriptions'
import Speaker from 'speaker'
import { nonstandard } from 'wrtc'
import Softphone from 'ringcentral-softphone'
import fs from 'fs'
const rc = new RingCentral({
server: process.env.RINGCENTRAL_SERVER_URL,
clientId: process.env.RINGCENTRAL_CLIENT_ID,
clientSecret: process.env.RINGCENTRAL_CLIENT_SECRET
})
;(async () => {
await rc.login({
username: process.env.RINGCENTRAL_USERNAME,
extension: process.env.RINGCENTRAL_EXTENSION,
password: process.env.RINGCENTRAL_PASSWORD
})
const softphone = new Softphone(rc)
await softphone.register()
softphone.on('INVITE', sipMessage => {
softphone.answer(sipMessage)
softphone.once('track', e => {
const audioSink = new nonstandard.RTCAudioSink(e.track)
let speaker = null
let prevSampleRate = null
const audioFilePath = 'call.raw'
if (fs.existsSync(audioFilePath)) {
fs.unlinkSync(audioFilePath)
}
const writeStream = fs.createWriteStream(audioFilePath, { flags: 'a' })
audioSink.ondata = data => {
console.log('live audio data receivedlive audio data received, sample rate is', data.sampleRate)
if (speaker === null) {
if (data.sampleRate === prevSampleRate) { // wait until sample rate stable
speaker = new Speaker({ channels: data.channelCount, bitDepth: data.bitsPerSample, sampleRate: data.sampleRate, signed: true })
}
prevSampleRate = data.sampleRate
} else {
speaker.write(Buffer.from(data.samples.buffer))
writeStream.write(Buffer.from(data.samples.buffer))
}
}
softphone.once('BYE', () => {
audioSink.stop()
speaker.close()
})
})
})
const r = await rc.get('/restapi/v1.0/account/~/extension')
const json = await r.json()
const agentExt = json.records.filter(ext => ext.extensionNumber === process.env.RINGCENTRAL_AGENT_EXT)[0]
const subscriptions = new Subscriptions({
sdk: rc
})
const subscription = subscriptions.createSubscription({
pollInterval: 10 * 1000,
renewHandicapMs: 2 * 60 * 1000
})
subscription.setEventFilters([`/restapi/v1.0/account/~/extension/${agentExt.id}/telephony/sessions`])
subscription.on(subscription.events.notification, async function (message) {
if (message.body.parties.some(p => p.status.code === 'Answered' && p.direction === 'Inbound')) {
await rc.post(`/restapi/v1.0/account/~/telephony/sessions/${message.body.telephonySessionId}/supervise`, {
mode: 'Listen',
supervisorDeviceId: softphone.device.id,
agentExtensionNumber: agentExt.extensionNumber
})
}
})
await subscription.register()
})()