@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/request.js ADDED
@@ -0,0 +1,115 @@
1
+ // The voip.ms HTTP boundary. Number tools give each exchange a deadline.
2
+ import { Unsent } from "@yaks/host/senders";
3
+ import { Blocked, Denied } from "@yaks/phone";
4
+ /** voip.ms as data: its API, how long a text may be, and the statuses that
5
+ * mean a text will not go, in a person's words. */ export let VOIPMS = {
6
+ api: 'https://voip.ms/api/v1/rest.php',
7
+ /** the most characters `sendSMS` takes; a longer text goes as `sendMMS` */ sms: 160,
8
+ /** the most characters `sendMMS` takes */ mms: 2048,
9
+ /** the variables its SMS URL callback fills in, as a query a host appends
10
+ * to its own address. Its {TIMESTAMP} names no time zone, so a text is
11
+ * kept as arriving when the callback came. */ callback: 'id={ID}&from={FROM}&to={TO}&message={MESSAGE}',
12
+ /** the server a number bought here rings, by voip.ms's number for it:
13
+ * Chicago */ pop: '7',
14
+ /** a number bought here pays by the minute its calls take, voip.ms's
15
+ * cheaper monthly price */ billing: '1',
16
+ blocked: {
17
+ limit_reached: 'voip.ms allows 100 texts a day from this line, and today’s are spent. Send it again tomorrow.',
18
+ sms_toolong: 'The text is longer than voip.ms carries (2,048 characters).',
19
+ invalid_dst: 'voip.ms says this number cannot get texts. It may be a landline or mistyped; check it in the directory.'
20
+ },
21
+ denied: {
22
+ ip_not_enabled: 'voip.ms refused the address yaks.app calls from. On voip.ms, open Main Menu, then SOAP & REST/JSON API, enter 0.0.0.0 under Enable IP Addresses and save.',
23
+ invalid_credentials: 'voip.ms refused the username or API password. The username is the email you sign in to voip.ms with; the API password is the one set on its SOAP & REST/JSON API page.',
24
+ missing_credentials: 'voip.ms needs the username and the API password.',
25
+ api_not_enabled: 'The voip.ms API is not enabled. On voip.ms, open Main Menu, then SOAP & REST/JSON API, and enable it.'
26
+ }
27
+ };
28
+ // voip.ms's API, called as the account: each method a GET carrying its
29
+ // username and API password, its answer's status read the same way for all.
30
+ // Given `methods`, any other is never sent.
31
+ export let requester = ({ user, key, api = VOIPMS.api, methods, fetch: given })=>async (method, params = {}, signal)=>{
32
+ if (methods && !methods.includes(method)) {
33
+ throw new Error(`This voip.ms account cannot ask for ${method}`);
34
+ }
35
+ let url = new URL(api);
36
+ for (let [k, v] of Object.entries({
37
+ api_username: user,
38
+ api_password: key,
39
+ method,
40
+ ...params
41
+ }))url.searchParams.set(k, v);
42
+ let response;
43
+ try {
44
+ // The global fetch as it is at the call, not as it was when this was made.
45
+ response = await (given ?? globalThis.fetch)(url, {
46
+ headers: {
47
+ accept: 'application/json'
48
+ },
49
+ signal
50
+ });
51
+ } catch {
52
+ signal?.throwIfAborted();
53
+ throw new Unsent(`voip.ms could not be reached for ${method}`);
54
+ }
55
+ if (response.status >= 500 || response.status == 429) {
56
+ await response.body?.cancel();
57
+ throw new Unsent(`voip.ms is not answering right now (${response.status} to ${method})` + (signal ? '' : '; yaks.app will try again'), 30_000);
58
+ }
59
+ let said = await response.json().catch(()=>{
60
+ signal?.throwIfAborted();
61
+ return {};
62
+ });
63
+ let status = String(said.status ?? '');
64
+ if (status == 'success') return said;
65
+ if (VOIPMS.blocked[status]) {
66
+ throw new Blocked(VOIPMS.blocked[status], status);
67
+ }
68
+ if (VOIPMS.denied[status]) throw new Denied(VOIPMS.denied[status], status);
69
+ throw new Error(`voip.ms answered ${status || response.status} to ${method}: ${said.message ?? 'no reason given'}`);
70
+ };
71
+ let CALL = 15_000;
72
+ /** A voip.ms method not answered in time: as every slow answer, `Unsent`,
73
+ * asked again later, though one that acts may have acted all the same. */ export class TimedOut extends Unsent {
74
+ constructor(method){
75
+ super(`voip.ms did not answer ${method} in time`);
76
+ }
77
+ }
78
+ /** The voip.ms methods that may be asked twice: those that read, and the
79
+ * settings that say the whole of what they set (`setSubAccount` is sent
80
+ * every field the account has). Any other may have acted
81
+ * however its first asking ended, so it is never asked again. */ export let REPEATABLE = /^(get|search)[A-Z]|^(setSMS|setDIDRouting|setSubAccount)$/;
82
+ /**
83
+ * Every voip.ms call, under one policy: each asking ends by `by` and within
84
+ * {@link CALL}; a {@link REPEATABLE} method that voip.ms is slow to answer,
85
+ * or answers with a 5xx, is asked once more, each asking with half the
86
+ * time. A slow answer is always `Unsent`, for the caller to ask again later:
87
+ * a second one of a repeatable method, and the timeout of any other, which is
88
+ * asked once ({@link TimedOut}). A caller can also ask for a single attempt.
89
+ */ export let bounded = (request, time, by = Infinity, retry = true)=>async (method, params)=>{
90
+ let once = async (until)=>{
91
+ let ms = until - time.now();
92
+ if (ms <= 0) throw new TimedOut(method);
93
+ let stop = new AbortController();
94
+ let cancel = time.after(ms, ()=>stop.abort(new TimedOut(method)));
95
+ try {
96
+ return await request(method, params, stop.signal);
97
+ } finally{
98
+ cancel();
99
+ }
100
+ };
101
+ let end = ()=>Math.min(by, time.now() + CALL);
102
+ if (!retry || !REPEATABLE.test(method)) return await once(end());
103
+ let slow = (e)=>e instanceof Unsent;
104
+ let last = end();
105
+ try {
106
+ return await once(Math.min(last, time.now() + CALL / 2));
107
+ } catch (error) {
108
+ if (!slow(error)) throw error;
109
+ return await once(last).catch((again)=>{
110
+ if (!slow(again)) throw again;
111
+ throw new Unsent(`voip.ms is slow to answer ${method} right now`);
112
+ });
113
+ }
114
+ };
115
+ //# sourceMappingURL=request.js.map
package/request.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request.js","sources":["./request.ts"],"names":[],"mappings":"AAAA,yEAAyE;AAEzE,SAAS,MAAM,kCAAuC;AACtD,SAAS,OAAO,EAAE,MAAM,2BAAgC;AAExD;iDACiD,GACjD,OAAO,IAAI,SAAS;EAClB,KAAK;EACL,yEAAyE,GACzE,KAAK;EACL,wCAAwC,GACxC,KAAK;EACL;;8CAE4C,GAC5C,UAAU;EACV;aACW,GACX,KAAK;EACL;2BACyB,GACzB,SAAS;EACT,SAAS;IACP,eACE;IACF,aAAa;IACb,aACE;EACJ;EACA,QAA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AAM,KAAK,CAAC,CAAC;QAC7B,IAAI,CAAC,KAAK,QAAQ,MAAM;QACxB,MAAM,IAAI,OAAO,CAAC,0BAA0B,EAAE,OAAO,UAAU,CAAC;MAClE;IACF;EACF,EAAC"}
package/request.ts ADDED
@@ -0,0 +1,182 @@
1
+ // The voip.ms HTTP boundary. Number tools give each exchange a deadline.
2
+ import type { Clock } from 'jsr:@yaks/fp@0.2.36'
3
+ import { Unsent } from '@yaks/host/senders'
4
+ import { Blocked, Denied } from '@yaks/phone'
5
+
6
+ /** voip.ms as data: its API, how long a text may be, and the statuses that
7
+ * mean a text will not go, in a person's words. */
8
+ export let VOIPMS = {
9
+ api: 'https://voip.ms/api/v1/rest.php',
10
+ /** the most characters `sendSMS` takes; a longer text goes as `sendMMS` */
11
+ sms: 160,
12
+ /** the most characters `sendMMS` takes */
13
+ mms: 2048,
14
+ /** the variables its SMS URL callback fills in, as a query a host appends
15
+ * to its own address. Its {TIMESTAMP} names no time zone, so a text is
16
+ * kept as arriving when the callback came. */
17
+ callback: 'id={ID}&from={FROM}&to={TO}&message={MESSAGE}',
18
+ /** the server a number bought here rings, by voip.ms's number for it:
19
+ * Chicago */
20
+ pop: '7',
21
+ /** a number bought here pays by the minute its calls take, voip.ms's
22
+ * cheaper monthly price */
23
+ billing: '1',
24
+ blocked: {
25
+ limit_reached:
26
+ 'voip.ms allows 100 texts a day from this line, and today’s are spent. Send it again tomorrow.',
27
+ sms_toolong: 'The text is longer than voip.ms carries (2,048 characters).',
28
+ invalid_dst:
29
+ 'voip.ms says this number cannot get texts. It may be a landline or mistyped; check it in the directory.',
30
+ } as Record<string, string>,
31
+ denied: {
32
+ ip_not_enabled:
33
+ 'voip.ms refused the address yaks.app calls from. On voip.ms, open Main Menu, then SOAP & REST/JSON API, enter 0.0.0.0 under Enable IP Addresses and save.',
34
+ invalid_credentials:
35
+ 'voip.ms refused the username or API password. The username is the email you sign in to voip.ms with; the API password is the one set on its SOAP & REST/JSON API page.',
36
+ missing_credentials: 'voip.ms needs the username and the API password.',
37
+ api_not_enabled:
38
+ 'The voip.ms API is not enabled. On voip.ms, open Main Menu, then SOAP & REST/JSON API, and enable it.',
39
+ } as Record<string, string>,
40
+ }
41
+
42
+ /** How a voip.ms sender is made. */
43
+ export type Voipms = {
44
+ /** the email the account signs in with */
45
+ user: string
46
+ /** the API password, set on its SOAP & REST/JSON API page */
47
+ key: string
48
+ /** the number texts go from, in E.164 form; absent, the account's first
49
+ * number that texts */
50
+ number?: string
51
+ /** the API's address (default {@link VOIPMS}.api) */
52
+ api?: string
53
+ /** the only methods this client may ask for; none is any, which only
54
+ * the numbers our own account sells are reached with (./mod.ts
55
+ * `numbers`) */
56
+ methods?: string[]
57
+ fetch?: typeof fetch
58
+ }
59
+
60
+ type Said = Record<string, unknown> & { status?: string; message?: string }
61
+ export type Params = Record<string, string>
62
+ export type Call = (method: string, params?: Params) => Promise<Said>
63
+
64
+ // voip.ms's API, called as the account: each method a GET carrying its
65
+ // username and API password, its answer's status read the same way for all.
66
+ // Given `methods`, any other is never sent.
67
+ export let requester = (
68
+ { user, key, api = VOIPMS.api, methods, fetch: given }: Omit<
69
+ Voipms,
70
+ 'number'
71
+ >,
72
+ ) =>
73
+ async (
74
+ method: string,
75
+ params: Params = {},
76
+ signal?: AbortSignal,
77
+ ): Promise<Said> => {
78
+ if (methods && !methods.includes(method)) {
79
+ throw new Error(`This voip.ms account cannot ask for ${method}`)
80
+ }
81
+ let url = new URL(api)
82
+ for (
83
+ let [k, v] of Object.entries({
84
+ api_username: user,
85
+ api_password: key,
86
+ method,
87
+ ...params,
88
+ })
89
+ ) url.searchParams.set(k, v)
90
+ let response
91
+ try {
92
+ // The global fetch as it is at the call, not as it was when this was made.
93
+ response = await (given ?? globalThis.fetch)(url, {
94
+ headers: { accept: 'application/json' },
95
+ signal,
96
+ })
97
+ } catch {
98
+ signal?.throwIfAborted()
99
+ throw new Unsent(`voip.ms could not be reached for ${method}`)
100
+ }
101
+ if (response.status >= 500 || response.status == 429) {
102
+ await response.body?.cancel()
103
+ throw new Unsent(
104
+ `voip.ms is not answering right now (${response.status} to ${method})` +
105
+ (signal ? '' : '; yaks.app will try again'),
106
+ 30_000,
107
+ )
108
+ }
109
+ let said = await response.json().catch(() => {
110
+ signal?.throwIfAborted()
111
+ return {}
112
+ }) as Said
113
+ let status = String(said.status ?? '')
114
+ if (status == 'success') return said
115
+ if (VOIPMS.blocked[status]) {
116
+ throw new Blocked(VOIPMS.blocked[status], status)
117
+ }
118
+ if (VOIPMS.denied[status]) throw new Denied(VOIPMS.denied[status], status)
119
+ throw new Error(
120
+ `voip.ms answered ${status || response.status} to ${method}: ${
121
+ said.message ?? 'no reason given'
122
+ }`,
123
+ )
124
+ }
125
+
126
+ let CALL = 15_000
127
+
128
+ /** A voip.ms method not answered in time: as every slow answer, `Unsent`,
129
+ * asked again later, though one that acts may have acted all the same. */
130
+ export class TimedOut extends Unsent {
131
+ constructor(method: string) {
132
+ super(`voip.ms did not answer ${method} in time`)
133
+ }
134
+ }
135
+
136
+ /** The voip.ms methods that may be asked twice: those that read, and the
137
+ * settings that say the whole of what they set (`setSubAccount` is sent
138
+ * every field the account has). Any other may have acted
139
+ * however its first asking ended, so it is never asked again. */
140
+ export let REPEATABLE =
141
+ /^(get|search)[A-Z]|^(setSMS|setDIDRouting|setSubAccount)$/
142
+
143
+ /**
144
+ * Every voip.ms call, under one policy: each asking ends by `by` and within
145
+ * {@link CALL}; a {@link REPEATABLE} method that voip.ms is slow to answer,
146
+ * or answers with a 5xx, is asked once more, each asking with half the
147
+ * time. A slow answer is always `Unsent`, for the caller to ask again later:
148
+ * a second one of a repeatable method, and the timeout of any other, which is
149
+ * asked once ({@link TimedOut}). A caller can also ask for a single attempt.
150
+ */
151
+ export let bounded = (
152
+ request: ReturnType<typeof requester>,
153
+ time: Clock,
154
+ by = Infinity,
155
+ retry = true,
156
+ ): Call =>
157
+ async (method, params) => {
158
+ let once = async (until: number) => {
159
+ let ms = until - time.now()
160
+ if (ms <= 0) throw new TimedOut(method)
161
+ let stop = new AbortController()
162
+ let cancel = time.after(ms, () => stop.abort(new TimedOut(method)))
163
+ try {
164
+ return await request(method, params, stop.signal)
165
+ } finally {
166
+ cancel()
167
+ }
168
+ }
169
+ let end = () => Math.min(by, time.now() + CALL)
170
+ if (!retry || !REPEATABLE.test(method)) return await once(end())
171
+ let slow = (e: unknown) => e instanceof Unsent
172
+ let last = end()
173
+ try {
174
+ return await once(Math.min(last, time.now() + CALL / 2))
175
+ } catch (error) {
176
+ if (!slow(error)) throw error
177
+ return await once(last).catch((again) => {
178
+ if (!slow(again)) throw again
179
+ throw new Unsent(`voip.ms is slow to answer ${method} right now`)
180
+ })
181
+ }
182
+ }
package/routes.js ADDED
@@ -0,0 +1,7 @@
1
+ // The `@yaks/voipms/routes` facet: `GET /voipms/<key>`, where a number's SMS
2
+ // URL callback brings the texts that arrived, the `door.key` the config
3
+ // passes this plugin in its path, since voip.ms signs nothing.
4
+ import { routes as doors } from "@yaks/phone/plugin";
5
+ import { provider } from "./mod.js";
6
+ export let routes = doors('voipms', provider);
7
+ //# sourceMappingURL=routes.js.map
package/routes.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.js","sources":["./routes.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,wEAAwE;AACxE,+DAA+D;AAC/D,SAAsB,UAAU,KAAK,kCAAuC;AAC5E,SAAS,QAAQ,mBAAkB;AAEnC,OAAO,IAAI,SAAiB,MAAM,UAAU,UAAS"}
package/routes.ts ADDED
@@ -0,0 +1,7 @@
1
+ // The `@yaks/voipms/routes` facet: `GET /voipms/<key>`, where a number's SMS
2
+ // URL callback brings the texts that arrived, the `door.key` the config
3
+ // passes this plugin in its path, since voip.ms signs nothing.
4
+ import { type Routes, routes as doors } from '@yaks/phone/plugin'
5
+ import { provider } from './mod.js'
6
+
7
+ export let routes: Routes = doors('voipms', provider)
package/voice.js ADDED
@@ -0,0 +1,240 @@
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 { CallStopError } from "@yaks/phone";
4
+ import { Unsent } from "@yaks/host/senders";
5
+ import { TimedOut, VOIPMS } from "./request.js";
6
+ export let accountFor = (digits)=>`y${digits}`;
7
+ // voip.ms silently truncates the username suffix to twelve characters.
8
+ let seatPrefix = (digits)=>`y${Number(digits).toString(36).padStart(7, '0')}`;
9
+ let seatAccount = (digits, seat, legacy)=>seat == legacy ? accountFor(digits) : seatPrefix(digits) + (parseInt(seat.slice(0, 8), 16) % 36 ** 4).toString(36).padStart(4, '0');
10
+ export let callsAs = (digits, account)=>account.endsWith(`_${accountFor(digits)}`) || new RegExp(`_${seatPrefix(digits)}[0-9a-z]{4}$`).test(account);
11
+ let accountsOf = async (call, digits)=>((await call('getSubAccounts')).accounts ?? []).filter((a)=>callsAs(digits, String(a.account))).sort((a, b)=>Number(a.id) - Number(b.id));
12
+ let drop = (call, account)=>call('delSubAccount', {
13
+ id: String(account.id)
14
+ });
15
+ /** A purchase failed before the DID could be put to use. */ export let abandon = async (call, digits)=>{
16
+ await call('cancelDID', {
17
+ did: digits
18
+ });
19
+ for (let account of (await accountsOf(call, digits)))await drop(call, account);
20
+ };
21
+ export let heldDid = async (call, digits)=>{
22
+ let held = await call('getDIDsInfo', {
23
+ did: digits
24
+ }).then((said)=>said.dids ?? [], (error)=>{
25
+ if (/invalid_did|no_did/.test(String(error))) return [];
26
+ throw error;
27
+ });
28
+ return held.find((d)=>String(d.did) == digits);
29
+ };
30
+ let NOWHERE = '192.0.2.1';
31
+ let restriction = (out)=>({
32
+ enable_ip_restriction: out ? '0' : '1',
33
+ ip_restriction: out ? '' : NOWHERE
34
+ });
35
+ let described = (digits, seat)=>seat ? `+1${digits} ${seat}` : `+1${digits}`;
36
+ export let made = (call, digits, username, out, seat)=>call('createSubAccount', {
37
+ username,
38
+ protocol: '1',
39
+ description: described(digits, seat),
40
+ auth_type: '1',
41
+ password: `Y${crypto.randomUUID().replaceAll('-', '')}`,
42
+ device_type: '2',
43
+ callerid_number: digits,
44
+ lock_international: '1',
45
+ international_route: '1',
46
+ music_on_hold: 'default',
47
+ allowed_codecs: 'ulaw;g729;gsm',
48
+ dtmf_mode: 'AUTO',
49
+ nat: 'yes',
50
+ ...restriction(out)
51
+ });
52
+ let blocking = async (call, account, out)=>{
53
+ let shut = String(account.enable_ip_restriction) == '1' && account.ip_restriction == NOWHERE;
54
+ if (shut != out) return;
55
+ let { account: _, ...said } = account;
56
+ await call('setSubAccount', {
57
+ ...Object.fromEntries(Object.entries(said).map(([k, v])=>[
58
+ k,
59
+ String(v ?? '')
60
+ ])),
61
+ ...restriction(out)
62
+ });
63
+ };
64
+ // Every step runs, and any failure fails the whole once all have ended.
65
+ let settled = async (steps)=>{
66
+ let ends = await Promise.allSettled(steps);
67
+ let errors = ends.flatMap((r)=>r.status == 'rejected' ? [
68
+ r.reason
69
+ ] : []);
70
+ if (errors.length == 1) throw errors[0];
71
+ if (errors.length) throw new AggregateError(errors, 'voip.ms refused a step');
72
+ };
73
+ let twice = (step)=>step().catch(()=>step());
74
+ let failed = (step)=>step.then(()=>[], (error)=>error instanceof AggregateError ? error.errors : [
75
+ error
76
+ ]);
77
+ let shut = async (call, digits, restrict)=>{
78
+ // Stop calls out first, but try incoming even when restricting fails.
79
+ let out = await failed(twice(restrict));
80
+ let incoming = await failed(heldDid(call, digits).then(async (did)=>{
81
+ if (did && did.routing != 'sys:hangup') {
82
+ await call('setDIDRouting', {
83
+ did: digits,
84
+ routing: 'sys:hangup'
85
+ });
86
+ }
87
+ }));
88
+ if (out.length || incoming.length) {
89
+ throw new CallStopError({
90
+ in: !incoming.length,
91
+ out: !out.length
92
+ }, [
93
+ ...out,
94
+ ...incoming
95
+ ]);
96
+ }
97
+ };
98
+ let groupOf = async (call, digits)=>{
99
+ let groups = await call('getRingGroups').catch((error)=>{
100
+ if (/no_ringgroup/.test(String(error))) return {
101
+ ring_groups: []
102
+ };
103
+ throw error;
104
+ });
105
+ return (groups.ring_groups ?? []).find((g)=>g.name == accountFor(digits));
106
+ };
107
+ let route = async (call, digits, accounts)=>{
108
+ let did = await heldDid(call, digits);
109
+ let routedToGroup = String(did?.routing ?? '').startsWith('grp:');
110
+ let group = accounts.length > 1 ? await groupOf(call, digits) : undefined;
111
+ let members = accounts.map((a)=>`account:${a.account},25,0`).sort().join(';');
112
+ let routing = accounts.length ? `account:${accounts[0].account}` : 'sys:hangup';
113
+ if (accounts.length > 1) {
114
+ let id = group?.ring_group;
115
+ if (!group || group.members != members) {
116
+ let set = await call('setRingGroup', {
117
+ name: accountFor(digits),
118
+ members,
119
+ ...id ? {
120
+ ring_group: String(id)
121
+ } : {}
122
+ });
123
+ id = set.ring_group ?? id;
124
+ }
125
+ if (!id) throw new Error('voip.ms did not return the ring group ID');
126
+ routing = `grp:${id}`;
127
+ }
128
+ if (did && did.routing != routing) {
129
+ await call('setDIDRouting', {
130
+ did: digits,
131
+ routing
132
+ });
133
+ }
134
+ if (routedToGroup && accounts.length < 2) {
135
+ let old = await groupOf(call, digits);
136
+ if (old) await call('delRingGroup', {
137
+ ringgroup: String(old.ring_group)
138
+ });
139
+ }
140
+ };
141
+ let belongs = (account, digits, seat, legacy)=>account.username == seatAccount(digits, seat, legacy) && (seat == legacy || account.description == described(digits, seat));
142
+ let taken = async (call, digits, seat, voice, submit)=>{
143
+ let username = seatAccount(digits, seat, voice.legacy);
144
+ let find = async ()=>(await accountsOf(call, digits)).find((a)=>belongs(a, digits, seat, voice.legacy));
145
+ let account = await find();
146
+ if (account) return account;
147
+ if (submit && !await submit(seat)) return undefined;
148
+ await made(call, digits, username, voice.out, seat == voice.legacy ? undefined : seat).catch(async (error)=>{
149
+ if (await find()) return;
150
+ if (error instanceof TimedOut) {
151
+ throw new Unsent('voip.ms has yet to confirm the SIP account');
152
+ }
153
+ throw error;
154
+ });
155
+ account = await find();
156
+ if (!account) throw new Error('voip.ms did not return the new SIP account');
157
+ return account;
158
+ };
159
+ export let allow = async (call, digits, voice, submit)=>{
160
+ let requested = new Set([
161
+ voice.legacy,
162
+ ...voice.requested ?? []
163
+ ]);
164
+ let seats = voice.seats.filter((seat)=>requested.has(seat) && !voice.revoked?.includes(seat));
165
+ let keep = async ()=>{
166
+ let kept = new Map();
167
+ let gone = [];
168
+ for (let account of (await accountsOf(call, digits))){
169
+ let username = String(account.account);
170
+ let mine = seats.some((seat)=>belongs(account, digits, seat, voice.legacy));
171
+ if (mine && !kept.has(username)) kept.set(username, account);
172
+ else gone.push(account);
173
+ }
174
+ let out = voice.in && voice.out;
175
+ await settled([
176
+ ...kept.values()
177
+ ].map((a)=>blocking(call, a, out)));
178
+ await settled(gone.map((account)=>drop(call, account)));
179
+ return kept;
180
+ };
181
+ if (!voice.in) {
182
+ // Trash restricts every sign-in. Only a separate seat revocation drops one.
183
+ await shut(call, digits, voice.revoked?.length ? keep : async ()=>settled((await accountsOf(call, digits)).map((a)=>blocking(call, a, false))));
184
+ return;
185
+ }
186
+ let kept = await keep();
187
+ for (let seat of seats){
188
+ if (![
189
+ ...kept.values()
190
+ ].some((a)=>belongs(a, digits, seat, voice.legacy))) {
191
+ let account = await taken(call, digits, seat, voice, submit);
192
+ if (account) kept.set(String(account.account), account);
193
+ }
194
+ }
195
+ await route(call, digits, [
196
+ ...kept.values()
197
+ ]);
198
+ };
199
+ export let release = async (call, digits)=>{
200
+ await call('cancelDID', {
201
+ did: digits
202
+ }).catch(async (error)=>{
203
+ if (await heldDid(call, digits)) throw error;
204
+ });
205
+ };
206
+ export let cleanup = async (call, digits)=>{
207
+ await settled([
208
+ accountsOf(call, digits).then((accounts)=>settled(accounts.map((account)=>drop(call, account)))),
209
+ groupOf(call, digits).then(async (group)=>{
210
+ if (group) {
211
+ await call('delRingGroup', {
212
+ ringgroup: String(group.ring_group)
213
+ });
214
+ }
215
+ })
216
+ ]);
217
+ };
218
+ export let login = async (call, digits, seat, voice, submit)=>{
219
+ if (!voice.in || !voice.seats.includes(seat)) {
220
+ throw new Error('This seat cannot sign a softphone in');
221
+ }
222
+ let account = await taken(call, digits, seat, voice, submit);
223
+ if (!account) throw new Unsent('voip.ms has yet to confirm the SIP account');
224
+ if (!account.password) {
225
+ throw new Error('voip.ms did not return the softphone sign-in');
226
+ }
227
+ await allow(call, digits, voice, submit);
228
+ let [server] = (await call('getServersInfo', {
229
+ server_pop: VOIPMS.pop
230
+ })).servers ?? [];
231
+ if (!server?.server_hostname) {
232
+ throw new Error('voip.ms did not return the SIP server');
233
+ }
234
+ return {
235
+ server: String(server.server_hostname),
236
+ user: String(account.account),
237
+ password: String(account.password)
238
+ };
239
+ };
240
+ //# sourceMappingURL=voice.js.map
package/voice.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"voice.js","sources":["./voice.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,4EAA4E;AAC5E,SACE,aAAa,2BAIgB;AAC/B,SAAS,MAAM,kCAAuC;AACtD,SAAiC,QAAQ,EAAE,MAAM,uBAAsB;AAIvE,OAAO,IAAI,aAAa,CAAC,SAAmB,CAAC,CAAC,EAAE,QAAQ,CAAA;AAExD,uEAAuE;AACvE,IAAI,aAAa,CAAC,SAChB,CAAC,CAAC,EAAE,OAAO,QAAQ,QAAQ,CAAC,IAAI,QAAQ,CAAC,GAAG,MAAM;AAEpD,IAAI,cAAc,CAAC,QAAgB,MAAc,SAC/C,QAAQ,SAAS,WAAW,UAAU,WAAW,UAC/C,CAAC,SAAS,KAAK,KAAK,CAAC,GAAG,IAAI,MAAO,MAAM,CAAE,EAAE,QAAQ,CAAC,IAAI,QAAQ,CAAC,GAAG;AAE1E,OAAO,IAAI,UAAU,CAAC,QAAgB,UACpC,QAAQ,QAAQ,CAAC,CAAC,CAAC,EAAE,WAAW,SAAS,KACzC,IAAI,OAAO,CAAC,CAAC,EAAE,WAAW,QAAQ,YAAY,CAAC,EAAE,IAAI,CAAC,SAAQ;AAEhE,IAAI,aAAa,OAAO,MAAY,SAClC,AAAC,CAAC,CAAC,MA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