Commit 8aae278 for jssip.net
commit 8aae2780b526441e64e39ded0941f7bb2cad9ea9
Author: José Luis Millán <jmillan@aliax.net>
Date: Thu Dec 3 14:00:27 2026 +0100
TS Subscriber
diff --git a/src/Subscriber.d.ts b/src/Subscriber.d.ts
deleted file mode 100644
index a2edc45..0000000
--- a/src/Subscriber.d.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { EventEmitter } from 'events';
-import { IncomingRequest, IncomingResponse } from './SIPMessage';
-import { UA } from './UA';
-
-declare enum SubscriberTerminatedCode {
- SUBSCRIBE_RESPONSE_TIMEOUT = 0,
- SUBSCRIBE_TRANSPORT_ERROR = 1,
- SUBSCRIBE_NON_OK_RESPONSE = 2,
- SUBSCRIBE_WRONG_OK_RESPONSE = 3,
- SUBSCRIBE_AUTHENTICATION_FAILED = 4,
- UNSUBSCRIBE_TIMEOUT = 5,
- FINAL_NOTIFY_RECEIVED = 6,
- WRONG_NOTIFY_RECEIVED = 7,
- UA_STOPPED = 8,
-}
-
-export interface MessageEventMap {
- pending: [];
- accepted: [];
- active: [];
- terminated: [
- terminationCode: SubscriberTerminatedCode,
- reason: string | undefined,
- retryAfter: number | undefined,
- response: IncomingResponse | undefined,
- ];
- notify: [
- isFinal: boolean,
- request: IncomingRequest,
- body: string | undefined,
- contentType: string | undefined,
- ];
-}
-
-interface SubscriberOptions {
- expires?: number;
- contentType?: string;
- allowEvents?: string;
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- params?: Record<string, any>;
- extraHeaders?: string[];
-}
-
-export class Subscriber extends EventEmitter<MessageEventMap> {
- constructor(
- ua: UA,
- target: string,
- eventName: string,
- accept: string,
- options?: SubscriberOptions
- );
- subscribe(body?: string): void;
- terminate(body?: string): void;
- get state(): string;
- get id(): string;
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- set data(_data: any);
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- get data(): any;
- static get C(): typeof SubscriberTerminatedCode;
- get C(): typeof SubscriberTerminatedCode;
-}
diff --git a/src/Subscriber.js b/src/Subscriber.js
deleted file mode 100644
index 2166db1..0000000
--- a/src/Subscriber.js
+++ /dev/null
@@ -1,707 +0,0 @@
-const EventEmitter = require('events').EventEmitter;
-const Exceptions = require('./Exceptions');
-const { Logger } = require('./Logger');
-const JsSIP_C = require('./Constants');
-const Utils = require('./Utils');
-const Grammar = require('./Grammar');
-const SIPMessage = require('./SIPMessage');
-const { RequestSender } = require('./RequestSender');
-const { Dialog } = require('./Dialog');
-
-const logger = new Logger('Subscriber');
-
-/**
- * Termination codes.
- */
-const C = {
- // Termination codes.
- SUBSCRIBE_RESPONSE_TIMEOUT: 0,
- SUBSCRIBE_TRANSPORT_ERROR: 1,
- SUBSCRIBE_NON_OK_RESPONSE: 2,
- SUBSCRIBE_WRONG_OK_RESPONSE: 3,
- SUBSCRIBE_AUTHENTICATION_FAILED: 4,
- UNSUBSCRIBE_TIMEOUT: 5,
- FINAL_NOTIFY_RECEIVED: 6,
- WRONG_NOTIFY_RECEIVED: 7,
- UA_STOPPED: 8,
-
- // Subscriber states.
- STATE_PENDING: 0,
- STATE_ACTIVE: 1,
- STATE_TERMINATED: 2,
- STATE_INIT: 3,
- STATE_WAITING_NOTIFY: 4,
-
- // RFC 6665 3.1.1, default expires value.
- DEFAULT_EXPIRES_SEC: 900,
-
- // How long to wait for the final NOTIFY once the un-SUBSCRIBE is accepted.
- FINAL_NOTIFY_TIMEOUT_SEC: 32,
-};
-
-/**
- * RFC 6665 Subscriber implementation.
- */
-module.exports = class Subscriber extends EventEmitter {
- /**
- * Expose C object.
- */
- static get C() {
- return C;
- }
-
- /**
- * @param {UA} ua - reference to JsSIP.UA
- * @param {string} target
- * @param {string} eventName - Event header value. May end with optional ;id=xxx
- * @param {string} accept - Accept header value.
- *
- * @param {SubscriberOption} options - optional parameters.
- * @param {number} expires - Expires header value. Default is 900.
- * @param {string} contentType - Content-Type header value. Used for SUBSCRIBE with body
- * @param {string} allowEvents - Allow-Events header value.
- * @param {RequestParams} params - Will have priority over ua.configuration.
- * If set please define: to_uri, to_display_name, from_uri, from_display_name
- * @param {Array<string>} extraHeaders - Additional SIP headers.
- */
- constructor(
- ua,
- target,
- eventName,
- accept,
- { expires, contentType, allowEvents, params, extraHeaders } = {}
- ) {
- logger.debug('new');
-
- super();
-
- // Check that arguments are defined.
- if (!target) {
- throw new TypeError('Not enough arguments: Missing target');
- }
-
- if (!eventName) {
- throw new TypeError('Not enough arguments: Missing eventName');
- }
-
- if (!accept) {
- throw new TypeError('Not enough arguments: Missing accept');
- }
-
- const event_header = Grammar.parse(eventName, 'Event');
-
- if (event_header === -1) {
- throw new TypeError('Missing Event header field');
- }
-
- this._ua = ua;
- this._target = this._ua.normalizeTarget(target);
-
- if (!this._target) {
- throw new TypeError(`Invalid target: ${target}`);
- }
-
- if (!Utils.isDecimal(expires) || expires <= 0) {
- expires = C.DEFAULT_EXPIRES_SEC;
- }
-
- this._expires = expires;
-
- // Used to subscribe with body.
- this._content_type = contentType;
-
- // Set initial subscribe parameters.
- this._params = Utils.cloneObject(params);
-
- if (!this._params.from_uri) {
- this._params.from_uri = this._ua.configuration.uri;
- }
-
- this._params.from_tag = Utils.newTag();
- this._params.to_tag = null;
- this._params.call_id = Utils.createRandomToken(20);
-
- // Create subscribe cseq if not defined custom cseq.
- if (this._params.cseq === undefined) {
- this._params.cseq = Math.floor(Math.random() * 10000 + 1);
- }
-
- // Subscriber state.
- this._state = C.STATE_INIT;
-
- // Dialog.
- this._dialog = null;
-
- // Whether the 2xx response to the initial SUBSCRIBE was already processed.
- this._accepted = false;
-
- // CSeq of the initial SUBSCRIBE. The dialog created by an early NOTIFY
- // must continue this sequence (RFC 6665 4.1.2.4).
- this._initial_cseq = null;
-
- // To refresh subscription.
- this._expires_timer = null;
- this._expires_timestamp = null;
-
- // To prevent duplicate terminated call.
- this._terminated = false;
-
- this._event_name = event_header.event;
- this._event_id = event_header.params && event_header.params.id;
-
- let eventValue = this._event_name;
-
- if (this._event_id) {
- eventValue += `;id=${this._event_id}`;
- }
-
- this._headers = Utils.cloneArray(extraHeaders);
- this._headers = this._headers.concat([
- `Event: ${eventValue}`,
- `Expires: ${this._expires}`,
- `Accept: ${accept}`,
- ]);
-
- if (!this._headers.find(header => header.startsWith('Contact'))) {
- const contact = `Contact: ${this._ua._contact.toString()}`;
-
- this._headers.push(contact);
- }
-
- if (allowEvents) {
- this._headers.push(`Allow-Events: ${allowEvents}`);
- }
-
- // To enqueue SUBSCRIBE requests created before the reception of the initial subscribe OK response.
- this._queue = [];
-
- // Custom session empty object for high level use.
- this._data = {};
- }
-
- // Expose Subscriber constants as a property of the Subscriber instance.
- get C() {
- return C;
- }
-
- /**
- * Get dialog state.
- */
- get state() {
- return this._state;
- }
-
- /**
- * Get dialog id.
- */
- get id() {
- return this._dialog ? this._dialog.id : null;
- }
-
- get data() {
- return this._data;
- }
-
- set data(_data) {
- this._data = _data;
- }
-
- onRequestTimeout() {
- this._terminateDialog(C.SUBSCRIBE_RESPONSE_TIMEOUT);
- }
-
- onTransportError() {
- this._terminateDialog(C.SUBSCRIBE_TRANSPORT_ERROR);
- }
-
- /**
- * Whether this subscriber is still waiting for the NOTIFY that creates the
- * subscription dialog and the given NOTIFY belongs to its initial SUBSCRIBE.
- *
- * RFC 6665 4.1.2.4: the first NOTIFY may arrive before the 2xx response to
- * the initial SUBSCRIBE, in which case it is the one creating the dialog.
- *
- * @param {string} call_id - Call-ID of the received NOTIFY.
- * @param {string} to_tag - To tag of the received NOTIFY.
- */
- matchEarlyNotify(call_id, to_tag) {
- return (
- this._dialog === null &&
- this._state === C.STATE_WAITING_NOTIFY &&
- call_id === this._params.call_id &&
- to_tag === this._params.from_tag
- );
- }
-
- /**
- * UA callback. Process the NOTIFY that arrived before the 2xx response to
- * the initial SUBSCRIBE. It creates the subscription dialog (RFC 6665
- * 4.1.2.4).
- */
- receiveEarlyNotify(request) {
- let dialog;
-
- try {
- dialog = Dialog.Create(this, request, 'UAS');
- } catch {
- // NOTIFY without Contact.
- request.reply(400);
-
- return;
- }
-
- // The dialog is created by an incoming request, so it has no local
- // sequence number yet. Continue the sequence of the initial SUBSCRIBE,
- // otherwise the refresh would use a random (possibly lower) CSeq.
- dialog.local_seqnum = this._initial_cseq;
-
- this._dialog = dialog;
-
- logger.debug('dialog created by the NOTIFY preceding the SUBSCRIBE 2xx');
-
- dialog.receiveRequest(request);
- }
-
- /**
- * Dialog callback.
- */
- receiveRequest(request) {
- if (request.method !== JsSIP_C.NOTIFY) {
- logger.warn('received non-NOTIFY request');
- request.reply(405);
-
- return;
- }
-
- // RFC 6665 8.2.1. Check if event header matches.
- const event_header = request.parseHeader('Event');
-
- if (!event_header) {
- logger.warn('missing Event header');
- request.reply(400);
- this._terminateDialog(C.WRONG_NOTIFY_RECEIVED);
-
- return;
- }
-
- const event_name = event_header.event;
- const event_id = event_header.params && event_header.params.id;
-
- if (event_name !== this._event_name || event_id !== this._event_id) {
- logger.warn('Event header does not match the one in SUBSCRIBE request');
- request.reply(489);
- this._terminateDialog(C.WRONG_NOTIFY_RECEIVED);
-
- return;
- }
-
- // Process Subscription-State header.
- const subs_state = request.parseHeader('subscription-state');
-
- if (!subs_state) {
- logger.warn('missing Subscription-State header');
- request.reply(400);
- this._terminateDialog(C.WRONG_NOTIFY_RECEIVED);
-
- return;
- }
-
- const new_state = this._parseSubscriptionState(subs_state.state);
-
- if (new_state === undefined) {
- logger.warn(
- `Invalid Subscription-State header value: ${subs_state.state}`
- );
- request.reply(400);
- this._terminateDialog(C.WRONG_NOTIFY_RECEIVED);
-
- return;
- }
- request.reply(200);
-
- const prev_state = this._state;
-
- if (prev_state !== C.STATE_TERMINATED && new_state !== C.STATE_TERMINATED) {
- this._state = new_state;
-
- if (subs_state.expires !== undefined) {
- const expires = subs_state.expires;
- const expires_timestamp = new Date().getTime() + expires * 1000;
- const max_time_deviation = 2000;
-
- // Expiration time is shorter and the difference is not too small.
- if (this._expires_timestamp - expires_timestamp > max_time_deviation) {
- logger.debug('update sending re-SUBSCRIBE time');
-
- this._scheduleSubscribe(expires);
- }
- }
- }
-
- if (prev_state !== C.STATE_PENDING && new_state === C.STATE_PENDING) {
- logger.debug('emit "pending"');
-
- this.emit('pending');
- } else if (prev_state !== C.STATE_ACTIVE && new_state === C.STATE_ACTIVE) {
- logger.debug('emit "active"');
-
- this.emit('active');
- }
-
- const body = request.body;
-
- // Check if the notify is final.
- const is_final = new_state === C.STATE_TERMINATED;
-
- // Notify event fired only for notify with body.
- if (body) {
- const content_type = request.getHeader('content-type');
-
- logger.debug('emit "notify"');
-
- this.emit('notify', is_final, request, body, content_type);
- }
-
- if (is_final) {
- const reason = subs_state.reason;
- let retry_after = undefined;
-
- if (subs_state.params && subs_state.params['retry-after'] !== undefined) {
- retry_after = parseInt(subs_state.params['retry-after']);
- }
-
- this._terminateDialog(C.FINAL_NOTIFY_RECEIVED, reason, retry_after);
- }
- }
-
- /**
- * User API
- */
-
- /**
- * Send the initial (non-fetch) and subsequent subscribe.
- * @param {string} body - subscribe request body.
- */
- subscribe(body = null) {
- logger.debug('subscribe()');
-
- if (this._state === C.STATE_INIT) {
- this._sendInitialSubscribe(body, this._headers);
- } else {
- this._sendSubsequentSubscribe(body, this._headers);
- }
- }
-
- /**
- * terminate.
- * Send un-subscribe or fetch-subscribe (with Expires: 0).
- * @param {string} body - un-subscribe request body
- */
- terminate(body = null) {
- logger.debug('terminate()');
-
- if (this._state === C.STATE_INIT) {
- throw new Exceptions.InvalidStateError(this._state);
- }
-
- // Prevent duplication un-subscribe sending.
- if (this._terminated) {
- return;
- }
- this._terminated = true;
-
- // No refresh from now on.
- clearTimeout(this._expires_timer);
- this._expires_timer = null;
-
- // Set header Expires: 0.
- const headers = this._headers.map(header => {
- return header.startsWith('Expires') ? 'Expires: 0' : header;
- });
-
- this._sendSubsequentSubscribe(body, headers);
- }
-
- /**
- * Private API.
- */
- _terminateDialog(
- terminationCode,
- reason = undefined,
- retryAfter = undefined,
- response = undefined
- ) {
- // To prevent duplicate emit terminated event.
- if (this._state === C.STATE_TERMINATED) {
- return;
- }
-
- this._state = C.STATE_TERMINATED;
-
- // Clear timers.
- clearTimeout(this._expires_timer);
-
- if (this._dialog) {
- this._dialog.terminate();
- this._dialog = null;
- }
-
- this._ua.destroySubscriber(this);
-
- logger.debug(`emit "terminated" code=${terminationCode}`);
-
- this.emit('terminated', terminationCode, reason, retryAfter, response);
- }
-
- _sendInitialSubscribe(body, headers) {
- if (body) {
- if (!this._content_type) {
- throw new TypeError('content_type is undefined');
- }
-
- headers = Utils.cloneArray(headers);
- headers.push(`Content-Type: ${this._content_type}`);
- }
-
- this._state = C.STATE_WAITING_NOTIFY;
-
- this._ua.newSubscriber(this);
-
- const request = new SIPMessage.OutgoingRequest(
- JsSIP_C.SUBSCRIBE,
- this._target,
- this._ua,
- this._params,
- headers,
- body
- );
-
- this._initial_cseq = request.cseq;
-
- const request_sender = new RequestSender(this._ua, request, {
- onRequestTimeout: () => {
- this.onRequestTimeout();
- },
- onTransportError: () => {
- this.onTransportError();
- },
- onAuthenticated: authenticated_request => {
- // The SUBSCRIBE is re-sent with an increased CSeq.
- this._initial_cseq = authenticated_request.cseq;
-
- if (this._dialog) {
- this._dialog.local_seqnum = this._initial_cseq;
- }
- },
- onReceiveResponse: response => {
- this._receiveSubscribeResponse(response);
- },
- });
-
- request_sender.send();
- }
-
- _sendSubsequentSubscribe(body, headers) {
- if (this._state === C.STATE_TERMINATED) {
- return;
- }
-
- if (!this._dialog) {
- logger.debug('enqueue subscribe');
-
- this._queue.push({ body, headers: Utils.cloneArray(headers) });
-
- return;
- }
-
- if (body) {
- if (!this._content_type) {
- throw new TypeError('content_type is undefined');
- }
-
- headers = Utils.cloneArray(headers);
- headers.push(`Content-Type: ${this._content_type}`);
- }
-
- this._dialog.sendRequest(JsSIP_C.SUBSCRIBE, {
- body,
- extraHeaders: headers,
- eventHandlers: {
- onRequestTimeout: () => {
- this.onRequestTimeout();
- },
- onTransportError: () => {
- this.onTransportError();
- },
- onSuccessResponse: response => {
- this._receiveSubscribeResponse(response);
- },
- onErrorResponse: response => {
- this._receiveSubscribeResponse(response);
- },
- onDialogError: response => {
- this._receiveSubscribeResponse(response);
- },
- },
- });
- }
-
- _receiveSubscribeResponse(response) {
- if (this._state === C.STATE_TERMINATED) {
- return;
- }
-
- if (response.status_code >= 200 && response.status_code < 300) {
- // Create dialog, unless an early NOTIFY already created it.
- if (this._dialog === null) {
- let dialog;
-
- try {
- dialog = Dialog.Create(this, response, 'UAC');
- } catch {
- // OK response without Contact.
- this._terminateDialog(
- C.SUBSCRIBE_WRONG_OK_RESPONSE,
- undefined,
- undefined,
- response
- );
-
- return;
- }
-
- this._dialog = dialog;
- }
-
- // The initial SUBSCRIBE is accepted. Refreshes land here too.
- if (!this._accepted) {
- this._accepted = true;
-
- logger.debug('emit "accepted"');
-
- this.emit('accepted');
-
- // Subsequent subscribes saved in the queue until dialog created.
- const queue = this._queue;
-
- this._queue = [];
-
- for (const subscribe of queue) {
- logger.debug('dequeue subscribe');
-
- this._sendSubsequentSubscribe(subscribe.body, subscribe.headers);
- }
- }
-
- // Un-SUBSCRIBE accepted: no refresh, only the final NOTIFY to wait for
- // (RFC 6665 4.1.2.3).
- if (this._terminated) {
- // A stopped UA drops every incoming request, the final NOTIFY too.
- if (this._ua.status === this._ua.C.STATUS_USER_CLOSED) {
- this._terminateDialog(C.UA_STOPPED, undefined, undefined, response);
- } else {
- this._scheduleFinalNotifyTimeout();
- }
-
- return;
- }
-
- // Check expires value.
- const expires_value = response.getHeader('expires');
-
- let expires = parseInt(expires_value);
-
- if (!Utils.isDecimal(expires) || expires <= 0) {
- logger.warn(
- `response without Expires header, setting a default value of ${C.DEFAULT_EXPIRES_SEC}`
- );
-
- // RFC 6665 3.1.1 subscribe OK response must contain Expires header.
- // Use workaround expires value.
- expires = C.DEFAULT_EXPIRES_SEC;
- }
-
- if (expires > 0) {
- this._scheduleSubscribe(expires);
- }
- } else if (response.status_code === 401 || response.status_code === 407) {
- this._terminateDialog(
- C.SUBSCRIBE_AUTHENTICATION_FAILED,
- undefined,
- undefined,
- response
- );
- } else if (response.status_code >= 300) {
- this._terminateDialog(
- C.SUBSCRIBE_NON_OK_RESPONSE,
- undefined,
- undefined,
- response
- );
- }
- }
-
- _scheduleSubscribe(expires) {
- // If the expires time is less than 140 seconds we do not support Chrome intensive timer throttling mode.
- // In this case, the re-subcribe is sent 5 seconds before the subscription expiration.
- //
- // When Chrome is in intensive timer throttling mode, in the worst case,
- // the timer will be 60 seconds late.
- // We give the server 10 seconds to make sure it will execute the command even if it is heavily loaded.
- // As a result, we order the time no later than 70 seconds before the subscription expiration.
- // Resulting time calculated as half time interval + (half interval - 70) * random.
- //
- // E.g. expires is 140, re-subscribe will be ordered to send in 70 seconds.
- // expires is 600, re-subscribe will be ordered to send in 300 + (0 .. 230) seconds.
-
- const timeout =
- expires >= 140
- ? (expires * 1000) / 2 +
- Math.floor((expires / 2 - 70) * 1000 * Math.random())
- : expires * 1000 - 5000;
-
- this._expires_timestamp = new Date().getTime() + expires * 1000;
-
- logger.debug(
- `next SUBSCRIBE will be sent in ${Math.floor(timeout / 1000)} sec`
- );
-
- clearTimeout(this._expires_timer);
- this._expires_timer = setTimeout(() => {
- this._expires_timer = null;
- this._sendSubsequentSubscribe(null, this._headers);
- }, timeout);
- }
-
- _scheduleFinalNotifyTimeout() {
- clearTimeout(this._expires_timer);
- this._expires_timer = setTimeout(() => {
- this._expires_timer = null;
- logger.debug('no final NOTIFY received after un-SUBSCRIBE');
- this._terminateDialog(C.UNSUBSCRIBE_TIMEOUT);
- }, C.FINAL_NOTIFY_TIMEOUT_SEC * 1000);
- }
-
- _parseSubscriptionState(strState) {
- switch (strState) {
- case 'pending': {
- return C.STATE_PENDING;
- }
- case 'active': {
- return C.STATE_ACTIVE;
- }
- case 'terminated': {
- return C.STATE_TERMINATED;
- }
- case 'init': {
- return C.STATE_INIT;
- }
- case 'notify_wait': {
- return C.STATE_WAITING_NOTIFY;
- }
- default: {
- return undefined;
- }
- }
- }
-};
diff --git a/src/Subscriber.ts b/src/Subscriber.ts
new file mode 100644
index 0000000..14b73a5
--- /dev/null
+++ b/src/Subscriber.ts
@@ -0,0 +1,939 @@
+import { EventEmitter } from 'events';
+
+import * as JsSIP_C from './Constants';
+import { Dialog } from './Dialog';
+import type { DialogId, DialogOwner, DialogUA } from './Dialog';
+import { InvalidStateError } from './Exceptions';
+import * as Grammar from './Grammar';
+import { Logger } from './Logger';
+import { RequestSender } from './RequestSender';
+import * as SIPMessage from './SIPMessage';
+import type {
+ IncomingRequest,
+ IncomingResponse,
+ OutgoingRequestParams,
+} from './SIPMessage';
+import * as Utils from './Utils';
+import URI = require('./URI');
+
+const logger = new Logger('Subscriber');
+
+/**
+ * Why the subscription ended, as reported by the `terminated` event.
+ */
+export enum TerminationCode {
+ SUBSCRIBE_RESPONSE_TIMEOUT = 0,
+ SUBSCRIBE_TRANSPORT_ERROR = 1,
+ SUBSCRIBE_NON_OK_RESPONSE = 2,
+ SUBSCRIBE_WRONG_OK_RESPONSE = 3,
+ SUBSCRIBE_AUTHENTICATION_FAILED = 4,
+ UNSUBSCRIBE_TIMEOUT = 5,
+ FINAL_NOTIFY_RECEIVED = 6,
+ WRONG_NOTIFY_RECEIVED = 7,
+ UA_STOPPED = 8,
+}
+
+/**
+ * State of the subscription.
+ *
+ * @remarks
+ * - `INIT` until `subscribe()` sends the initial SUBSCRIBE, then
+ * `WAITING_NOTIFY` until the first NOTIFY says whether it is `PENDING` or
+ * `ACTIVE`.
+ */
+export enum State {
+ PENDING = 0,
+ ACTIVE = 1,
+ TERMINATED = 2,
+ INIT = 3,
+ WAITING_NOTIFY = 4,
+}
+
+/**
+ * The constants the subscriber exposes, both as a static and as an instance
+ * member.
+ *
+ * @remarks
+ * - {@link TerminationCode} and {@link State} hold the same values under
+ * shorter names, and are what the subscriber itself is typed with.
+ */
+export const C = {
+ // Termination codes.
+ SUBSCRIBE_RESPONSE_TIMEOUT: TerminationCode.SUBSCRIBE_RESPONSE_TIMEOUT,
+ SUBSCRIBE_TRANSPORT_ERROR: TerminationCode.SUBSCRIBE_TRANSPORT_ERROR,
+ SUBSCRIBE_NON_OK_RESPONSE: TerminationCode.SUBSCRIBE_NON_OK_RESPONSE,
+ SUBSCRIBE_WRONG_OK_RESPONSE: TerminationCode.SUBSCRIBE_WRONG_OK_RESPONSE,
+ SUBSCRIBE_AUTHENTICATION_FAILED:
+ TerminationCode.SUBSCRIBE_AUTHENTICATION_FAILED,
+ UNSUBSCRIBE_TIMEOUT: TerminationCode.UNSUBSCRIBE_TIMEOUT,
+ FINAL_NOTIFY_RECEIVED: TerminationCode.FINAL_NOTIFY_RECEIVED,
+ WRONG_NOTIFY_RECEIVED: TerminationCode.WRONG_NOTIFY_RECEIVED,
+ UA_STOPPED: TerminationCode.UA_STOPPED,
+
+ // Subscriber states.
+ STATE_PENDING: State.PENDING,
+ STATE_ACTIVE: State.ACTIVE,
+ STATE_TERMINATED: State.TERMINATED,
+ STATE_INIT: State.INIT,
+ STATE_WAITING_NOTIFY: State.WAITING_NOTIFY,
+
+ // RFC 6665 3.1.1, default expires value.
+ DEFAULT_EXPIRES_SEC: 900,
+
+ // How long to wait for the final NOTIFY once the un-SUBSCRIBE is accepted.
+ FINAL_NOTIFY_TIMEOUT_SEC: 32,
+};
+
+/**
+ * The events a {@link Subscriber} emits.
+ */
+export type SubscriberEventMap = {
+ /**
+ * The notifier has not accepted the subscription yet.
+ */
+ pending: [];
+ /**
+ * The initial SUBSCRIBE got a 2xx response.
+ */
+ accepted: [];
+ /**
+ * The notifier has accepted the subscription.
+ */
+ active: [];
+ /**
+ * The subscription ended, for whatever reason. `reason`, `retryAfter`
+ * and `response` are only set by the terminations that have them.
+ */
+ terminated: [
+ terminationCode: TerminationCode,
+ reason: string | undefined,
+ retryAfter: number | undefined,
+ response: IncomingResponse | undefined,
+ ];
+ /**
+ * A NOTIFY carrying a body arrived. `isFinal` marks the last one of the
+ * subscription.
+ */
+ notify: [
+ isFinal: boolean,
+ request: IncomingRequest,
+ body: string,
+ contentType: string | undefined,
+ ];
+};
+
+/**
+ * Options accepted by the constructor.
+ */
+export type SubscriberOptions = {
+ /**
+ * How long (in seconds) to ask the subscription to last.
+ *
+ * @defaultValue {@link C.DEFAULT_EXPIRES_SEC}
+ */
+ expires?: number;
+ /**
+ * Value of the Content-Type header field, needed only to subscribe with
+ * a body.
+ */
+ contentType?: string;
+ /**
+ * Value of the Allow-Events header field.
+ */
+ allowEvents?: string;
+ /**
+ * Parameters of the initial SUBSCRIBE, which take priority over the ones
+ * the UA is configured with.
+ *
+ * @remarks
+ * - `from_tag`, `to_tag` and `call_id` are always the subscriber's own.
+ */
+ params?: OutgoingRequestParams | null;
+ /**
+ * Whole `Name: value` header field lines to add to every SUBSCRIBE. A
+ * `Contact` among them replaces the one the UA would use.
+ */
+ extraHeaders?: string[] | null;
+};
+
+/**
+ * The `UA` surface a subscriber depends on.
+ *
+ * TODO: Replace with `import type { UA } from './UA'` once `UA` is ported to
+ * TypeScript.
+ */
+export interface SubscriberUA extends DialogUA {
+ readonly contact: DialogUA['contact'] & {
+ toString(): string;
+ };
+
+ normalizeTarget(target: string | URI): URI | undefined;
+ newSubscriber(subscriber: Subscriber): void;
+ destroySubscriber(subscriber: Subscriber): void;
+}
+
+// A SUBSCRIBE held back until the dialog exists.
+type QueuedSubscribe = {
+ body: string | null;
+ headers: string[];
+};
+
+/**
+ * Subscribes to an event the peer reports, and follows the NOTIFY requests
+ * that carry it, per
+ * [RFC 6665](https://datatracker.ietf.org/doc/html/rfc6665).
+ *
+ * @remarks
+ * - Applications get one from `UA.subscribe()`, and nothing is sent until
+ * {@link Subscriber.subscribe} is called.
+ */
+export class Subscriber
+ extends EventEmitter<SubscriberEventMap>
+ implements DialogOwner
+{
+ /**
+ * The constants above, reachable without the instance.
+ */
+ static get C(): typeof C {
+ return C;
+ }
+
+ /**
+ * The UA the subscriber belongs to.
+ *
+ * @internal
+ */
+ readonly _ua: SubscriberUA;
+
+ #target: URI;
+ #expires: number;
+ #content_type: string | undefined;
+ #params: OutgoingRequestParams;
+ #state: State = State.INIT;
+ #dialog: Dialog | null = null;
+
+ // Whether the 2xx response to the initial SUBSCRIBE was already processed.
+ #accepted = false;
+
+ // CSeq of the initial SUBSCRIBE. The dialog created by an early NOTIFY
+ // must continue this sequence (RFC 6665 4.1.2.4).
+ #initial_cseq: number | undefined;
+
+ // To refresh subscription.
+ #expires_timer: ReturnType<typeof setTimeout> | null = null;
+ #expires_timestamp: number | null = null;
+
+ // To prevent duplicate terminated call.
+ #terminated = false;
+
+ #event_name: string;
+ #event_id: string | null | undefined;
+ #headers: string[];
+
+ // To enqueue SUBSCRIBE requests created before the reception of the
+ // initial subscribe OK response.
+ #queue: QueuedSubscribe[] = [];
+
+ #data: unknown = {};
+
+ /**
+ * @param ua - The UA that sends the SUBSCRIBE.
+ * @param target - Who to subscribe to.
+ * @param eventName - Value of the Event header field, so the event name
+ * optionally followed by `;id=xxx`.
+ * @param accept - Value of the Accept header field.
+ *
+ * @throws
+ * - `TypeError` if `target`, `eventName` or `accept` is missing, if
+ * `eventName` is not a valid Event header field value, or if `target`
+ * is not a valid target.
+ */
+ constructor(
+ ua: SubscriberUA,
+ target: string | URI,
+ eventName: string,
+ accept: string,
+ {
+ expires,
+ contentType,
+ allowEvents,
+ params,
+ extraHeaders,
+ }: SubscriberOptions = {}
+ ) {
+ logger.debug('new');
+
+ super();
+
+ // Check that arguments are defined.
+ if (!target) {
+ throw new TypeError('Not enough arguments: Missing target');
+ }
+
+ if (!eventName) {
+ throw new TypeError('Not enough arguments: Missing eventName');
+ }
+
+ if (!accept) {
+ throw new TypeError('Not enough arguments: Missing accept');
+ }
+
+ const event_header: Grammar.EventHeader | -1 = Grammar.parse(
+ eventName,
+ 'Event'
+ );
+
+ if (event_header === -1) {
+ throw new TypeError('Missing Event header field');
+ }
+
+ this._ua = ua;
+
+ const normalized = this._ua.normalizeTarget(target);
+
+ if (!normalized) {
+ throw new TypeError(`Invalid target: ${target.toString()}`);
+ }
+
+ this.#target = normalized;
+
+ if (expires === undefined || !Utils.isDecimal(expires) || expires <= 0) {
+ expires = C.DEFAULT_EXPIRES_SEC;
+ }
+
+ this.#expires = expires;
+
+ // Used to subscribe with body.
+ this.#content_type = contentType;
+
+ // Set initial subscribe parameters.
+ this.#params = Utils.cloneObject(params);
+
+ if (!this.#params.from_uri) {
+ this.#params.from_uri = this._ua.configuration.uri;
+ }
+
+ this.#params.from_tag = Utils.newTag();
+ this.#params.to_tag = undefined;
+ this.#params.call_id = Utils.createRandomToken(20);
+
+ // Create subscribe cseq if not defined custom cseq.
+ if (this.#params.cseq === undefined) {
+ this.#params.cseq = Math.floor(Math.random() * 10000 + 1);
+ }
+
+ this.#event_name = event_header.event;
+ this.#event_id = event_header.params?.['id'];
+
+ let eventValue = this.#event_name;
+
+ if (this.#event_id) {
+ eventValue += `;id=${this.#event_id}`;
+ }
+
+ this.#headers = Utils.cloneArray(extraHeaders);
+ this.#headers = this.#headers.concat([
+ `Event: ${eventValue}`,
+ `Expires: ${this.#expires}`,
+ `Accept: ${accept}`,
+ ]);
+
+ if (!this.#headers.find(header => header.startsWith('Contact'))) {
+ const contact = `Contact: ${this._ua.contact.toString()}`;
+
+ this.#headers.push(contact);
+ }
+
+ if (allowEvents) {
+ this.#headers.push(`Allow-Events: ${allowEvents}`);
+ }
+ }
+
+ /**
+ * The constants above.
+ */
+ get C(): typeof C {
+ return C;
+ }
+
+ /**
+ * State of the subscription.
+ */
+ get state(): State {
+ return this.#state;
+ }
+
+ /**
+ * Id of the dialog the subscription runs in, or `null` until the
+ * notifier answers the initial SUBSCRIBE.
+ */
+ get id(): DialogId | null {
+ return this.#dialog ? this.#dialog.id : null;
+ }
+
+ /**
+ * Anything the application wants to keep along with the subscriber.
+ */
+ get data(): unknown {
+ return this.#data;
+ }
+
+ /**
+ * Replaces whatever was kept along with the subscriber.
+ */
+ set data(_data: unknown) {
+ this.#data = _data;
+ }
+
+ /**
+ * @internal
+ */
+ onRequestTimeout(): void {
+ this.#terminateDialog(TerminationCode.SUBSCRIBE_RESPONSE_TIMEOUT);
+ }
+
+ /**
+ * @internal
+ */
+ onTransportError(): void {
+ this.#terminateDialog(TerminationCode.SUBSCRIBE_TRANSPORT_ERROR);
+ }
+
+ /**
+ * Whether this subscriber is still waiting for the NOTIFY that creates
+ * the subscription dialog and the given NOTIFY belongs to its initial
+ * SUBSCRIBE.
+ *
+ * @param call_id - Call-ID of the received NOTIFY.
+ * @param to_tag - To tag of the received NOTIFY.
+ *
+ * @remarks
+ * - Called by the `UA`. The application must not call it.
+ * - [RFC 6665 Section 4.1.2.4](https://datatracker.ietf.org/doc/html/rfc6665#section-4.1.2.4):
+ * the first NOTIFY may arrive before the 2xx response to the initial
+ * SUBSCRIBE, in which case it is the one creating the dialog.
+ */
+ matchEarlyNotify(
+ call_id: string | undefined,
+ to_tag: string | undefined
+ ): boolean {
+ return (
+ this.#dialog === null &&
+ this.#state === State.WAITING_NOTIFY &&
+ call_id === this.#params.call_id &&
+ to_tag === this.#params.from_tag
+ );
+ }
+
+ /**
+ * Take over the NOTIFY that arrived before the 2xx response to the
+ * initial SUBSCRIBE, which creates the subscription dialog.
+ *
+ * @remarks
+ * - Called by the `UA`. The application must not call it.
+ */
+ receiveEarlyNotify(request: IncomingRequest): void {
+ let dialog;
+
+ try {
+ dialog = Dialog.Create(this, request, 'UAS');
+ } catch {
+ // NOTIFY without Contact.
+ request.reply(400);
+
+ return;
+ }
+
+ // The dialog is created by an incoming request, so it has no local
+ // sequence number yet. Continue the sequence of the initial SUBSCRIBE,
+ // otherwise the refresh would use a random (possibly lower) CSeq.
+ dialog.local_seqnum = this.#initial_cseq;
+
+ this.#dialog = dialog;
+
+ logger.debug('dialog created by the NOTIFY preceding the SUBSCRIBE 2xx');
+
+ dialog.receiveRequest(request);
+ }
+
+ /**
+ * Take over a request the dialog received.
+ *
+ * @remarks
+ * - Called by the `Dialog`. The application must not call it.
+ * - Anything other than a NOTIFY is answered 405.
+ */
+ receiveRequest(request: IncomingRequest): void {
+ if (request.method !== JsSIP_C.NOTIFY) {
+ logger.warn('received non-NOTIFY request');
+ request.reply(405);
+
+ return;
+ }
+
+ // RFC 6665 8.2.1. Check if event header matches.
+ const event_header = request.parseHeader<Grammar.EventHeader>('Event');
+
+ if (!event_header) {
+ logger.warn('missing Event header');
+ request.reply(400);
+ this.#terminateDialog(TerminationCode.WRONG_NOTIFY_RECEIVED);
+
+ return;
+ }
+
+ const event_name = event_header.event;
+ const event_id = event_header.params?.['id'];
+
+ if (event_name !== this.#event_name || event_id !== this.#event_id) {
+ logger.warn('Event header does not match the one in SUBSCRIBE request');
+ request.reply(489);
+ this.#terminateDialog(TerminationCode.WRONG_NOTIFY_RECEIVED);
+
+ return;
+ }
+
+ // Process Subscription-State header.
+ const subs_state =
+ request.parseHeader<Grammar.SubscriptionStateHeader>(
+ 'subscription-state'
+ );
+
+ if (!subs_state) {
+ logger.warn('missing Subscription-State header');
+ request.reply(400);
+ this.#terminateDialog(TerminationCode.WRONG_NOTIFY_RECEIVED);
+
+ return;
+ }
+
+ const new_state = this.#parseSubscriptionState(subs_state.state);
+
+ if (new_state === undefined) {
+ logger.warn(
+ `Invalid Subscription-State header value: ${subs_state.state}`
+ );
+ request.reply(400);
+ this.#terminateDialog(TerminationCode.WRONG_NOTIFY_RECEIVED);
+
+ return;
+ }
+ request.reply(200);
+
+ const prev_state = this.#state;
+
+ if (prev_state !== State.TERMINATED && new_state !== State.TERMINATED) {
+ this.#state = new_state;
+
+ if (subs_state.expires !== undefined) {
+ const expires = subs_state.expires;
+ const expires_timestamp = new Date().getTime() + expires * 1000;
+ const max_time_deviation = 2000;
+
+ // Expiration time is shorter and the difference is not too small.
+ // Before the first refresh is scheduled there is no timestamp to
+ // compare against, and nothing to bring forward either.
+ if (
+ this.#expires_timestamp !== null &&
+ this.#expires_timestamp - expires_timestamp > max_time_deviation
+ ) {
+ logger.debug('update sending re-SUBSCRIBE time');
+
+ this.#scheduleSubscribe(expires);
+ }
+ }
+ }
+
+ if (prev_state !== State.PENDING && new_state === State.PENDING) {
+ logger.debug('emit "pending"');
+
+ this.emit('pending');
+ } else if (prev_state !== State.ACTIVE && new_state === State.ACTIVE) {
+ logger.debug('emit "active"');
+
+ this.emit('active');
+ }
+
+ const body = request.body;
+
+ // Check if the notify is final.
+ const is_final = new_state === State.TERMINATED;
+
+ // Notify event fired only for notify with body.
+ if (body) {
+ const content_type = request.getHeader('content-type');
+
+ logger.debug('emit "notify"');
+
+ this.emit('notify', is_final, request, body, content_type);
+ }
+
+ if (is_final) {
+ const reason = subs_state.reason;
+ let retry_after = undefined;
+ const retry_after_param = subs_state.params?.['retry-after'];
+
+ if (retry_after_param !== undefined) {
+ retry_after = parseInt(retry_after_param!);
+ }
+
+ this.#terminateDialog(
+ TerminationCode.FINAL_NOTIFY_RECEIVED,
+ reason,
+ retry_after
+ );
+ }
+ }
+
+ /**
+ * Send the initial SUBSCRIBE, and every refresh of it afterwards.
+ *
+ * @param body - Body of the SUBSCRIBE, sent with the content type the
+ * subscriber was built with.
+ *
+ * @throws
+ * - `TypeError` if a body is given and no content type was configured.
+ *
+ * @remarks
+ * - Refreshes are sent on their own, so calling this once is enough to
+ * keep the subscription alive.
+ */
+ subscribe(body: string | null = null): void {
+ logger.debug('subscribe()');
+
+ if (this.#state === State.INIT) {
+ this.#sendInitialSubscribe(body, this.#headers);
+ } else {
+ this.#sendSubsequentSubscribe(body, this.#headers);
+ }
+ }
+
+ /**
+ * End the subscription, by sending a SUBSCRIBE with `Expires: 0`.
+ *
+ * @param body - Body of the un-SUBSCRIBE.
+ *
+ * @throws
+ * - {@link InvalidStateError} if nothing was subscribed to yet.
+ * - `TypeError` if a body is given and no content type was configured.
+ *
+ * @remarks
+ * - The subscriber stays alive until the final NOTIFY arrives, or for
+ * {@link C.FINAL_NOTIFY_TIMEOUT_SEC} seconds if it never does.
+ * - Calling it again while that is pending does nothing.
+ */
+ terminate(body: string | null = null): void {
+ logger.debug('terminate()');
+
+ if (this.#state === State.INIT) {
+ throw new InvalidStateError(this.#state);
+ }
+
+ // Prevent duplication un-subscribe sending.
+ if (this.#terminated) {
+ return;
+ }
+ this.#terminated = true;
+
+ // No refresh from now on.
+ clearTimeout(this.#expires_timer!);
+ this.#expires_timer = null;
+
+ // Set header Expires: 0.
+ const headers = this.#headers.map(header => {
+ return header.startsWith('Expires') ? 'Expires: 0' : header;
+ });
+
+ this.#sendSubsequentSubscribe(body, headers);
+ }
+
+ #terminateDialog(
+ terminationCode: TerminationCode,
+ reason: string | undefined = undefined,
+ retryAfter: number | undefined = undefined,
+ response: IncomingResponse | undefined = undefined
+ ): void {
+ // To prevent duplicate emit terminated event.
+ if (this.#state === State.TERMINATED) {
+ return;
+ }
+
+ this.#state = State.TERMINATED;
+
+ // Clear timers.
+ clearTimeout(this.#expires_timer!);
+
+ if (this.#dialog) {
+ this.#dialog.terminate();
+ this.#dialog = null;
+ }
+
+ this._ua.destroySubscriber(this);
+
+ logger.debug(`emit "terminated" code=${terminationCode}`);
+
+ this.emit('terminated', terminationCode, reason, retryAfter, response);
+ }
+
+ #sendInitialSubscribe(body: string | null, headers: string[]): void {
+ if (body) {
+ if (!this.#content_type) {
+ throw new TypeError('content_type is undefined');
+ }
+
+ headers = Utils.cloneArray(headers);
+ headers.push(`Content-Type: ${this.#content_type}`);
+ }
+
+ this.#state = State.WAITING_NOTIFY;
+
+ this._ua.newSubscriber(this);
+
+ const request = new SIPMessage.OutgoingRequest(
+ JsSIP_C.SUBSCRIBE,
+ this.#target,
+ this._ua,
+ this.#params,
+ headers,
+ // A request carries no body either way, but the field is typed as
+ // optional rather than nullable.
+ body ?? undefined
+ );
+
+ this.#initial_cseq = request.cseq;
+
+ const request_sender = new RequestSender(this._ua, request, {
+ onRequestTimeout: () => {
+ this.onRequestTimeout();
+ },
+ onTransportError: () => {
+ this.onTransportError();
+ },
+ onAuthenticated: authenticated_request => {
+ // The SUBSCRIBE is re-sent with an increased CSeq.
+ this.#initial_cseq = authenticated_request.cseq;
+
+ if (this.#dialog) {
+ this.#dialog.local_seqnum = this.#initial_cseq;
+ }
+ },
+ onReceiveResponse: response => {
+ this.#receiveSubscribeResponse(response);
+ },
+ });
+
+ request_sender.send();
+ }
+
+ #sendSubsequentSubscribe(body: string | null, headers: string[]): void {
+ if (this.#state === State.TERMINATED) {
+ return;
+ }
+
+ if (!this.#dialog) {
+ logger.debug('enqueue subscribe');
+
+ this.#queue.push({ body, headers: Utils.cloneArray(headers) });
+
+ return;
+ }
+
+ if (body) {
+ if (!this.#content_type) {
+ throw new TypeError('content_type is undefined');
+ }
+
+ headers = Utils.cloneArray(headers);
+ headers.push(`Content-Type: ${this.#content_type}`);
+ }
+
+ this.#dialog.sendRequest(JsSIP_C.SUBSCRIBE, {
+ body,
+ extraHeaders: headers,
+ eventHandlers: {
+ onRequestTimeout: () => {
+ this.onRequestTimeout();
+ },
+ onTransportError: () => {
+ this.onTransportError();
+ },
+ onSuccessResponse: response => {
+ this.#receiveSubscribeResponse(response);
+ },
+ onErrorResponse: response => {
+ this.#receiveSubscribeResponse(response);
+ },
+ onDialogError: response => {
+ this.#receiveSubscribeResponse(response);
+ },
+ },
+ });
+ }
+
+ #receiveSubscribeResponse(response: IncomingResponse): void {
+ if (this.#state === State.TERMINATED) {
+ return;
+ }
+
+ if (response.status_code >= 200 && response.status_code < 300) {
+ // Create dialog, unless an early NOTIFY already created it.
+ if (this.#dialog === null) {
+ let dialog;
+
+ try {
+ dialog = Dialog.Create(this, response, 'UAC');
+ } catch {
+ // OK response without Contact.
+ this.#terminateDialog(
+ TerminationCode.SUBSCRIBE_WRONG_OK_RESPONSE,
+ undefined,
+ undefined,
+ response
+ );
+
+ return;
+ }
+
+ this.#dialog = dialog;
+ }
+
+ // The initial SUBSCRIBE is accepted. Refreshes land here too.
+ if (!this.#accepted) {
+ this.#accepted = true;
+
+ logger.debug('emit "accepted"');
+
+ this.emit('accepted');
+
+ // Subsequent subscribes saved in the queue until dialog created.
+ const queue = this.#queue;
+
+ this.#queue = [];
+
+ for (const subscribe of queue) {
+ logger.debug('dequeue subscribe');
+
+ this.#sendSubsequentSubscribe(subscribe.body, subscribe.headers);
+ }
+ }
+
+ // Un-SUBSCRIBE accepted: no refresh, only the final NOTIFY to wait for
+ // (RFC 6665 4.1.2.3).
+ if (this.#terminated) {
+ // A stopped UA drops every incoming request, the final NOTIFY too.
+ if (this._ua.status === this._ua.C.STATUS_USER_CLOSED) {
+ this.#terminateDialog(
+ TerminationCode.UA_STOPPED,
+ undefined,
+ undefined,
+ response
+ );
+ } else {
+ this.#scheduleFinalNotifyTimeout();
+ }
+
+ return;
+ }
+
+ // Check expires value.
+ const expires_value = response.getHeader('expires');
+
+ let expires = parseInt(expires_value!);
+
+ if (!Utils.isDecimal(expires) || expires <= 0) {
+ logger.warn(
+ `response without Expires header, setting a default value of ${C.DEFAULT_EXPIRES_SEC}`
+ );
+
+ // RFC 6665 3.1.1 subscribe OK response must contain Expires header.
+ // Use workaround expires value.
+ expires = C.DEFAULT_EXPIRES_SEC;
+ }
+
+ if (expires > 0) {
+ this.#scheduleSubscribe(expires);
+ }
+ } else if (response.status_code === 401 || response.status_code === 407) {
+ this.#terminateDialog(
+ TerminationCode.SUBSCRIBE_AUTHENTICATION_FAILED,
+ undefined,
+ undefined,
+ response
+ );
+ } else if (response.status_code >= 300) {
+ this.#terminateDialog(
+ TerminationCode.SUBSCRIBE_NON_OK_RESPONSE,
+ undefined,
+ undefined,
+ response
+ );
+ }
+ }
+
+ #scheduleSubscribe(expires: number): void {
+ // If the expires time is less than 140 seconds we do not support Chrome
+ // intensive timer throttling mode. In this case, the re-subcribe is sent
+ // 5 seconds before the subscription expiration.
+ //
+ // When Chrome is in intensive timer throttling mode, in the worst case,
+ // the timer will be 60 seconds late. We give the server 10 seconds to
+ // make sure it will execute the command even if it is heavily loaded.
+ // As a result, we order the time no later than 70 seconds before the
+ // subscription expiration. Resulting time calculated as half time
+ // interval + (half interval - 70) * random.
+ //
+ // E.g. expires is 140, re-subscribe will be ordered to send in 70 sec.
+ // expires is 600, re-subscribe will be ordered to send in
+ // 300 + (0 .. 230) seconds.
+
+ const timeout =
+ expires >= 140
+ ? (expires * 1000) / 2 +
+ Math.floor((expires / 2 - 70) * 1000 * Math.random())
+ : expires * 1000 - 5000;
+
+ this.#expires_timestamp = new Date().getTime() + expires * 1000;
+
+ logger.debug(
+ `next SUBSCRIBE will be sent in ${Math.floor(timeout / 1000)} sec`
+ );
+
+ clearTimeout(this.#expires_timer!);
+ this.#expires_timer = setTimeout(() => {
+ this.#expires_timer = null;
+ this.#sendSubsequentSubscribe(null, this.#headers);
+ }, timeout);
+ }
+
+ #scheduleFinalNotifyTimeout(): void {
+ clearTimeout(this.#expires_timer!);
+ this.#expires_timer = setTimeout(() => {
+ this.#expires_timer = null;
+ logger.debug('no final NOTIFY received after un-SUBSCRIBE');
+ this.#terminateDialog(TerminationCode.UNSUBSCRIBE_TIMEOUT);
+ }, C.FINAL_NOTIFY_TIMEOUT_SEC * 1000);
+ }
+
+ #parseSubscriptionState(strState: string): State | undefined {
+ switch (strState) {
+ case 'pending': {
+ return State.PENDING;
+ }
+ case 'active': {
+ return State.ACTIVE;
+ }
+ case 'terminated': {
+ return State.TERMINATED;
+ }
+ case 'init': {
+ return State.INIT;
+ }
+ case 'notify_wait': {
+ return State.WAITING_NOTIFY;
+ }
+ default: {
+ return undefined;
+ }
+ }
+ }
+}
diff --git a/src/UA.d.ts b/src/UA.d.ts
index 9726f01..649209b 100644
--- a/src/UA.d.ts
+++ b/src/UA.d.ts
@@ -17,7 +17,7 @@ import { Message, SendMessageOptions } from './Message';
import { Options, SendOptionsOptions } from './Options';
import { Registrator } from './Registrator';
import { Notifier, NotifierOptions } from './Notifier';
-import { Subscriber } from './Subscriber';
+import { Subscriber, SubscriberOptions } from './Subscriber';
import URI = require('./URI');
import { causes } from './Constants';
import { Configuration } from './Configuration';
@@ -212,15 +212,7 @@ export interface SubscriberParams {
to_display_name?: string;
}
-export interface SubscriberOptions {
- expires?: number;
- contentType?: string;
- allowEvents?: string;
- params?: SubscriberParams;
- extraHeaders?: string[];
-}
-
-export { NotifierOptions };
+export { NotifierOptions, SubscriberOptions };
declare enum UAStatus {
// UA status codes.
diff --git a/src/UA.js b/src/UA.js
index 1a1685a..4aed61c 100644
--- a/src/UA.js
+++ b/src/UA.js
@@ -5,7 +5,7 @@ const { Logger } = require('./Logger');
const JsSIP_C = require('./Constants');
const { Registrator } = require('./Registrator');
const RTCSession = require('./RTCSession');
-const Subscriber = require('./Subscriber');
+const { Subscriber } = require('./Subscriber');
const { Notifier } = require('./Notifier');
const { Message } = require('./Message');
const { Options } = require('./Options');