@yaks/voipms 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/voice.ts ADDED
@@ -0,0 +1,316 @@
1
+ // The carrier's SIP accounts for one DID. Account names identify the line
2
+ // even after deletion, so its outstanding call records can still be billed.
3
+ import {
4
+ CallStopError,
5
+ type Login,
6
+ type SubmitLogin,
7
+ type Voice,
8
+ } from '@yaks/phone'
9
+ import { Unsent } from '@yaks/host/senders'
10
+ import { type Call, type Params, TimedOut, VOIPMS } from './request.js'
11
+
12
+ type Fields = Record<string, string | number | undefined>
13
+
14
+ export let accountFor = (digits: string) => `y${digits}`
15
+
16
+ // voip.ms silently truncates the username suffix to twelve characters.
17
+ let seatPrefix = (digits: string) =>
18
+ `y${Number(digits).toString(36).padStart(7, '0')}`
19
+
20
+ let seatAccount = (digits: string, seat: string, legacy: string | null) =>
21
+ seat == legacy ? accountFor(digits) : seatPrefix(digits) +
22
+ (parseInt(seat.slice(0, 8), 16) % (36 ** 4)).toString(36).padStart(4, '0')
23
+
24
+ export let callsAs = (digits: string, account: string) =>
25
+ account.endsWith(`_${accountFor(digits)}`) ||
26
+ new RegExp(`_${seatPrefix(digits)}[0-9a-z]{4}$`).test(account)
27
+
28
+ let accountsOf = async (call: Call, digits: string) =>
29
+ (((await call('getSubAccounts')).accounts ?? []) as Fields[])
30
+ .filter((a) => callsAs(digits, String(a.account)))
31
+ .sort((a, b) => Number(a.id) - Number(b.id))
32
+
33
+ let drop = (call: Call, account: Fields) =>
34
+ call('delSubAccount', { id: String(account.id) })
35
+
36
+ /** A purchase failed before the DID could be put to use. */
37
+ export let abandon = async (call: Call, digits: string) => {
38
+ await call('cancelDID', { did: digits })
39
+ for (let account of await accountsOf(call, digits)) await drop(call, account)
40
+ }
41
+
42
+ export let heldDid = async (call: Call, digits: string) => {
43
+ let held = await call('getDIDsInfo', { did: digits }).then(
44
+ (said) => (said.dids ?? []) as Fields[],
45
+ (error) => {
46
+ if (/invalid_did|no_did/.test(String(error))) return []
47
+ throw error
48
+ },
49
+ )
50
+ return held.find((d) => String(d.did) == digits)
51
+ }
52
+
53
+ let NOWHERE = '192.0.2.1'
54
+
55
+ let restriction = (out: boolean): Params => ({
56
+ enable_ip_restriction: out ? '0' : '1',
57
+ ip_restriction: out ? '' : NOWHERE,
58
+ })
59
+
60
+ let described = (digits: string, seat?: string) =>
61
+ seat ? `+1${digits} ${seat}` : `+1${digits}`
62
+
63
+ export let made = (
64
+ call: Call,
65
+ digits: string,
66
+ username: string,
67
+ out: boolean,
68
+ seat?: string,
69
+ ) =>
70
+ call('createSubAccount', {
71
+ username,
72
+ protocol: '1',
73
+ description: described(digits, seat),
74
+ auth_type: '1',
75
+ password: `Y${crypto.randomUUID().replaceAll('-', '')}`,
76
+ device_type: '2',
77
+ callerid_number: digits,
78
+ lock_international: '1',
79
+ international_route: '1',
80
+ music_on_hold: 'default',
81
+ allowed_codecs: 'ulaw;g729;gsm',
82
+ dtmf_mode: 'AUTO',
83
+ nat: 'yes',
84
+ ...restriction(out),
85
+ })
86
+
87
+ let blocking = async (call: Call, account: Fields, out: boolean) => {
88
+ let shut = String(account.enable_ip_restriction) == '1' &&
89
+ account.ip_restriction == NOWHERE
90
+ if (shut != out) return
91
+ let { account: _, ...said } = account
92
+ await call('setSubAccount', {
93
+ ...Object.fromEntries(
94
+ Object.entries(said).map(([k, v]) => [k, String(v ?? '')]),
95
+ ),
96
+ ...restriction(out),
97
+ })
98
+ }
99
+
100
+ // Every step runs, and any failure fails the whole once all have ended.
101
+ let settled = async (steps: Promise<unknown>[]) => {
102
+ let ends = await Promise.allSettled(steps)
103
+ let errors = ends.flatMap((r) => r.status == 'rejected' ? [r.reason] : [])
104
+ if (errors.length == 1) throw errors[0]
105
+ if (errors.length) throw new AggregateError(errors, 'voip.ms refused a step')
106
+ }
107
+
108
+ let twice = <T>(step: () => Promise<T>) => step().catch(() => step())
109
+
110
+ let failed = (step: Promise<unknown>): Promise<unknown[]> =>
111
+ step.then(
112
+ () => [],
113
+ (error) => error instanceof AggregateError ? error.errors : [error],
114
+ )
115
+
116
+ let shut = async (
117
+ call: Call,
118
+ digits: string,
119
+ restrict: () => Promise<unknown>,
120
+ ) => {
121
+ // Stop calls out first, but try incoming even when restricting fails.
122
+ let out = await failed(twice(restrict))
123
+ let incoming = await failed(
124
+ heldDid(call, digits).then(async (did) => {
125
+ if (did && did.routing != 'sys:hangup') {
126
+ await call('setDIDRouting', { did: digits, routing: 'sys:hangup' })
127
+ }
128
+ }),
129
+ )
130
+ if (out.length || incoming.length) {
131
+ throw new CallStopError({ in: !incoming.length, out: !out.length }, [
132
+ ...out,
133
+ ...incoming,
134
+ ])
135
+ }
136
+ }
137
+
138
+ let groupOf = async (call: Call, digits: string) => {
139
+ let groups = await call('getRingGroups').catch((error) => {
140
+ if (/no_ringgroup/.test(String(error))) return { ring_groups: [] }
141
+ throw error
142
+ })
143
+ return ((groups.ring_groups ?? []) as Fields[])
144
+ .find((g) => g.name == accountFor(digits))
145
+ }
146
+
147
+ let route = async (call: Call, digits: string, accounts: Fields[]) => {
148
+ let did = await heldDid(call, digits)
149
+ let routedToGroup = String(did?.routing ?? '').startsWith('grp:')
150
+ let group = accounts.length > 1 ? await groupOf(call, digits) : undefined
151
+ let members = accounts.map((a) => `account:${a.account},25,0`).sort().join(
152
+ ';',
153
+ )
154
+ let routing = accounts.length
155
+ ? `account:${accounts[0].account}`
156
+ : 'sys:hangup'
157
+ if (accounts.length > 1) {
158
+ let id = group?.ring_group
159
+ if (!group || group.members != members) {
160
+ let set = await call('setRingGroup', {
161
+ name: accountFor(digits),
162
+ members,
163
+ ...(id ? { ring_group: String(id) } : {}),
164
+ })
165
+ id = (set.ring_group ?? id) as string | undefined
166
+ }
167
+ if (!id) throw new Error('voip.ms did not return the ring group ID')
168
+ routing = `grp:${id}`
169
+ }
170
+ if (did && did.routing != routing) {
171
+ await call('setDIDRouting', { did: digits, routing })
172
+ }
173
+ if (routedToGroup && accounts.length < 2) {
174
+ let old = await groupOf(call, digits)
175
+ if (old) await call('delRingGroup', { ringgroup: String(old.ring_group) })
176
+ }
177
+ }
178
+
179
+ let belongs = (
180
+ account: Fields,
181
+ digits: string,
182
+ seat: string,
183
+ legacy: string | null,
184
+ ) =>
185
+ account.username == seatAccount(digits, seat, legacy) &&
186
+ (seat == legacy || account.description == described(digits, seat))
187
+
188
+ let taken = async (
189
+ call: Call,
190
+ digits: string,
191
+ seat: string,
192
+ voice: Voice,
193
+ submit?: SubmitLogin,
194
+ ) => {
195
+ let username = seatAccount(digits, seat, voice.legacy)
196
+ let find = async () =>
197
+ (await accountsOf(call, digits))
198
+ .find((a) => belongs(a, digits, seat, voice.legacy))
199
+ let account = await find()
200
+ if (account) return account
201
+ if (submit && !await submit(seat)) return undefined
202
+ await made(
203
+ call,
204
+ digits,
205
+ username,
206
+ voice.out,
207
+ seat == voice.legacy ? undefined : seat,
208
+ )
209
+ .catch(async (error) => {
210
+ if (await find()) return
211
+ if (error instanceof TimedOut) {
212
+ throw new Unsent('voip.ms has yet to confirm the SIP account')
213
+ }
214
+ throw error
215
+ })
216
+ account = await find()
217
+ if (!account) throw new Error('voip.ms did not return the new SIP account')
218
+ return account
219
+ }
220
+
221
+ export let allow = async (
222
+ call: Call,
223
+ digits: string,
224
+ voice: Voice,
225
+ submit?: SubmitLogin,
226
+ ) => {
227
+ let requested = new Set([voice.legacy, ...voice.requested ?? []])
228
+ let seats = voice.seats.filter((seat) =>
229
+ requested.has(seat) && !voice.revoked?.includes(seat)
230
+ )
231
+ let keep = async () => {
232
+ let kept = new Map<string, Fields>()
233
+ let gone: Fields[] = []
234
+ for (let account of await accountsOf(call, digits)) {
235
+ let username = String(account.account)
236
+ let mine = seats.some((seat) =>
237
+ belongs(account, digits, seat, voice.legacy)
238
+ )
239
+ if (mine && !kept.has(username)) kept.set(username, account)
240
+ else gone.push(account)
241
+ }
242
+ let out = voice.in && voice.out
243
+ await settled([...kept.values()].map((a) => blocking(call, a, out)))
244
+ await settled(gone.map((account) => drop(call, account)))
245
+ return kept
246
+ }
247
+ if (!voice.in) {
248
+ // Trash restricts every sign-in. Only a separate seat revocation drops one.
249
+ await shut(
250
+ call,
251
+ digits,
252
+ voice.revoked?.length ? keep : async () =>
253
+ settled(
254
+ (await accountsOf(call, digits)).map((a) => blocking(call, a, false)),
255
+ ),
256
+ )
257
+ return
258
+ }
259
+ let kept = await keep()
260
+ for (let seat of seats) {
261
+ if (
262
+ ![...kept.values()].some((a) => belongs(a, digits, seat, voice.legacy))
263
+ ) {
264
+ let account = await taken(call, digits, seat, voice, submit)
265
+ if (account) kept.set(String(account.account), account)
266
+ }
267
+ }
268
+ await route(call, digits, [...kept.values()])
269
+ }
270
+
271
+ export let release = async (call: Call, digits: string) => {
272
+ await call('cancelDID', { did: digits }).catch(async (error) => {
273
+ if (await heldDid(call, digits)) throw error
274
+ })
275
+ }
276
+
277
+ export let cleanup = async (call: Call, digits: string) => {
278
+ await settled([
279
+ accountsOf(call, digits).then((accounts) =>
280
+ settled(accounts.map((account) => drop(call, account)))
281
+ ),
282
+ groupOf(call, digits).then(async (group) => {
283
+ if (group) {
284
+ await call('delRingGroup', { ringgroup: String(group.ring_group) })
285
+ }
286
+ }),
287
+ ])
288
+ }
289
+
290
+ export let login = async (
291
+ call: Call,
292
+ digits: string,
293
+ seat: string,
294
+ voice: Voice,
295
+ submit?: SubmitLogin,
296
+ ): Promise<Login> => {
297
+ if (!voice.in || !voice.seats.includes(seat)) {
298
+ throw new Error('This seat cannot sign a softphone in')
299
+ }
300
+ let account = await taken(call, digits, seat, voice, submit)
301
+ if (!account) throw new Unsent('voip.ms has yet to confirm the SIP account')
302
+ if (!account.password) {
303
+ throw new Error('voip.ms did not return the softphone sign-in')
304
+ }
305
+ await allow(call, digits, voice, submit)
306
+ let [server] = ((await call('getServersInfo', { server_pop: VOIPMS.pop }))
307
+ .servers ?? []) as Fields[]
308
+ if (!server?.server_hostname) {
309
+ throw new Error('voip.ms did not return the SIP server')
310
+ }
311
+ return {
312
+ server: String(server.server_hostname),
313
+ user: String(account.account),
314
+ password: String(account.password),
315
+ }
316
+ }