var XYClient = (function(exports, ice) { 'use strict'; var domain; // This constructor is used to store event handlers. Instantiating this is // faster than explicitly calling `Object.create(null)` to get a "clean" empty // object (tested with v8 v4.9). function EventHandlers() {} EventHandlers.prototype = Object.create(null); function EventEmitter() { EventEmitter.init.call(this); } // nodejs oddity // require('events') === require('events').EventEmitter EventEmitter.EventEmitter = EventEmitter; EventEmitter.usingDomains = false; EventEmitter.prototype.domain = undefined; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; EventEmitter.init = function() { this.domain = null; if (EventEmitter.usingDomains) { // if there is an active domain, then attach to it. if (domain.active && !(this instanceof domain.Domain)); } if (!this._events || this._events === Object.getPrototypeOf(this)._events) { this._events = new EventHandlers(); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; }; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || isNaN(n)) throw new TypeError('"n" argument must be a positive number'); this._maxListeners = n; return this; }; function $getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return $getMaxListeners(this); }; // These standalone emit* functions are used to optimize calling of event // handlers for fast cases because emit() itself often has a variable number of // arguments and can be deoptimized because of that. These functions always have // the same number of arguments and thus do not get deoptimized, so the code // inside them can execute faster. function emitNone(handler, isFn, self) { if (isFn) handler.call(self); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self); } } function emitOne(handler, isFn, self, arg1) { if (isFn) handler.call(self, arg1); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1); } } function emitTwo(handler, isFn, self, arg1, arg2) { if (isFn) handler.call(self, arg1, arg2); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1, arg2); } } function emitThree(handler, isFn, self, arg1, arg2, arg3) { if (isFn) handler.call(self, arg1, arg2, arg3); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1, arg2, arg3); } } function emitMany(handler, isFn, self, args) { if (isFn) handler.apply(self, args); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].apply(self, args); } } EventEmitter.prototype.emit = function emit(type) { var er, handler, len, args, i, events, domain; var doError = (type === 'error'); events = this._events; if (events) doError = (doError && events.error == null); else if (!doError) return false; domain = this.domain; // If there is no 'error' event listener then throw. if (doError) { er = arguments[1]; if (domain) { if (!er) er = new Error('Uncaught, unspecified "error" event'); er.domainEmitter = this; er.domain = domain; er.domainThrown = false; domain.emit('error', er); } else if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } return false; } handler = events[type]; if (!handler) return false; var isFn = typeof handler === 'function'; len = arguments.length; switch (len) { // fast cases case 1: emitNone(handler, isFn, this); break; case 2: emitOne(handler, isFn, this, arguments[1]); break; case 3: emitTwo(handler, isFn, this, arguments[1], arguments[2]); break; case 4: emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); break; // slower default: args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; emitMany(handler, isFn, this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = target._events; if (!events) { events = target._events = new EventHandlers(); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (!existing) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; } else { // If we've already got an array, just append. if (prepend) { existing.unshift(listener); } else { existing.push(listener); } } // Check for listener leak if (!existing.warned) { m = $getMaxListeners(target); if (m && m > 0 && existing.length > m) { existing.warned = true; var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + type + ' listeners added. ' + 'Use emitter.setMaxListeners() to increase limit'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; emitWarning(w); } } } return target; } function emitWarning(e) { typeof console.warn === 'function' ? console.warn(e) : console.log(e); } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function _onceWrap(target, type, listener) { var fired = false; function g() { target.removeListener(type, g); if (!fired) { fired = true; listener.apply(target, arguments); } } g.listener = listener; return g; } EventEmitter.prototype.once = function once(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = this._events; if (!events) return this; list = events[type]; if (!list) return this; if (list === listener || (list.listener && list.listener === listener)) { if (--this._eventsCount === 0) this._events = new EventHandlers(); else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (list.length === 1) { list[0] = undefined; if (--this._eventsCount === 0) { this._events = new EventHandlers(); return this; } else { delete events[type]; } } else { spliceOne(list, position); } if (events.removeListener) this.emit('removeListener', type, originalListener || listener); } return this; }; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events; events = this._events; if (!events) return this; // not listening for removeListener, no need to emit if (!events.removeListener) { if (arguments.length === 0) { this._events = new EventHandlers(); this._eventsCount = 0; } else if (events[type]) { if (--this._eventsCount === 0) this._events = new EventHandlers(); else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = Object.keys(events); for (var i = 0, key; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = new EventHandlers(); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners) { // LIFO order do { this.removeListener(type, listeners[listeners.length - 1]); } while (listeners[0]); } return this; }; EventEmitter.prototype.listeners = function listeners(type) { var evlistener; var ret; var events = this._events; if (!events) ret = []; else { evlistener = events[type]; if (!evlistener) ret = []; else if (typeof evlistener === 'function') ret = [evlistener.listener || evlistener]; else ret = unwrapListeners(evlistener); } return ret; }; EventEmitter.listenerCount = function(emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; }; // About 1.5x faster than the two-arg version of Array#splice(). function spliceOne(list, index) { for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) list[i] = list[k]; list.pop(); } function arrayClone(arr, i) { var copy = new Array(i); while (i--) copy[i] = arr[i]; return copy; } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } /** * 呼叫状态 */ var CallState; (function(CallState) { /** * 0 无 */ CallState[CallState["None"] = 0] = "None"; /** *1 初始 */ CallState[CallState["Init"] = 1] = "Init"; /** *2 空闲 */ CallState[CallState["Normal"] = 2] = "Normal"; /** *3 呼出 */ CallState[CallState["Callout"] = 3] = "Callout"; /** * 4 呼入 */ CallState[CallState["Incoming"] = 4] = "Incoming"; /** * 5 回铃 */ CallState[CallState["Ringing"] = 5] = "Ringing"; /** * 6 通话 */ CallState[CallState["Connect"] = 6] = "Connect"; /** * 7 结束 */ CallState[CallState["Release"] = 7] = "Release"; /** * 8 保持 */ CallState[CallState["Hold"] = 8] = "Hold"; /** * 9 取消保持 */ CallState[CallState["Unhold"] = 9] = "Unhold"; })(CallState || (CallState = {})); // export interface interruptEventPara { // sender: Call; // number: string; // } // ********************************************************************** // const _ModuleRegistry = ice.Ice._ModuleRegistry; const Slice = ice.Ice.Slice; let Dispatcher = _ModuleRegistry.module("Dispatcher"); Dispatcher.ECode = Slice.defineEnum([ ['ECodeNone', 0], ['ECodeRegister', 1000], ['ECodeRegisterKickout', 1001], ['ECodeRegisterTimeout', 1002], ['ECodeRegisterNotRegister', 1003], ['ECodeRegisterDisConnect', 1004], ['ECodeRegisterUserIsLogin', 1005], ['ECodeRegisterErrorPwd', 1006], ['ECodeRegisterLicenseOut', 1007], ['ECodeRegisterNotExist', 1008], ['ECodeCalling', 1100], ['ECodeCallingCaller', 1101], ['ECodeCallingCallee', 1102], ['ECodeCallingType', 1103], ['ECodeCallingSessionNotFound', 1104], ['ECodeCallingTerminalNotFound', 1105], ['ECodeCallingNumberNotRegistered', 1106], ['ECodeCallingUserNotExist', 1107], ['ECodeCallingNoAuth', 1108], ['ECodeCallingOprFailed', 1109], ['ECodeCallingUserNotInGroup', 1110], ['ECodeCallingGroupNotFound', 1111], ['ECodeCallingCallTypeError', 1112], ['ECodeCallingSessionCreateFailed', 1113], ['ECodeOpFaxFailured', 1114], ['ECodeFileNotFound', 1115], ['ECodeNoCid', 1116], ['ECodeNumberBusy', 1117], ['ECodeCallingOperateFailed', 1118], ['ECodeCallingNotHaveFitCall', 1119], ['ECodeNotDTPUser', 1120], ['ECodeSessionStateError', 1121], ['ECodeCanNotCallIntercomGroup', 1122], ['ECodeCallingOperateNotConn', 1123], ['ECodeConsole', 1200], ['ECodeConsoleBind', 1201], ['ECodeErrLicense', 1202], ['ECodeErrCanNotUse', 1203], ['ECodeConsoleBindErrorType', 1204], ['ECodeConsoleBindFristRegist', 1205], ['ECodeNotMCUSession', 1300], ['ECodeIsBinded', 1301], ['ECodeMsgGroupExist', 1400], ['ECodeMsgGroupNotExist', 1401], ['ECodeVideoBugCalledIsVoice', 1500] ]); Object.defineProperty(Dispatcher, 'ECodeNoneDis', { value: "\u672a\u5b9a\u4e49\u9519\u8bef" }); Object.defineProperty(Dispatcher, 'ECodeRegisterKickoutDis', { value: "\u5f02\u5730\u767b\u9646" }); Object.defineProperty(Dispatcher, 'ECodeRegisterTimeoutDis', { value: "\u767b\u9646\u8d85\u65f6" }); Object.defineProperty(Dispatcher, 'ECodeRegisterNotRegisterDis', { value: "\u53f7\u7801\u672a\u6ce8\u518c" }); Object.defineProperty(Dispatcher, 'ECodeRegisterDisConnectDis', { value: "\u8fde\u63a5\u5df2\u65ad\u5f00" }); Object.defineProperty(Dispatcher, 'ECodeRegisterUserIsLoginDis', { value: "\u53f7\u7801\u5df2\u5728\u5176\u5b83\u7ec8\u7aef\u767b\u5f55" }); Object.defineProperty(Dispatcher, 'ECodeRegisterErrorPwdDis', { value: "\u5bc6\u7801\u9519\u8bef" }); Object.defineProperty(Dispatcher, 'ECodeRegisterLicenseOutDis', { value: "\u8fbe\u5230\u6388\u6743\u6570\u4e0a\u9650" }); Object.defineProperty(Dispatcher, 'ECodeRegisterNotExistDis', { value: "\u7528\u6237\u4e0d\u5b58\u5728" }); Object.defineProperty(Dispatcher, 'ECodeCallingCallerDis', { value: "\u4e3b\u53eb\u53f7\u7801\u9519\u8bef" }); Object.defineProperty(Dispatcher, 'ECodeCallingCalleeDis', { value: "\u88ab\u53eb\u53f7\u7801\u9519\u8bef" }); Object.defineProperty(Dispatcher, 'ECodeCallingTypeDis', { value: "\u547c\u53eb\u7c7b\u578b\u9519\u8bef" }); Object.defineProperty(Dispatcher, 'ECodeCallingSessionNotFoundDis', { value: "\u627e\u4e0d\u5230\u547c\u53ebID" }); Object.defineProperty(Dispatcher, 'ECodeConsoleBindDis', { value: "\u7ed1\u5b9a\u53f7\u7801\u9519\u8bef,\u53f7\u7801\u672a\u6ce8\u518c" }); Object.defineProperty(Dispatcher, 'ECodeConsoleBindErrorTypeDis', { value: "\u7ed1\u5b9a\u53f7\u7801\u9519\u8bef,\u53f7\u7801\u7c7b\u578b\u9519\u8bef" }); Object.defineProperty(Dispatcher, 'ECodeConsoleBindFristRegistDis', { value: "\u8bf7\u5148\u6ce8\u518c\u518d\u7ed1\u5b9a\u53f7\u7801" }); Object.defineProperty(Dispatcher, 'ECodeCallingTerminalNotFoundDis', { value: "\u53f7\u7801\u4e0d\u5b58\u5728" }); Object.defineProperty(Dispatcher, 'ECodeCallingNumberNotRegisteredDis', { value: "\u53f7\u7801\u672a\u6ce8\u518c" }); Object.defineProperty(Dispatcher, 'ECodeCallingUserNotExistDis', { value: "\u7528\u6237\u4e0d\u5b58\u5728" }); Object.defineProperty(Dispatcher, 'ECodeCallingNoAuthDis', { value: "\u6ca1\u6709\u6743\u9650" }); Object.defineProperty(Dispatcher, 'ECodeCallingOprFailedDis', { value: "\u64cd\u4f5c\u6267\u884c\u5931\u8d25" }); Object.defineProperty(Dispatcher, 'ECodeCallingUserNotInGroupDis', { value: "\u7528\u6237\u5728\u8be5\u7ec4\u4e2d\u4e0d\u5b58\u5728" }); Object.defineProperty(Dispatcher, 'ECodeCallingGroupNotFoundDis', { value: "\u7ec4\u53f7\u4e0d\u5b58\u5728" }); Object.defineProperty(Dispatcher, 'ECodeCallingCallTypeErrorDis', { value: "\u547c\u53eb\u7c7b\u578b\u9519\u8bef" }); Object.defineProperty(Dispatcher, 'ECodeCallingSessionCreateFailedDis', { value: "\u547c\u53eb\u521b\u5efa\u5931\u8d25" }); Object.defineProperty(Dispatcher, 'ECodeCallingOperateFailedDis', { value: "\u64cd\u4f5c\u5931\u8d25" }); Object.defineProperty(Dispatcher, 'ECodeCallingNotHaveFitCallDis', { value: "\u6ca1\u6709\u7b26\u5408\u6761\u4ef6\u547c\u53eb" }); Object.defineProperty(Dispatcher, 'ECodeSessionStateErrorDis', { value: "\u547c\u53eb\u72b6\u6001\u9519\u8bef" }); Object.defineProperty(Dispatcher, 'ECodeCanNotCallIntercomGroupDis', { value: "\u4e0d\u80fd\u547c\u53eb\u5bf9\u8bb2\u7ec4" }); Object.defineProperty(Dispatcher, 'ECodeCallingOperateNotConnDis', { value: "\u4ec5\u53ef\u5bf9\u901a\u8bdd\u4e2d\u7684\u7528\u6237\u8fdb\u884c\u64cd\u4f5c" }); Object.defineProperty(Dispatcher, 'ECodeOpFaxFailuredDis', { value: "\u53d1\u9001\u4f20\u771f\u5931\u8d25" }); Object.defineProperty(Dispatcher, 'ECodeFileNotFoundDis', { value: "\u627e\u4e0d\u5230\u6587\u4ef6" }); Object.defineProperty(Dispatcher, 'ECodeNoCidDis', { value: "\u547c\u53ebID\u4e3a\u7a7a" }); Object.defineProperty(Dispatcher, 'ECodeNumberBusyDis', { value: "\u6307\u5b9a\u53f7\u7801\u5fd9" }); Object.defineProperty(Dispatcher, 'ECodeErrLicenseDis', { value: "\u8d85\u51falicense\u9650\u5236" }); Object.defineProperty(Dispatcher, 'ECodeErrCanNotUseDis', { value: "\u529f\u80fd\u672a\u5f00\u901a" }); Object.defineProperty(Dispatcher, 'ECodeNotDTPUserDis', { value: "\u975e\u8c03\u5ea6\u7528\u6237" }); Object.defineProperty(Dispatcher, 'ECodeNotMCUSessionDis', { value: "\u975eMCU\u547c\u53eb" }); Object.defineProperty(Dispatcher, 'ECodeIsBindedDis', { value: "\u53f7\u7801\u5df2\u88ab\u7ed1\u5b9a\uff0c\u7ed1\u5b9a\u4eba:" }); Object.defineProperty(Dispatcher, 'ECodeMsgGroupExistDis', { value: "\u5f53\u524d\u7fa4\u5df2\u5b58\u5728" }); Object.defineProperty(Dispatcher, 'ECodeMsgGroupNotExistDis', { value: "\u6307\u5b9a\u7684\u7fa4\u4e0d\u5b58\u5728" }); Object.defineProperty(Dispatcher, 'ECodeVideoBugCalledIsVoiceDis', { value: "\u6307\u5b9a\u53f7\u7801\u5728\u97f3\u9891\u901a\u8bdd\u4e2d" }); Dispatcher.Error = class extends ice.Ice.UserException { constructor(code = Dispatcher.ECode.ECodeNone, desc = "", _cause = "") { super(_cause); this.code = code; this.desc = desc; } static get _parent() { return ice.Ice.UserException; } static get _id() { return "::Dispatcher::Error"; } _mostDerivedType() { return Dispatcher.Error; } _writeMemberImpl(ostr) { Dispatcher.ECode._write(ostr, this.code); ostr.writeString(this.desc); } _readMemberImpl(istr) { this.code = Dispatcher.ECode._read(istr); this.desc = istr.readString(); } }; Object.defineProperty(Dispatcher, 'SYSMessageDiskUsed', { value: "\u8c03\u5ea6\u670d\u52a1\u5668\u5b58\u50a8\u5feb\u6ee1\uff0c\u8bf7\u53ca\u65f6\u5907\u4efd\u6216\u6e05\u9664\u6570\u636e" }); Object.defineProperty(Dispatcher, 'SYSMessageDiskClear', { value: "\u8c03\u5ea6\u670d\u52a1\u5668\u5b58\u50a8\u7a7a\u95f4\u6e05\u7406\u5b8c\u6bd5" }); // const _ModuleRegistry$1 = ice.Ice._ModuleRegistry; const Slice$1 = ice.Ice.Slice; let Dispatcher$1 = _ModuleRegistry$1.module("Dispatcher"); Dispatcher$1.CallType = Slice$1.defineEnum([ ['CallTypeNone', 0], ['CallTypeSingle', 1], ['CallTypeTmpgroup', 2], ['CallTypeReport', 3], ['CallTypeBroadcast', 4], ['CallTypeTemporary', 5], ['CallTypeInterpose', 6], ['CallTypeForceremove', 7], ['CallTypeMonitor', 8], ['CallTypeIntercom', 9], ['CallTypeSwitch', 10], ['CallTypeUrgent', 11], ['CallTypeSingle2', 12], ['CallTypeTmpintercom', 13], ['CallTypeVideobug', 14], ['CallTypeMCUMetting', 15], ['CallTypeSOS', 16], ['CallTypeTransferVideo', 17], ['CallTypeTransferVideoToMcu', 18], ['CallTypeUploadVideo', 19] ]); Dispatcher$1.SubCallType = Slice$1.defineEnum([ ['SubCallTypeNone', 0], ['SubCallTypeFixMeeting', 1], ['SubCallTypeScheduleMeeting', 2], ['SubCallTypeSwitch', 3] ]); Dispatcher$1.RegisterState = Slice$1.defineEnum([ ['RegisterStateNone', 0], ['RegisterStateLogin', 1], ['RegisterStateLogout', 2], ['RegisterStateTTOnline', 20] ]); Dispatcher$1.CallState = Slice$1.defineEnum([ ['CallStateNone', 0], ['CallStateInit', 1], ['CallStateNormal', 2], ['CallStateCallout', 3], ['CallStateIncoming', 4], ['CallStateRinging', 5], ['CallStateConnect', 6], ['CallStateHold', 7], ['CallStateBusy', 8], ['CallStateOffhook', 9], ['CallStateRelease', 10], ['CallStateUnspeak', 11], ['CallStateSpeak', 12], ['CallStateQueue', 13], ['CallStateUnhold', 14], ['CallStateZombie', 15] ]); Dispatcher$1.MediaType = Slice$1.defineEnum([ ['MediaTypeNone', 0], ['MediaTypeAudio', 1], ['MediaTypeVideo', 2] ]); Dispatcher$1.GroupType = Slice$1.defineEnum([ ['GroupTypeIntercomgroup', 0], ['GroupTypeOther', 1], ['GroupTypeNone', 2] ]); Dispatcher$1.UserType = Slice$1.defineEnum([ ['UserTypeDispatch', 0], ['UserTypeHandheld', 1], ['UserTypeCommonuser', 2], ['UserTypeOutlineuser', 3], ['UserTypeMonitoruser', 4], ['UserTypeSsu', 5], ['UserType3ghandheld', 6], ['UserTypeMonitordevice', 7], ['UserTypeNone', 8], ['UserType323', 9], ['UserTypeStationGroup', 10], ['UserTypeStationUser', 11], ['UserTypeRelayUser', 12], ['UserTypeBroadRelayUser', 13], ['UserTypeRelayGW', 14], ['UserTypeMCUReg', 15], ['UserTypeOutlineHandler', 16], ['UserTypeWeiDe', 17], ['UserTypeOutlineCar', 18], ['UserTypeTianTong', 20], ['UserTypeMeshDev', 21] ]); Dispatcher$1.FileType = Slice$1.defineEnum([ ['FileTypeNone', 0], ['FileTypeText', 1], ['FileTypePic', 2], ['FileTypeVoice', 3], ['FileTypeVideo', 4], ['FileTypeGisinfo', 5], ['FileTypePlayAudio', 6], ['FileTypeFax', 7], ['FileTypeOther', 8], ['FileTypePlayVideo', 9] ]); Dispatcher$1.FileState = Slice$1.defineEnum([ ['FileStateNone', 0], ['FileStateUploading', 1], ['FileStateUploaded', 2] ]); Dispatcher$1.SpeakType = Slice$1.defineEnum([ ['SpeakTypeNone', 0], ['SpeakTypeMute', 1], ['SpeakTypeUnmute', 2] ]); Dispatcher$1.UserOrGroup = Slice$1.defineEnum([ ['UOGNone', 0], ['UOGEmployee', 1], ['UOGGroup', 2] ]); Dispatcher$1.HearType = Slice$1.defineEnum([ ['HearTypeNone', 0], ['HearTypeMute', 1], ['HearTypeUnmute', 2] ]); Dispatcher$1.PushVideoType = Slice$1.defineEnum([ ['PushVideoTypeNone', 0], ['PushVideoTypePush', 1], ['PushVideoTypeUnpush', 2] ]); Dispatcher$1.PlayAudioType = Slice$1.defineEnum([ ['PlayAudioTypeNone', 0], ['PlayAudioTypeStart', 1], ['PlayAudioTypeStop', 2] ]); Dispatcher$1.PlayVideoType = Slice$1.defineEnum([ ['PlayVideoTypeNone', 0], ['PlayVideoTypeStart', 1], ['PlayVideoTypeStop', 2] ]); Dispatcher$1.AudioFileType = Slice$1.defineEnum([ ['AudioFileTypeNone', 0], ['AudioFileTypeEcho', 1] ]); Dispatcher$1.AnswerType = Slice$1.defineEnum([ ['AnswerTypeNone', 0], ['AnswerTypeAuto', 1], ['AnswerTypeMan', 2] ]); Dispatcher$1.HoldType = Slice$1.defineEnum([ ['HoldTypeNone', 0], ['HoldTypeHold', 1], ['HoldTypeUnhold', 2] ]); Dispatcher$1.GisTraceType = Slice$1.defineEnum([ ['GisTraceTypeNone', 0], ['GisTraceTypeSub', 1], ['GisTraceTypeUnsub', 2] ]); Dispatcher$1.PrePlanState = Slice$1.defineEnum([ ['PrePlanStateNone', 0], ['PrePlanStateRuning', 1], ['PrePlanStateEnd', 2] ]); Dispatcher$1.VBugStateType = Slice$1.defineEnum([ ['VBugStateTypeNone', 0], ['VBugStateTypeOk', 1], ['VBugStateTypeFailure', 2], ['VBugStateTypeRelease', 3] ]); Dispatcher$1.PrePlanInstType = Slice$1.defineEnum([ ['PrePlanTypeInstMessage', 1], ['PrePlanTypeInstBroadCast', 2], ['PrePlanTypeInstMeeting', 3] ]); Dispatcher$1.FaxStateSend = Slice$1.defineEnum([ ['FaxStateSendNone', 0], ['FaxStateSending', 1], ['FaxStateSended', 2], ['FaxStateSendFailure', 3] ]); Dispatcher$1.FaxStateRecv = Slice$1.defineEnum([ ['FaxStateRecvNone', 0], ['FaxStateRecving', 1], ['FaxStateRecved', 2], ['FaxStateRecvedFailure', 3] ]); Dispatcher$1.emCalledType = Slice$1.defineEnum([ ['CalledTypeNONE', 0], ['CalledTypeTDNSFreeswitch', 1], ['CalledTypeMCU', 2], ['CalledTypePlayVideo', 3], ['CalledTypeMCUDevice', 4], ['CalledType28181', 5], ['CalledTypeMonitorDeivce', 6], ['CalledTypePlayHisVideo', 7] ]); Dispatcher$1.emVideoDeviceType = Slice$1.defineEnum([ ['VDTNONE', 0], ['VDTHKIPC', 1], ['VDTOTHER', 2], ['VDTHKDVR', 3], ['VDTHKVIDEOSERVER', 4], ['VDTHKDECOMPILER', 5], ['VDTDHIPC', 10], ['VDTDHDVR', 11], ['VDTDHVIDEOSERVER', 12], ['VDTDHDECOMPILER', 13], ['VDTWEIBOIPC', 14], ['VDT4GMONITOR', 15], ['VDTMINGJING', 16] ]); Dispatcher$1.emCodecType = Slice$1.defineEnum([ ['CDTNONE', 0], ['CDTH264', 1], ['CDTH265', 2], ['CDT264265', 3] ]); Dispatcher$1.Identity = class { constructor(user = "") { this.user = user; } _write(ostr) { ostr.writeString(this.user); } _read(istr) { this.user = istr.readString(); } static get minWireSize() { return 1; } }; Slice$1.defineStruct(Dispatcher$1.Identity, true, true); Dispatcher$1.CommonRequestT = class { constructor(cid = "") { this.cid = cid; } _write(ostr) { ostr.writeString(this.cid); } _read(istr) { this.cid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$1.defineStruct(Dispatcher$1.CommonRequestT, true, true); Object.defineProperty(Dispatcher$1, 'CALLREMARKENGOTRANSFER', { value: "\u534f\u5546\u8f6c\u63a5" }); Object.defineProperty(Dispatcher$1, 'CALLREMARKMOINTOR', { value: "\u76d1\u542c" }); Object.defineProperty(Dispatcher$1, 'CALLREMARKSUBSTITUTE', { value: "\u4ee3\u63a5" }); Object.defineProperty(Dispatcher$1, 'CALLREMARKINTERPOSE', { value: "\u5f3a\u63d2" }); Object.defineProperty(Dispatcher$1, 'CALLREMARKREMOVE', { value: "\u5f3a\u65ad" }); Object.defineProperty(Dispatcher$1, 'CALLREMARKSWITCH', { value: "\u8f6c\u63a5" }); Object.defineProperty(Dispatcher$1, 'CALLREMARKADDMEMBER', { value: "\u9080\u8bf7\u6210\u5458" }); Object.defineProperty(Dispatcher$1, 'CALLREMARKPLAYFILE', { value: "\u64ad\u653e\u6587\u4ef6" }); Object.defineProperty(Dispatcher$1, 'CALLREMARKREMOVEOTHER', { value: "\u5f3a\u62c6" }); Object.defineProperty(Dispatcher$1, 'STRYMSDISPATCHERGROUP', { value: "\u8c03\u5ea6\u670d\u52a1\u5668\u4e13\u7528" }); // const _ModuleRegistry$2 = ice.Ice._ModuleRegistry; const Slice$2 = ice.Ice.Slice; Dispatcher.BusinessTypeRT = class { constructor(id = 0, WTGroupID = 0, WorkTypeName = "", TheValue = 0, description = "", TheState = 0, IsDefault = 0, WTGroupName = "") { this.id = id; this.WTGroupID = WTGroupID; this.WorkTypeName = WorkTypeName; this.TheValue = TheValue; this.description = description; this.TheState = TheState; this.IsDefault = IsDefault; this.WTGroupName = WTGroupName; } _write(ostr) { ostr.writeInt(this.id); ostr.writeInt(this.WTGroupID); ostr.writeString(this.WorkTypeName); ostr.writeInt(this.TheValue); ostr.writeString(this.description); ostr.writeInt(this.TheState); ostr.writeInt(this.IsDefault); ostr.writeString(this.WTGroupName); } _read(istr) { this.id = istr.readInt(); this.WTGroupID = istr.readInt(); this.WorkTypeName = istr.readString(); this.TheValue = istr.readInt(); this.description = istr.readString(); this.TheState = istr.readInt(); this.IsDefault = istr.readInt(); this.WTGroupName = istr.readString(); } static get minWireSize() { return 23; } }; Slice$2.defineStruct(Dispatcher.BusinessTypeRT, true, true); Slice$2.defineSequence(Dispatcher, "BusinessTypeRTSeqHelper", "Dispatcher.BusinessTypeRT", false); Dispatcher.SendBusFileReceiveT = class { constructor(MsgUUID = "", Receiver = "", ReceiverName = "", Remark = "", ModifyEmployee = "") { this.MsgUUID = MsgUUID; this.Receiver = Receiver; this.ReceiverName = ReceiverName; this.Remark = Remark; this.ModifyEmployee = ModifyEmployee; } _write(ostr) { ostr.writeString(this.MsgUUID); ostr.writeString(this.Receiver); ostr.writeString(this.ReceiverName); ostr.writeString(this.Remark); ostr.writeString(this.ModifyEmployee); } _read(istr) { this.MsgUUID = istr.readString(); this.Receiver = istr.readString(); this.ReceiverName = istr.readString(); this.Remark = istr.readString(); this.ModifyEmployee = istr.readString(); } static get minWireSize() { return 5; } }; Slice$2.defineStruct(Dispatcher.SendBusFileReceiveT, true, true); Slice$2.defineSequence(Dispatcher, "SendBusFileReceiveSeqHelper", "Dispatcher.SendBusFileReceiveT", false); Dispatcher.StartSendBusFileT = class { constructor(MsgUUID = "", FileUUID = "", FileType = 0, FileName = "", Remark = "") { this.MsgUUID = MsgUUID; this.FileUUID = FileUUID; this.FileType = FileType; this.FileName = FileName; this.Remark = Remark; } _write(ostr) { ostr.writeString(this.MsgUUID); ostr.writeString(this.FileUUID); ostr.writeInt(this.FileType); ostr.writeString(this.FileName); ostr.writeString(this.Remark); } _read(istr) { this.MsgUUID = istr.readString(); this.FileUUID = istr.readString(); this.FileType = istr.readInt(); this.FileName = istr.readString(); this.Remark = istr.readString(); } static get minWireSize() { return 8; } }; Slice$2.defineStruct(Dispatcher.StartSendBusFileT, true, true); Slice$2.defineSequence(Dispatcher, "StartSendBusFileSeqHelper", "Dispatcher.StartSendBusFileT", false); Dispatcher.StartSendBusInfoT = class { constructor(MsgUUID = "", KeyStationID = 0, KeyLineID = 0, KeyRailNum = "", Sender = "", senderName = "", WorkTypeValue = 0, ParentID = "", Descrip = "", SendState = 0, Files = null, Receivers = null) { this.MsgUUID = MsgUUID; this.KeyStationID = KeyStationID; this.KeyLineID = KeyLineID; this.KeyRailNum = KeyRailNum; this.Sender = Sender; this.senderName = senderName; this.WorkTypeValue = WorkTypeValue; this.ParentID = ParentID; this.Descrip = Descrip; this.SendState = SendState; this.Files = Files; this.Receivers = Receivers; } _write(ostr) { ostr.writeString(this.MsgUUID); ostr.writeInt(this.KeyStationID); ostr.writeInt(this.KeyLineID); ostr.writeString(this.KeyRailNum); ostr.writeString(this.Sender); ostr.writeString(this.senderName); ostr.writeInt(this.WorkTypeValue); ostr.writeString(this.ParentID); ostr.writeString(this.Descrip); ostr.writeInt(this.SendState); Dispatcher.StartSendBusFileSeqHelper.write(ostr, this.Files); Dispatcher.SendBusFileReceiveSeqHelper.write(ostr, this.Receivers); } _read(istr) { this.MsgUUID = istr.readString(); this.KeyStationID = istr.readInt(); this.KeyLineID = istr.readInt(); this.KeyRailNum = istr.readString(); this.Sender = istr.readString(); this.senderName = istr.readString(); this.WorkTypeValue = istr.readInt(); this.ParentID = istr.readString(); this.Descrip = istr.readString(); this.SendState = istr.readInt(); this.Files = Dispatcher.StartSendBusFileSeqHelper.read(istr); this.Receivers = Dispatcher.SendBusFileReceiveSeqHelper.read(istr); } static get minWireSize() { return 24; } }; Slice$2.defineStruct(Dispatcher.StartSendBusInfoT, true, true); Dispatcher.StartSendBusFileRT = class { constructor(MsgUUID = "", FileUUID = "", FileName = "", FilePath = "") { this.MsgUUID = MsgUUID; this.FileUUID = FileUUID; this.FileName = FileName; this.FilePath = FilePath; } _write(ostr) { ostr.writeString(this.MsgUUID); ostr.writeString(this.FileUUID); ostr.writeString(this.FileName); ostr.writeString(this.FilePath); } _read(istr) { this.MsgUUID = istr.readString(); this.FileUUID = istr.readString(); this.FileName = istr.readString(); this.FilePath = istr.readString(); } static get minWireSize() { return 4; } }; Slice$2.defineStruct(Dispatcher.StartSendBusFileRT, true, true); Slice$2.defineSequence(Dispatcher, "StartSendBusFileRTSeqHelper", "Dispatcher.StartSendBusFileRT", false); Dispatcher.SendBusInfoRT = class { constructor(MsgUUID = "", Sender = "", Files = null) { this.MsgUUID = MsgUUID; this.Sender = Sender; this.Files = Files; } _write(ostr) { ostr.writeString(this.MsgUUID); ostr.writeString(this.Sender); Dispatcher.StartSendBusFileRTSeqHelper.write(ostr, this.Files); } _read(istr) { this.MsgUUID = istr.readString(); this.Sender = istr.readString(); this.Files = Dispatcher.StartSendBusFileRTSeqHelper.read(istr); } static get minWireSize() { return 3; } }; Slice$2.defineStruct(Dispatcher.SendBusInfoRT, true, true); Dispatcher.SendBusInfoEndT = class { constructor(MsgUUID = "", SendState = 1) { this.MsgUUID = MsgUUID; this.SendState = SendState; } _write(ostr) { ostr.writeString(this.MsgUUID); ostr.writeInt(this.SendState); } _read(istr) { this.MsgUUID = istr.readString(); this.SendState = istr.readInt(); } static get minWireSize() { return 5; } }; Slice$2.defineStruct(Dispatcher.SendBusInfoEndT, true, true); Dispatcher.SendBusFileEndT = class { constructor(FileUUID = "", SendState = 1) { this.FileUUID = FileUUID; this.SendState = SendState; } _write(ostr) { ostr.writeString(this.FileUUID); ostr.writeInt(this.SendState); } _read(istr) { this.FileUUID = istr.readString(); this.SendState = istr.readInt(); } static get minWireSize() { return 5; } }; Slice$2.defineStruct(Dispatcher.SendBusFileEndT, true, true); Dispatcher.BusFileReceivedT = class { constructor(MsgUUID = "", receiver = "") { this.MsgUUID = MsgUUID; this.receiver = receiver; } _write(ostr) { ostr.writeString(this.MsgUUID); ostr.writeString(this.receiver); } _read(istr) { this.MsgUUID = istr.readString(); this.receiver = istr.readString(); } static get minWireSize() { return 2; } }; Slice$2.defineStruct(Dispatcher.BusFileReceivedT, true, true); Dispatcher.GetNotReceivedInfoT = class { constructor(maxnum = 10, receiver = "") { this.maxnum = maxnum; this.receiver = receiver; } _write(ostr) { ostr.writeInt(this.maxnum); ostr.writeString(this.receiver); } _read(istr) { this.maxnum = istr.readInt(); this.receiver = istr.readString(); } static get minWireSize() { return 5; } }; Slice$2.defineStruct(Dispatcher.GetNotReceivedInfoT, true, true); Dispatcher.GetNotReceivedInfoRT = class { constructor(Sendnum = 0, HaveOther = false) { this.Sendnum = Sendnum; this.HaveOther = HaveOther; } _write(ostr) { ostr.writeInt(this.Sendnum); ostr.writeBool(this.HaveOther); } _read(istr) { this.Sendnum = istr.readInt(); this.HaveOther = istr.readBool(); } static get minWireSize() { return 5; } }; Slice$2.defineStruct(Dispatcher.GetNotReceivedInfoRT, true, false); const iceC_Dispatcher_BusinessOP_ids = [ "::Dispatcher::BusinessOP", "::Ice::Object" ]; Dispatcher.BusinessOP = class extends ice.Ice.Object {}; Dispatcher.BusinessOPPrx = class extends ice.Ice.ObjectPrx {}; Slice$2.defineOperations(Dispatcher.BusinessOP, Dispatcher.BusinessOPPrx, iceC_Dispatcher_BusinessOP_ids, 0, { "opGetBusinessTypes": [, , , , ["Dispatcher.BusinessTypeRTSeqHelper"], [ [Dispatcher.Identity] ], , [ Dispatcher.Error ], , ], "opStartSendBusinessInfo": [, , , , [Dispatcher.SendBusInfoRT], [ [Dispatcher.Identity], [Dispatcher.StartSendBusInfoT] ], , [ Dispatcher.Error ], , ], "opStartSendFile": [, , , , [Dispatcher.StartSendBusFileRT], [ [Dispatcher.Identity], [Dispatcher.StartSendBusFileT] ], , [ Dispatcher.Error ], , ], "opSendBusinessInfoEnd": [, , , , [1], [ [Dispatcher.Identity], [Dispatcher.SendBusInfoEndT] ], , [ Dispatcher.Error ], , ], "opSendBusinessFileEnd": [, , , , [1], [ [Dispatcher.Identity], [Dispatcher.SendBusFileEndT] ], , [ Dispatcher.Error ], , ], "opChangeBusFileReceive": [, , , , [1], [ [Dispatcher.Identity], [Dispatcher.SendBusFileReceiveT] ], , [ Dispatcher.Error ], , ], "opBusFileReceived": [, , , , , [ [Dispatcher.Identity], [Dispatcher.BusFileReceivedT] ], , [ Dispatcher.Error ], , ], "opGetNotReceivedInfo": [, , , , [Dispatcher.GetNotReceivedInfoRT], [ [Dispatcher.Identity], [Dispatcher.GetNotReceivedInfoT] ], , [ Dispatcher.Error ], , ], "opDeleteBusInfo": [, , , , [1], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ] }); // const _ModuleRegistry$3 = ice.Ice._ModuleRegistry; const Slice$3 = ice.Ice.Slice; Dispatcher.PlayAudioEvT = class { constructor(cid = "", uuid = "", type = Dispatcher.PlayAudioType.PlayAudioTypeNone) { this.cid = cid; this.uuid = uuid; this.type = type; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.uuid); Dispatcher.PlayAudioType._write(ostr, this.type); } _read(istr) { this.cid = istr.readString(); this.uuid = istr.readString(); this.type = Dispatcher.PlayAudioType._read(istr); } static get minWireSize() { return 3; } }; Slice$3.defineStruct(Dispatcher.PlayAudioEvT, true, true); Dispatcher.CallDirect = Slice$3.defineEnum([ ['CallDirectNone', 0], ['CallDirectOut', 1], ['CallDirectIn', 2] ]); Dispatcher.SessionChangeT = class { constructor(cid = "", callingnum = "", callingname = "", othernum = "", othername = "", direction = Dispatcher.CallDirect.CallDirectNone, state = Dispatcher.CallState.CallStateNone, type = Dispatcher.CallType.CallTypeNone, level = 0, isVideo = Dispatcher.MediaType.MediaTypeNone, RoadParameters = "") { this.cid = cid; this.callingnum = callingnum; this.callingname = callingname; this.othernum = othernum; this.othername = othername; this.direction = direction; this.state = state; this.type = type; this.level = level; this.isVideo = isVideo; this.RoadParameters = RoadParameters; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.callingnum); ostr.writeString(this.callingname); ostr.writeString(this.othernum); ostr.writeString(this.othername); Dispatcher.CallDirect._write(ostr, this.direction); Dispatcher.CallState._write(ostr, this.state); Dispatcher.CallType._write(ostr, this.type); ostr.writeInt(this.level); Dispatcher.MediaType._write(ostr, this.isVideo); ostr.writeString(this.RoadParameters); } _read(istr) { this.cid = istr.readString(); this.callingnum = istr.readString(); this.callingname = istr.readString(); this.othernum = istr.readString(); this.othername = istr.readString(); this.direction = Dispatcher.CallDirect._read(istr); this.state = Dispatcher.CallState._read(istr); this.type = Dispatcher.CallType._read(istr); this.level = istr.readInt(); this.isVideo = Dispatcher.MediaType._read(istr); this.RoadParameters = istr.readString(); } static get minWireSize() { return 14; } }; Slice$3.defineStruct(Dispatcher.SessionChangeT, true, true); Slice$3.defineSequence(Dispatcher, "SessionChangeTSeqHelper", "Dispatcher.SessionChangeT", false); // const _ModuleRegistry$4 = ice.Ice._ModuleRegistry; const Slice$4 = ice.Ice.Slice; Dispatcher.CMStateChangeT = class { constructor(cid = "", employeeid = "", state = Dispatcher.CallState.CallStateNone, stateDecorate = "", name = "", type = 8) { this.cid = cid; this.employeeid = employeeid; this.state = state; this.stateDecorate = stateDecorate; this.name = name; this.type = type; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.employeeid); Dispatcher.CallState._write(ostr, this.state); ostr.writeString(this.stateDecorate); ostr.writeString(this.name); ostr.writeInt(this.type); } _read(istr) { this.cid = istr.readString(); this.employeeid = istr.readString(); this.state = Dispatcher.CallState._read(istr); this.stateDecorate = istr.readString(); this.name = istr.readString(); this.type = istr.readInt(); } static get minWireSize() { return 9; } }; Slice$4.defineStruct(Dispatcher.CMStateChangeT, true, true); Dispatcher.CallChangeT = class { constructor(employeeid = "", state = Dispatcher.CallState.CallStateNone, othername = "", othernumber = "", DNSprefix = "", islocal = 0) { this.employeeid = employeeid; this.state = state; this.othername = othername; this.othernumber = othernumber; this.DNSprefix = DNSprefix; this.islocal = islocal; } _write(ostr) { ostr.writeString(this.employeeid); Dispatcher.CallState._write(ostr, this.state); ostr.writeString(this.othername); ostr.writeString(this.othernumber); ostr.writeString(this.DNSprefix); ostr.writeInt(this.islocal); } _read(istr) { this.employeeid = istr.readString(); this.state = Dispatcher.CallState._read(istr); this.othername = istr.readString(); this.othernumber = istr.readString(); this.DNSprefix = istr.readString(); this.islocal = istr.readInt(); } static get minWireSize() { return 9; } }; Slice$4.defineStruct(Dispatcher.CallChangeT, true, true); Dispatcher.SessionChange1T = class { constructor(cid = "", callingnum = "", callingname = "", othernum = "", othername = "", direction = Dispatcher.CallDirect.CallDirectNone, state = Dispatcher.CallState.CallStateNone, type = Dispatcher.CallType.CallTypeNone, level = 0, isVideo = Dispatcher.MediaType.MediaTypeNone, RoadParameters = "", othermsg = "") { this.cid = cid; this.callingnum = callingnum; this.callingname = callingname; this.othernum = othernum; this.othername = othername; this.direction = direction; this.state = state; this.type = type; this.level = level; this.isVideo = isVideo; this.RoadParameters = RoadParameters; this.othermsg = othermsg; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.callingnum); ostr.writeString(this.callingname); ostr.writeString(this.othernum); ostr.writeString(this.othername); Dispatcher.CallDirect._write(ostr, this.direction); Dispatcher.CallState._write(ostr, this.state); Dispatcher.CallType._write(ostr, this.type); ostr.writeInt(this.level); Dispatcher.MediaType._write(ostr, this.isVideo); ostr.writeString(this.RoadParameters); ostr.writeString(this.othermsg); } _read(istr) { this.cid = istr.readString(); this.callingnum = istr.readString(); this.callingname = istr.readString(); this.othernum = istr.readString(); this.othername = istr.readString(); this.direction = Dispatcher.CallDirect._read(istr); this.state = Dispatcher.CallState._read(istr); this.type = Dispatcher.CallType._read(istr); this.level = istr.readInt(); this.isVideo = Dispatcher.MediaType._read(istr); this.RoadParameters = istr.readString(); this.othermsg = istr.readString(); } static get minWireSize() { return 15; } }; Slice$4.defineStruct(Dispatcher.SessionChange1T, true, true); const iceC_Dispatcher_CallingCB_ids = [ "::Dispatcher::CallingCB", "::Ice::Object" ]; Dispatcher.CallingCB = class extends ice.Ice.Object {}; Dispatcher.CallingCBPrx = class extends ice.Ice.ObjectPrx {}; Slice$4.defineOperations(Dispatcher.CallingCB, Dispatcher.CallingCBPrx, iceC_Dispatcher_CallingCB_ids, 0, { "IFCNotifySessionStateEvt": [, 2, 2, , , [ [Dispatcher.SessionChangeT] ], , , , ], "IFCNotifySessionStateEvt2": [, 2, 2, , , [ [Dispatcher.SessionChange1T] ], , , , ], "IFCNotifyConfMemberStateEvt": [, 2, 2, , , [ [Dispatcher.CMStateChangeT] ], , , , ], "IFCNotifyCallStateEvt": [, 2, 2, , , [ [Dispatcher.CallChangeT] ], , , , ], "IFCNotifyAudioPlayStateEvt": [, 2, 2, , , [ [Dispatcher.PlayAudioEvT] ], , , , ] }); const iceC_Dispatcher_CallingCBSub_ids = [ "::Dispatcher::CallingCBSub", "::Ice::Object" ]; Dispatcher.CallingCBSub = class extends ice.Ice.Object {}; Dispatcher.CallingCBSubPrx = class extends ice.Ice.ObjectPrx {}; Slice$4.defineOperations(Dispatcher.CallingCBSub, Dispatcher.CallingCBSubPrx, iceC_Dispatcher_CallingCBSub_ids, 0); // const _ModuleRegistry$5 = ice.Ice._ModuleRegistry; const Slice$5 = ice.Ice.Slice; Dispatcher.NegoTransferT = class { constructor(number = "", call1 = "", call2 = "", cid1 = "", cid2 = "") { this.number = number; this.call1 = call1; this.call2 = call2; this.cid1 = cid1; this.cid2 = cid2; } _write(ostr) { ostr.writeString(this.number); ostr.writeString(this.call1); ostr.writeString(this.call2); ostr.writeString(this.cid1); ostr.writeString(this.cid2); } _read(istr) { this.number = istr.readString(); this.call1 = istr.readString(); this.call2 = istr.readString(); this.cid1 = istr.readString(); this.cid2 = istr.readString(); } static get minWireSize() { return 5; } }; Slice$5.defineStruct(Dispatcher.NegoTransferT, true, true); Dispatcher.NegoTransferRT = class { constructor(cid = "") { this.cid = cid; } _write(ostr) { ostr.writeString(this.cid); } _read(istr) { this.cid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$5.defineStruct(Dispatcher.NegoTransferRT, true, true); Dispatcher.PlayAudioT = class { constructor(fname = "", empid = "", cid = "", state = Dispatcher.PlayAudioType.PlayAudioTypeNone, uuid = "") { this.fname = fname; this.empid = empid; this.cid = cid; this.state = state; this.uuid = uuid; } _write(ostr) { ostr.writeString(this.fname); ostr.writeString(this.empid); ostr.writeString(this.cid); Dispatcher.PlayAudioType._write(ostr, this.state); ostr.writeString(this.uuid); } _read(istr) { this.fname = istr.readString(); this.empid = istr.readString(); this.cid = istr.readString(); this.state = Dispatcher.PlayAudioType._read(istr); this.uuid = istr.readString(); } static get minWireSize() { return 5; } }; Slice$5.defineStruct(Dispatcher.PlayAudioT, true, true); Dispatcher.PlayAudioRT = class { constructor(code = 0) { this.code = code; } _write(ostr) { ostr.writeInt(this.code); } _read(istr) { this.code = istr.readInt(); } static get minWireSize() { return 4; } }; Slice$5.defineStruct(Dispatcher.PlayAudioRT, true, false); Dispatcher.CallCommonT = class { constructor(cid = "", caller = "", called = "") { this.cid = cid; this.caller = caller; this.called = called; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.caller); ostr.writeString(this.called); } _read(istr) { this.cid = istr.readString(); this.caller = istr.readString(); this.called = istr.readString(); } static get minWireSize() { return 3; } }; Slice$5.defineStruct(Dispatcher.CallCommonT, true, true); Dispatcher.CallCommonRET = class { constructor(cid = "", caller = "", callee = "") { this.cid = cid; this.caller = caller; this.callee = callee; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.caller); ostr.writeString(this.callee); } _read(istr) { this.cid = istr.readString(); this.caller = istr.readString(); this.callee = istr.readString(); } static get minWireSize() { return 3; } }; Slice$5.defineStruct(Dispatcher.CallCommonRET, true, true); Slice$5.defineSequence(Dispatcher, "CallCommonRESeqHelper", "Dispatcher.CallCommonRET", false); Dispatcher.CallCommonRT = class { constructor(seq = null) { this.seq = seq; } _write(ostr) { Dispatcher.CallCommonRESeqHelper.write(ostr, this.seq); } _read(istr) { this.seq = Dispatcher.CallCommonRESeqHelper.read(istr); } static get minWireSize() { return 1; } }; Slice$5.defineStruct(Dispatcher.CallCommonRT, true, true); Dispatcher.SpeakerT = class { constructor(cid = "", employeeid = "", speakertypea = Dispatcher.SpeakType.SpeakTypeNone) { this.cid = cid; this.employeeid = employeeid; this.speakertypea = speakertypea; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.employeeid); Dispatcher.SpeakType._write(ostr, this.speakertypea); } _read(istr) { this.cid = istr.readString(); this.employeeid = istr.readString(); this.speakertypea = Dispatcher.SpeakType._read(istr); } static get minWireSize() { return 3; } }; Slice$5.defineStruct(Dispatcher.SpeakerT, true, true); Dispatcher.SpeakerRT = class { constructor(code = 0) { this.code = code; } _write(ostr) { ostr.writeInt(this.code); } _read(istr) { this.code = istr.readInt(); } static get minWireSize() { return 4; } }; Slice$5.defineStruct(Dispatcher.SpeakerRT, true, false); Dispatcher.HearT = class { constructor(cid = "", number = "", hear = Dispatcher.HearType.HearTypeNone) { this.cid = cid; this.number = number; this.hear = hear; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.number); Dispatcher.HearType._write(ostr, this.hear); } _read(istr) { this.cid = istr.readString(); this.number = istr.readString(); this.hear = Dispatcher.HearType._read(istr); } static get minWireSize() { return 3; } }; Slice$5.defineStruct(Dispatcher.HearT, true, true); Dispatcher.HearRT = class { constructor(code = 0) { this.code = code; } _write(ostr) { ostr.writeInt(this.code); } _read(istr) { this.code = istr.readInt(); } static get minWireSize() { return 4; } }; Slice$5.defineStruct(Dispatcher.HearRT, true, false); Dispatcher.MuteLocalTrackT = class { constructor(cid = "", number = "", mute = false) { this.cid = cid; this.number = number; this.mute = mute; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.number); ostr.writeBool(this.mute); } _read(istr) { this.cid = istr.readString(); this.number = istr.readString(); this.mute = istr.readBool(); } static get minWireSize() { return 3; } }; Slice$5.defineStruct(Dispatcher.MuteLocalTrackT, true, true); Dispatcher.ForceEndConfeT = class { constructor(cid = "", employeeid = "") { this.cid = cid; this.employeeid = employeeid; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.employeeid); } _read(istr) { this.cid = istr.readString(); this.employeeid = istr.readString(); } static get minWireSize() { return 2; } }; Slice$5.defineStruct(Dispatcher.ForceEndConfeT, true, true); Dispatcher.HoldT = class { constructor(cid = "", htype = Dispatcher.HoldType.HoldTypeNone) { this.cid = cid; this.htype = htype; } _write(ostr) { ostr.writeString(this.cid); Dispatcher.HoldType._write(ostr, this.htype); } _read(istr) { this.cid = istr.readString(); this.htype = Dispatcher.HoldType._read(istr); } static get minWireSize() { return 2; } }; Slice$5.defineStruct(Dispatcher.HoldT, true, true); Dispatcher.HoldRT = class { constructor(cid = "") { this.cid = cid; } _write(ostr) { ostr.writeString(this.cid); } _read(istr) { this.cid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$5.defineStruct(Dispatcher.HoldRT, true, true); Dispatcher.HangupT = class { constructor(cid = "") { this.cid = cid; } _write(ostr) { ostr.writeString(this.cid); } _read(istr) { this.cid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$5.defineStruct(Dispatcher.HangupT, true, true); Dispatcher.HangupT1 = class { constructor(cid = "", member = "") { this.cid = cid; this.member = member; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.member); } _read(istr) { this.cid = istr.readString(); this.member = istr.readString(); } static get minWireSize() { return 2; } }; Slice$5.defineStruct(Dispatcher.HangupT1, true, true); Dispatcher.HangupRT = class { constructor(cid = "") { this.cid = cid; } _write(ostr) { ostr.writeString(this.cid); } _read(istr) { this.cid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$5.defineStruct(Dispatcher.HangupRT, true, true); Dispatcher.CalleeT = class { constructor(employeeid = "") { this.employeeid = employeeid; } _write(ostr) { ostr.writeString(this.employeeid); } _read(istr) { this.employeeid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$5.defineStruct(Dispatcher.CalleeT, true, true); Slice$5.defineSequence(Dispatcher, "CalleeSeqHelper", "Dispatcher.CalleeT", false); Dispatcher.CreateConfT = class { constructor(member = null, sessname = "", sessnum = "", caller = "", ctype = Dispatcher.CallType.CallTypeNone, isVideo = Dispatcher.MediaType.MediaTypeNone) { this.member = member; this.sessname = sessname; this.sessnum = sessnum; this.caller = caller; this.ctype = ctype; this.isVideo = isVideo; } _write(ostr) { Dispatcher.CalleeSeqHelper.write(ostr, this.member); ostr.writeString(this.sessname); ostr.writeString(this.sessnum); ostr.writeString(this.caller); Dispatcher.CallType._write(ostr, this.ctype); Dispatcher.MediaType._write(ostr, this.isVideo); } _read(istr) { this.member = Dispatcher.CalleeSeqHelper.read(istr); this.sessname = istr.readString(); this.sessnum = istr.readString(); this.caller = istr.readString(); this.ctype = Dispatcher.CallType._read(istr); this.isVideo = Dispatcher.MediaType._read(istr); } static get minWireSize() { return 6; } }; Slice$5.defineStruct(Dispatcher.CreateConfT, true, true); Dispatcher.CreateMcuConfT = class { constructor(member = null, sessname = "", sessnum = "", caller = "", ctype = Dispatcher.CallType.CallTypeNone, isVideo = Dispatcher.MediaType.MediaTypeNone, isMcuCall = false) { this.member = member; this.sessname = sessname; this.sessnum = sessnum; this.caller = caller; this.ctype = ctype; this.isVideo = isVideo; this.isMcuCall = isMcuCall; } _write(ostr) { Dispatcher.CalleeSeqHelper.write(ostr, this.member); ostr.writeString(this.sessname); ostr.writeString(this.sessnum); ostr.writeString(this.caller); Dispatcher.CallType._write(ostr, this.ctype); Dispatcher.MediaType._write(ostr, this.isVideo); ostr.writeBool(this.isMcuCall); } _read(istr) { this.member = Dispatcher.CalleeSeqHelper.read(istr); this.sessname = istr.readString(); this.sessnum = istr.readString(); this.caller = istr.readString(); this.ctype = Dispatcher.CallType._read(istr); this.isVideo = Dispatcher.MediaType._read(istr); this.isMcuCall = istr.readBool(); } static get minWireSize() { return 7; } }; Slice$5.defineStruct(Dispatcher.CreateMcuConfT, true, true); Dispatcher.CreateMcuConf1T = class { constructor(member = null, sessname = "", sessnum = "", caller = "", ctype = Dispatcher.CallType.CallTypeNone, isVideo = Dispatcher.MediaType.MediaTypeNone, isMcuCall = false, defaultsdp = "") { this.member = member; this.sessname = sessname; this.sessnum = sessnum; this.caller = caller; this.ctype = ctype; this.isVideo = isVideo; this.isMcuCall = isMcuCall; this.defaultsdp = defaultsdp; } _write(ostr) { Dispatcher.CalleeSeqHelper.write(ostr, this.member); ostr.writeString(this.sessname); ostr.writeString(this.sessnum); ostr.writeString(this.caller); Dispatcher.CallType._write(ostr, this.ctype); Dispatcher.MediaType._write(ostr, this.isVideo); ostr.writeBool(this.isMcuCall); ostr.writeString(this.defaultsdp); } _read(istr) { this.member = Dispatcher.CalleeSeqHelper.read(istr); this.sessname = istr.readString(); this.sessnum = istr.readString(); this.caller = istr.readString(); this.ctype = Dispatcher.CallType._read(istr); this.isVideo = Dispatcher.MediaType._read(istr); this.isMcuCall = istr.readBool(); this.defaultsdp = istr.readString(); } static get minWireSize() { return 8; } }; Slice$5.defineStruct(Dispatcher.CreateMcuConf1T, true, true); Dispatcher.CreateConf1T = class { constructor(member = null, sessname = "", sessnum = "", caller = "", ctype = Dispatcher.CallType.CallTypeNone, isVideo = Dispatcher.MediaType.MediaTypeNone, isMcuCall = false, defaultsdp = "") { this.member = member; this.sessname = sessname; this.sessnum = sessnum; this.caller = caller; this.ctype = ctype; this.isVideo = isVideo; this.isMcuCall = isMcuCall; this.defaultsdp = defaultsdp; } _write(ostr) { Dispatcher.CalleeSeqHelper.write(ostr, this.member); ostr.writeString(this.sessname); ostr.writeString(this.sessnum); ostr.writeString(this.caller); Dispatcher.CallType._write(ostr, this.ctype); Dispatcher.MediaType._write(ostr, this.isVideo); ostr.writeBool(this.isMcuCall); ostr.writeString(this.defaultsdp); } _read(istr) { this.member = Dispatcher.CalleeSeqHelper.read(istr); this.sessname = istr.readString(); this.sessnum = istr.readString(); this.caller = istr.readString(); this.ctype = Dispatcher.CallType._read(istr); this.isVideo = Dispatcher.MediaType._read(istr); this.isMcuCall = istr.readBool(); this.defaultsdp = istr.readString(); } static get minWireSize() { return 8; } }; Slice$5.defineStruct(Dispatcher.CreateConf1T, true, true); Dispatcher.CreateConfRT = class { constructor(sessnum = "", cid = "", empid = "") { this.sessnum = sessnum; this.cid = cid; this.empid = empid; } _write(ostr) { ostr.writeString(this.sessnum); ostr.writeString(this.cid); ostr.writeString(this.empid); } _read(istr) { this.sessnum = istr.readString(); this.cid = istr.readString(); this.empid = istr.readString(); } static get minWireSize() { return 3; } }; Slice$5.defineStruct(Dispatcher.CreateConfRT, true, true); Dispatcher.AddMemberT = class { constructor(cid = "", number = "", astype = Dispatcher.AnswerType.AnswerTypeNone) { this.cid = cid; this.number = number; this.astype = astype; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.number); Dispatcher.AnswerType._write(ostr, this.astype); } _read(istr) { this.cid = istr.readString(); this.number = istr.readString(); this.astype = Dispatcher.AnswerType._read(istr); } static get minWireSize() { return 3; } }; Slice$5.defineStruct(Dispatcher.AddMemberT, true, true); Dispatcher.AddMemberRT = class { constructor(cid = "", empid = "") { this.cid = cid; this.empid = empid; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.empid); } _read(istr) { this.cid = istr.readString(); this.empid = istr.readString(); } static get minWireSize() { return 2; } }; Slice$5.defineStruct(Dispatcher.AddMemberRT, true, true); Dispatcher.DelMemberT = class { constructor(cid = "", number = "") { this.cid = cid; this.number = number; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.number); } _read(istr) { this.cid = istr.readString(); this.number = istr.readString(); } static get minWireSize() { return 2; } }; Slice$5.defineStruct(Dispatcher.DelMemberT, true, true); Dispatcher.DelMemberRT = class { constructor(cid = "", empid = "") { this.cid = cid; this.empid = empid; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.empid); } _read(istr) { this.cid = istr.readString(); this.empid = istr.readString(); } static get minWireSize() { return 2; } }; Slice$5.defineStruct(Dispatcher.DelMemberRT, true, true); Dispatcher.AllCallMemberT = class { constructor(sid = "", cid = "") { this.sid = sid; this.cid = cid; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.cid); } _read(istr) { this.sid = istr.readString(); this.cid = istr.readString(); } static get minWireSize() { return 2; } }; Slice$5.defineStruct(Dispatcher.AllCallMemberT, true, true); Dispatcher.AllCallMemberRT = class { constructor(cid = "", employeeid = "", name = "", type = 8, state = Dispatcher.CallState.CallStateNone, stateDecorate = "") { this.cid = cid; this.employeeid = employeeid; this.name = name; this.type = type; this.state = state; this.stateDecorate = stateDecorate; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.employeeid); ostr.writeString(this.name); ostr.writeInt(this.type); Dispatcher.CallState._write(ostr, this.state); ostr.writeString(this.stateDecorate); } _read(istr) { this.cid = istr.readString(); this.employeeid = istr.readString(); this.name = istr.readString(); this.type = istr.readInt(); this.state = Dispatcher.CallState._read(istr); this.stateDecorate = istr.readString(); } static get minWireSize() { return 9; } }; Slice$5.defineStruct(Dispatcher.AllCallMemberRT, true, true); Slice$5.defineSequence(Dispatcher, "AllCallMemberRSeqHelper", "Dispatcher.AllCallMemberRT", false); Dispatcher.PullQueueCallT = class { constructor(cid = "", caller = "") { this.cid = cid; this.caller = caller; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.caller); } _read(istr) { this.cid = istr.readString(); this.caller = istr.readString(); } static get minWireSize() { return 2; } }; Slice$5.defineStruct(Dispatcher.PullQueueCallT, true, true); Dispatcher.PushCallToQueueT = class { constructor(cid = "", RoadParameters = "") { this.cid = cid; this.RoadParameters = RoadParameters; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.RoadParameters); } _read(istr) { this.cid = istr.readString(); this.RoadParameters = istr.readString(); } static get minWireSize() { return 2; } }; Slice$5.defineStruct(Dispatcher.PushCallToQueueT, true, true); Dispatcher.PushCallToQueueT1 = class { constructor(cid = "", member = "", RoadParameters = "") { this.cid = cid; this.member = member; this.RoadParameters = RoadParameters; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.member); ostr.writeString(this.RoadParameters); } _read(istr) { this.cid = istr.readString(); this.member = istr.readString(); this.RoadParameters = istr.readString(); } static get minWireSize() { return 3; } }; Slice$5.defineStruct(Dispatcher.PushCallToQueueT1, true, true); Dispatcher.GetAllSessionT = class { constructor(employeeid = "") { this.employeeid = employeeid; } _write(ostr) { ostr.writeString(this.employeeid); } _read(istr) { this.employeeid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$5.defineStruct(Dispatcher.GetAllSessionT, true, true); Dispatcher.GetAllSession1T = class { constructor(employeeid = "", cType = Dispatcher.CallType.CallTypeNone) { this.employeeid = employeeid; this.cType = cType; } _write(ostr) { ostr.writeString(this.employeeid); Dispatcher.CallType._write(ostr, this.cType); } _read(istr) { this.employeeid = istr.readString(); this.cType = Dispatcher.CallType._read(istr); } static get minWireSize() { return 2; } }; Slice$5.defineStruct(Dispatcher.GetAllSession1T, true, true); Dispatcher.SendDTMFbyCidT = class { constructor(cid = "", member = "", strdtmf = "") { this.cid = cid; this.member = member; this.strdtmf = strdtmf; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.member); ostr.writeString(this.strdtmf); } _read(istr) { this.cid = istr.readString(); this.member = istr.readString(); this.strdtmf = istr.readString(); } static get minWireSize() { return 3; } }; Slice$5.defineStruct(Dispatcher.SendDTMFbyCidT, true, true); Dispatcher.OrderDetailT = class { constructor(number = "", index = 0, ringtime = 30) { this.number = number; this.index = index; this.ringtime = ringtime; } _write(ostr) { ostr.writeString(this.number); ostr.writeInt(this.index); ostr.writeInt(this.ringtime); } _read(istr) { this.number = istr.readString(); this.index = istr.readInt(); this.ringtime = istr.readInt(); } static get minWireSize() { return 9; } }; Slice$5.defineStruct(Dispatcher.OrderDetailT, true, true); Slice$5.defineSequence(Dispatcher, "OrderDetailSeqHelper", "Dispatcher.OrderDetailT", false); Dispatcher.OrderCalledT = class { constructor(called = "", details = null) { this.called = called; this.details = details; } _write(ostr) { ostr.writeString(this.called); Dispatcher.OrderDetailSeqHelper.write(ostr, this.details); } _read(istr) { this.called = istr.readString(); this.details = Dispatcher.OrderDetailSeqHelper.read(istr); } static get minWireSize() { return 2; } }; Slice$5.defineStruct(Dispatcher.OrderCalledT, true, true); Slice$5.defineSequence(Dispatcher, "OrderCalledSeqHelper", "Dispatcher.OrderCalledT", false); Dispatcher.CalledOrderT = class { constructor(calleds = null, sessname = "", sessnum = "", caller = "", ctype = Dispatcher.CallType.CallTypeNone, isVideo = Dispatcher.MediaType.MediaTypeNone) { this.calleds = calleds; this.sessname = sessname; this.sessnum = sessnum; this.caller = caller; this.ctype = ctype; this.isVideo = isVideo; } _write(ostr) { Dispatcher.OrderCalledSeqHelper.write(ostr, this.calleds); ostr.writeString(this.sessname); ostr.writeString(this.sessnum); ostr.writeString(this.caller); Dispatcher.CallType._write(ostr, this.ctype); Dispatcher.MediaType._write(ostr, this.isVideo); } _read(istr) { this.calleds = Dispatcher.OrderCalledSeqHelper.read(istr); this.sessname = istr.readString(); this.sessnum = istr.readString(); this.caller = istr.readString(); this.ctype = Dispatcher.CallType._read(istr); this.isVideo = Dispatcher.MediaType._read(istr); } static get minWireSize() { return 6; } }; Slice$5.defineStruct(Dispatcher.CalledOrderT, true, true); Dispatcher.CalledOrderRT = class { constructor(sessnum = "", cid = "", empid = "") { this.sessnum = sessnum; this.cid = cid; this.empid = empid; } _write(ostr) { ostr.writeString(this.sessnum); ostr.writeString(this.cid); ostr.writeString(this.empid); } _read(istr) { this.sessnum = istr.readString(); this.cid = istr.readString(); this.empid = istr.readString(); } static get minWireSize() { return 3; } }; Slice$5.defineStruct(Dispatcher.CalledOrderRT, true, true); Dispatcher.AddMemberByCallOrderT = class { constructor(cid = "", number = "", astype = Dispatcher.AnswerType.AnswerTypeNone, details = null) { this.cid = cid; this.number = number; this.astype = astype; this.details = details; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.number); Dispatcher.AnswerType._write(ostr, this.astype); Dispatcher.OrderDetailSeqHelper.write(ostr, this.details); } _read(istr) { this.cid = istr.readString(); this.number = istr.readString(); this.astype = Dispatcher.AnswerType._read(istr); this.details = Dispatcher.OrderDetailSeqHelper.read(istr); } static get minWireSize() { return 4; } }; Slice$5.defineStruct(Dispatcher.AddMemberByCallOrderT, true, true); Dispatcher.ReCallDetailT = class { constructor(number = "", callnum = 0) { this.number = number; this.callnum = callnum; } _write(ostr) { ostr.writeString(this.number); ostr.writeInt(this.callnum); } _read(istr) { this.number = istr.readString(); this.callnum = istr.readInt(); } static get minWireSize() { return 5; } }; Slice$5.defineStruct(Dispatcher.ReCallDetailT, true, true); Slice$5.defineSequence(Dispatcher, "ReCallDetailSeqHelper", "Dispatcher.ReCallDetailT", false); Dispatcher.SetReCallNumberT = class { constructor(cid = "", details = null) { this.cid = cid; this.details = details; } _write(ostr) { ostr.writeString(this.cid); Dispatcher.ReCallDetailSeqHelper.write(ostr, this.details); } _read(istr) { this.cid = istr.readString(); this.details = Dispatcher.ReCallDetailSeqHelper.read(istr); } static get minWireSize() { return 2; } }; Slice$5.defineStruct(Dispatcher.SetReCallNumberT, true, true); Dispatcher.AllCallMemberRT1 = class { constructor(cid = "", employeeid = "", name = "", type = 8, state = Dispatcher.CallState.CallStateNone, stateDecorate = "", level = 10, IsReCall = false, ReCallNum = -1) { this.cid = cid; this.employeeid = employeeid; this.name = name; this.type = type; this.state = state; this.stateDecorate = stateDecorate; this.level = level; this.IsReCall = IsReCall; this.ReCallNum = ReCallNum; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.employeeid); ostr.writeString(this.name); ostr.writeInt(this.type); Dispatcher.CallState._write(ostr, this.state); ostr.writeString(this.stateDecorate); ostr.writeInt(this.level); ostr.writeBool(this.IsReCall); ostr.writeInt(this.ReCallNum); } _read(istr) { this.cid = istr.readString(); this.employeeid = istr.readString(); this.name = istr.readString(); this.type = istr.readInt(); this.state = Dispatcher.CallState._read(istr); this.stateDecorate = istr.readString(); this.level = istr.readInt(); this.IsReCall = istr.readBool(); this.ReCallNum = istr.readInt(); } static get minWireSize() { return 18; } }; Slice$5.defineStruct(Dispatcher.AllCallMemberRT1, true, true); Slice$5.defineSequence(Dispatcher, "AllCallMemberRSeq1Helper", "Dispatcher.AllCallMemberRT1", false); Dispatcher.SessionJoinT = class { constructor(cid = "") { this.cid = cid; } _write(ostr) { ostr.writeString(this.cid); } _read(istr) { this.cid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$5.defineStruct(Dispatcher.SessionJoinT, true, true); Slice$5.defineSequence(Dispatcher, "SessionJoinSeqHelper", "Dispatcher.SessionJoinT", false); Dispatcher.CreateSOSCallT = class { constructor(member = null, sessname = "", sessnum = "", caller = "", isVideo = Dispatcher.MediaType.MediaTypeNone) { this.member = member; this.sessname = sessname; this.sessnum = sessnum; this.caller = caller; this.isVideo = isVideo; } _write(ostr) { Dispatcher.CalleeSeqHelper.write(ostr, this.member); ostr.writeString(this.sessname); ostr.writeString(this.sessnum); ostr.writeString(this.caller); Dispatcher.MediaType._write(ostr, this.isVideo); } _read(istr) { this.member = Dispatcher.CalleeSeqHelper.read(istr); this.sessname = istr.readString(); this.sessnum = istr.readString(); this.caller = istr.readString(); this.isVideo = Dispatcher.MediaType._read(istr); } static get minWireSize() { return 5; } }; Slice$5.defineStruct(Dispatcher.CreateSOSCallT, true, true); Dispatcher.UploadVideoCallT = class { constructor(member = null, sessname = "", sessnum = "", caller = "", isVideo = Dispatcher.MediaType.MediaTypeNone) { this.member = member; this.sessname = sessname; this.sessnum = sessnum; this.caller = caller; this.isVideo = isVideo; } _write(ostr) { Dispatcher.CalleeSeqHelper.write(ostr, this.member); ostr.writeString(this.sessname); ostr.writeString(this.sessnum); ostr.writeString(this.caller); Dispatcher.MediaType._write(ostr, this.isVideo); } _read(istr) { this.member = Dispatcher.CalleeSeqHelper.read(istr); this.sessname = istr.readString(); this.sessnum = istr.readString(); this.caller = istr.readString(); this.isVideo = Dispatcher.MediaType._read(istr); } static get minWireSize() { return 5; } }; Slice$5.defineStruct(Dispatcher.UploadVideoCallT, true, true); Dispatcher.TransferVideoT = class { constructor(sessname = "", sessnum = "", srccid = "", srcnumber = "", calleds = null) { this.sessname = sessname; this.sessnum = sessnum; this.srccid = srccid; this.srcnumber = srcnumber; this.calleds = calleds; } _write(ostr) { ostr.writeString(this.sessname); ostr.writeString(this.sessnum); ostr.writeString(this.srccid); ostr.writeString(this.srcnumber); Dispatcher.OrderCalledSeqHelper.write(ostr, this.calleds); } _read(istr) { this.sessname = istr.readString(); this.sessnum = istr.readString(); this.srccid = istr.readString(); this.srcnumber = istr.readString(); this.calleds = Dispatcher.OrderCalledSeqHelper.read(istr); } static get minWireSize() { return 5; } }; Slice$5.defineStruct(Dispatcher.TransferVideoT, true, true); Dispatcher.TransferVideoToMCUT = class { constructor(sessname = "", sessnum = "", srccid = "", srcnumber = "", defaultcode = "", calleds = null) { this.sessname = sessname; this.sessnum = sessnum; this.srccid = srccid; this.srcnumber = srcnumber; this.defaultcode = defaultcode; this.calleds = calleds; } _write(ostr) { ostr.writeString(this.sessname); ostr.writeString(this.sessnum); ostr.writeString(this.srccid); ostr.writeString(this.srcnumber); ostr.writeString(this.defaultcode); Dispatcher.OrderCalledSeqHelper.write(ostr, this.calleds); } _read(istr) { this.sessname = istr.readString(); this.sessnum = istr.readString(); this.srccid = istr.readString(); this.srcnumber = istr.readString(); this.defaultcode = istr.readString(); this.calleds = Dispatcher.OrderCalledSeqHelper.read(istr); } static get minWireSize() { return 6; } }; Slice$5.defineStruct(Dispatcher.TransferVideoToMCUT, true, true); Dispatcher.TransferVideoRT = class { constructor(newcid = "") { this.newcid = newcid; } _write(ostr) { ostr.writeString(this.newcid); } _read(istr) { this.newcid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$5.defineStruct(Dispatcher.TransferVideoRT, true, true); Dispatcher.AddMemberT1 = class { constructor(cid = "", number = "", astype = Dispatcher.AnswerType.AnswerTypeNone, speakertypea = Dispatcher.SpeakType.SpeakTypeNone, hear = Dispatcher.HearType.HearTypeNone, RoadParameters = "", details = null) { this.cid = cid; this.number = number; this.astype = astype; this.speakertypea = speakertypea; this.hear = hear; this.RoadParameters = RoadParameters; this.details = details; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.number); Dispatcher.AnswerType._write(ostr, this.astype); Dispatcher.SpeakType._write(ostr, this.speakertypea); Dispatcher.HearType._write(ostr, this.hear); ostr.writeString(this.RoadParameters); Dispatcher.OrderDetailSeqHelper.write(ostr, this.details); } _read(istr) { this.cid = istr.readString(); this.number = istr.readString(); this.astype = Dispatcher.AnswerType._read(istr); this.speakertypea = Dispatcher.SpeakType._read(istr); this.hear = Dispatcher.HearType._read(istr); this.RoadParameters = istr.readString(); this.details = Dispatcher.OrderDetailSeqHelper.read(istr); } static get minWireSize() { return 7; } }; Slice$5.defineStruct(Dispatcher.AddMemberT1, true, true); const iceC_Dispatcher_CallingOP_ids = [ "::Dispatcher::CallingOP", "::Ice::Object" ]; Dispatcher.CallingOP = class extends ice.Ice.Object {}; Dispatcher.CallingOPPrx = class extends ice.Ice.ObjectPrx {}; Slice$5.defineOperations(Dispatcher.CallingOP, Dispatcher.CallingOPPrx, iceC_Dispatcher_CallingOP_ids, 0, { "IFCReqNegoTransfer": [, , , , [Dispatcher.NegoTransferRT], [ [Dispatcher.Identity], [Dispatcher.NegoTransferT] ], , [ Dispatcher.Error ], , ], "IFCReqPlayAudio": [, , , , [Dispatcher.PlayAudioRT], [ [Dispatcher.Identity], [Dispatcher.PlayAudioT] ], , [ Dispatcher.Error ], , ], "IFCReqCallPickup": [, , , , [Dispatcher.CallCommonRT], [ [Dispatcher.Identity], [Dispatcher.CallCommonT] ], , [ Dispatcher.Error ], , ], "IFCReqForbiddenTalk": [, , , , [Dispatcher.SpeakerRT], [ [Dispatcher.Identity], [Dispatcher.SpeakerT] ], , [ Dispatcher.Error ], , ], "IFCReqForbiddenHear": [, , , , [Dispatcher.HearRT], [ [Dispatcher.Identity], [Dispatcher.HearT] ], , [ Dispatcher.Error ], , ], "IFCReqMuteLocalMic": [, , , , [1], [ [Dispatcher.Identity], [Dispatcher.MuteLocalTrackT] ], , [ Dispatcher.Error ], , ], "IFCReqMuteLocalCamera": [, , , , [1], [ [Dispatcher.Identity], [Dispatcher.MuteLocalTrackT] ], , [ Dispatcher.Error ], , ], "IFCReqEndConf": [, , , , [Dispatcher.CommonRequestT], [ [Dispatcher.Identity], [Dispatcher.ForceEndConfeT] ], , [ Dispatcher.Error ], , ], "IFCReqForceBreak": [, , , , [Dispatcher.CallCommonRT], [ [Dispatcher.Identity], [Dispatcher.CallCommonT] ], , [ Dispatcher.Error ], , ], "IFCReqForceDemolition": [, , , , [Dispatcher.CallCommonRT], [ [Dispatcher.Identity], [Dispatcher.CallCommonT] ], , [ Dispatcher.Error ], , ], "IFCReqForceInsert": [, , , , [Dispatcher.CallCommonRT], [ [Dispatcher.Identity], [Dispatcher.CallCommonT] ], , [ Dispatcher.Error ], , ], "IFCReqMonitor": [, , , , [Dispatcher.CallCommonRT], [ [Dispatcher.Identity], [Dispatcher.CallCommonT] ], , [ Dispatcher.Error ], , ], "IFCReqCallTransfer": [, , , , [Dispatcher.CallCommonRT], [ [Dispatcher.Identity], [Dispatcher.CallCommonT] ], , [ Dispatcher.Error ], , ], "IFCReqHold": [, , , , [Dispatcher.HoldRT], [ [Dispatcher.Identity], [Dispatcher.HoldT] ], , [ Dispatcher.Error ], , ], "IFCReqHangup": [, , , , [Dispatcher.HangupRT], [ [Dispatcher.Identity], [Dispatcher.HangupT] ], , [ Dispatcher.Error ], , ], "IFCReqHangup2": [, , , , [Dispatcher.HangupRT], [ [Dispatcher.Identity], [Dispatcher.HangupT1] ], , [ Dispatcher.Error ], , ], "IFCReqCreateConf": [, , , , [Dispatcher.CreateConfRT], [ [Dispatcher.Identity], [Dispatcher.CreateConfT] ], , [ Dispatcher.Error ], , ], "IFCReqCreateMcuConf": [, , , , [Dispatcher.CreateConfRT], [ [Dispatcher.Identity], [Dispatcher.CreateMcuConfT] ], , [ Dispatcher.Error ], , ], "IFCReqCreateMcuConf2": [, , , , [Dispatcher.CreateConfRT], [ [Dispatcher.Identity], [Dispatcher.CreateMcuConf1T] ], , [ Dispatcher.Error ], , ], "IFCReqCreateConf2": [, , , , [Dispatcher.CreateConfRT], [ [Dispatcher.Identity], [Dispatcher.CreateConf1T] ], , [ Dispatcher.Error ], , ], "IFCReqCreateScheduleConf": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqFixScheduleConf": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqDeleteScheduleConf": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetScheduleConf": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqCreateFileBroadcastConf": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetFileBroadcastState": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqAddMember": [, , , , [Dispatcher.AddMemberRT], [ [Dispatcher.Identity], [Dispatcher.AddMemberT] ], , [ Dispatcher.Error ], , ], "IFCReqDelMember": [, , , , [Dispatcher.DelMemberRT], [ [Dispatcher.Identity], [Dispatcher.DelMemberT] ], , [ Dispatcher.Error ], , ], "IFCReqGetAllMember": [, , , , ["Dispatcher.AllCallMemberRSeqHelper"], [ [Dispatcher.Identity], [Dispatcher.AllCallMemberT] ], , [ Dispatcher.Error ], , ], "IFCReqPullCallFromQueue": [, , , , [Dispatcher.CommonRequestT], [ [Dispatcher.Identity], [Dispatcher.PullQueueCallT] ], , [ Dispatcher.Error ], , ], "IFCReqPushCallToQueue": [, , , , [Dispatcher.CommonRequestT], [ [Dispatcher.Identity], [Dispatcher.PushCallToQueueT] ], , [ Dispatcher.Error ], , ], "IFCReqPushCallToQueue2": [, , , , [Dispatcher.CommonRequestT], [ [Dispatcher.Identity], [Dispatcher.PushCallToQueueT1] ], , [ Dispatcher.Error ], , ], "IFCReqGetAllSessions": [, , , , ["Dispatcher.SessionChangeTSeqHelper"], [ [Dispatcher.Identity], [Dispatcher.GetAllSessionT] ], , [ Dispatcher.Error ], , ], "IFCReqGetAllSessions2": [, , , , ["Dispatcher.SessionChangeTSeqHelper"], [ [Dispatcher.Identity], [Dispatcher.GetAllSession1T] ], , [ Dispatcher.Error ], , ], "IFCReqSendDtmf": [, , , , [1], [ [Dispatcher.Identity], [Dispatcher.SendDTMFbyCidT] ], , [ Dispatcher.Error ], , ], "IFCReqCreateCallByOrder": [, , , , [Dispatcher.CalledOrderRT], [ [Dispatcher.Identity], [Dispatcher.CalledOrderT] ], , [ Dispatcher.Error ], , ], "IFCReqInviteMemberByOrder": [, , , , , [ [Dispatcher.Identity], [Dispatcher.AddMemberByCallOrderT] ], , [ Dispatcher.Error ], , ], "IFCReqSetCallCount": [, , , , , [ [Dispatcher.Identity], [Dispatcher.SetReCallNumberT] ], , [ Dispatcher.Error ], , ], "IFCReqGetAllMember1": [, , , , ["Dispatcher.AllCallMemberRSeq1Helper"], [ [Dispatcher.Identity], [Dispatcher.AllCallMemberT] ], , [ Dispatcher.Error ], , ], "IFCReqCallMerge": [, , , , [Dispatcher.CreateConfRT], [ [Dispatcher.Identity], ["Dispatcher.SessionJoinSeqHelper"] ], , [ Dispatcher.Error ], , ], "IFCReqCreateSOSCall": [, , , , [Dispatcher.CreateConfRT], [ [Dispatcher.Identity], [Dispatcher.CreateSOSCallT] ], , [ Dispatcher.Error ], , ], "IFCReqTransferVideo": [, , , , [Dispatcher.TransferVideoRT], [ [Dispatcher.Identity], [Dispatcher.TransferVideoT] ], , [ Dispatcher.Error ], , ], "IFCReqTransferVideoByJson": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqTransferVideoToMCU": [, , , , [Dispatcher.TransferVideoRT], [ [Dispatcher.Identity], [Dispatcher.TransferVideoToMCUT] ], , [ Dispatcher.Error ], , ], "IFCReqCreateVideoUploadCall": [, , , , [Dispatcher.CreateConfRT], [ [Dispatcher.Identity], [Dispatcher.UploadVideoCallT] ], , [ Dispatcher.Error ], , ], "IFCReqTmpCallMerge": [, , , , ["Dispatcher.SessionJoinSeqHelper"], [ [Dispatcher.Identity], ["Dispatcher.SessionJoinSeqHelper"] ], , [ Dispatcher.Error ], , ], "IFCReqAddMember2": [, , , , [Dispatcher.AddMemberRT], [ [Dispatcher.Identity], [Dispatcher.AddMemberT1] ], , [ Dispatcher.Error ], , ], "IFCReqRecallIntercom": [, , , , , [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetAllMember2": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetAllFixMeetingSessions": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqAddMemberToFixMeeting": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqPushStartCallAudio": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqPushStopCallAudio": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ] }); const iceC_Dispatcher_CallingSB_ids = [ "::Dispatcher::CallingSB", "::Ice::Object" ]; Dispatcher.CallingSB = class extends ice.Ice.Object {}; Dispatcher.CallingSBPrx = class extends ice.Ice.ObjectPrx {}; Slice$5.defineOperations(Dispatcher.CallingSB, Dispatcher.CallingSBPrx, iceC_Dispatcher_CallingSB_ids, 0); // const _ModuleRegistry$6 = ice.Ice._ModuleRegistry; const Slice$6 = ice.Ice.Slice; Dispatcher.SendVideoT = class { constructor(sid = "", cid = "", employeeid = "", ip = "", port = "", codec = "", stream = "", framerate = "", agentid = "") { this.sid = sid; this.cid = cid; this.employeeid = employeeid; this.ip = ip; this.port = port; this.codec = codec; this.stream = stream; this.framerate = framerate; this.agentid = agentid; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.cid); ostr.writeString(this.employeeid); ostr.writeString(this.ip); ostr.writeString(this.port); ostr.writeString(this.codec); ostr.writeString(this.stream); ostr.writeString(this.framerate); ostr.writeString(this.agentid); } _read(istr) { this.sid = istr.readString(); this.cid = istr.readString(); this.employeeid = istr.readString(); this.ip = istr.readString(); this.port = istr.readString(); this.codec = istr.readString(); this.stream = istr.readString(); this.framerate = istr.readString(); this.agentid = istr.readString(); } static get minWireSize() { return 9; } }; Slice$6.defineStruct(Dispatcher.SendVideoT, true, true); Dispatcher.SendVideoRT = class { constructor(sid = "", ip = "", port = "", agentid = "") { this.sid = sid; this.ip = ip; this.port = port; this.agentid = agentid; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.ip); ostr.writeString(this.port); ostr.writeString(this.agentid); } _read(istr) { this.sid = istr.readString(); this.ip = istr.readString(); this.port = istr.readString(); this.agentid = istr.readString(); } static get minWireSize() { return 4; } }; Slice$6.defineStruct(Dispatcher.SendVideoRT, true, true); Dispatcher.GetVideoT = class { constructor(sid = "", cid = "", employeeid = "", ip = "", port = "", employeeiddst = "", codec = "", stream = "", framerate = "", agentid = "") { this.sid = sid; this.cid = cid; this.employeeid = employeeid; this.ip = ip; this.port = port; this.employeeiddst = employeeiddst; this.codec = codec; this.stream = stream; this.framerate = framerate; this.agentid = agentid; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.cid); ostr.writeString(this.employeeid); ostr.writeString(this.ip); ostr.writeString(this.port); ostr.writeString(this.employeeiddst); ostr.writeString(this.codec); ostr.writeString(this.stream); ostr.writeString(this.framerate); ostr.writeString(this.agentid); } _read(istr) { this.sid = istr.readString(); this.cid = istr.readString(); this.employeeid = istr.readString(); this.ip = istr.readString(); this.port = istr.readString(); this.employeeiddst = istr.readString(); this.codec = istr.readString(); this.stream = istr.readString(); this.framerate = istr.readString(); this.agentid = istr.readString(); } static get minWireSize() { return 10; } }; Slice$6.defineStruct(Dispatcher.GetVideoT, true, true); Dispatcher.GetVideoRT = class { constructor(sid = "", cid = "") { this.sid = sid; this.cid = cid; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.cid); } _read(istr) { this.sid = istr.readString(); this.cid = istr.readString(); } static get minWireSize() { return 2; } }; Slice$6.defineStruct(Dispatcher.GetVideoRT, true, true); Dispatcher.ChangeVideoT = class { constructor(sid = "", cid = "", employeeid = "", ip = "", port = "", employeeiddst = "", codec = "", stream = "", framerate = "", agentid = "") { this.sid = sid; this.cid = cid; this.employeeid = employeeid; this.ip = ip; this.port = port; this.employeeiddst = employeeiddst; this.codec = codec; this.stream = stream; this.framerate = framerate; this.agentid = agentid; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.cid); ostr.writeString(this.employeeid); ostr.writeString(this.ip); ostr.writeString(this.port); ostr.writeString(this.employeeiddst); ostr.writeString(this.codec); ostr.writeString(this.stream); ostr.writeString(this.framerate); ostr.writeString(this.agentid); } _read(istr) { this.sid = istr.readString(); this.cid = istr.readString(); this.employeeid = istr.readString(); this.ip = istr.readString(); this.port = istr.readString(); this.employeeiddst = istr.readString(); this.codec = istr.readString(); this.stream = istr.readString(); this.framerate = istr.readString(); this.agentid = istr.readString(); } static get minWireSize() { return 10; } }; Slice$6.defineStruct(Dispatcher.ChangeVideoT, true, true); Dispatcher.ChangeVideoRT = class { constructor(sid = "", streamid = "", ip = "", port = "", codec = "", stream = "", framerate = "", agentid = "") { this.sid = sid; this.streamid = streamid; this.ip = ip; this.port = port; this.codec = codec; this.stream = stream; this.framerate = framerate; this.agentid = agentid; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.streamid); ostr.writeString(this.ip); ostr.writeString(this.port); ostr.writeString(this.codec); ostr.writeString(this.stream); ostr.writeString(this.framerate); ostr.writeString(this.agentid); } _read(istr) { this.sid = istr.readString(); this.streamid = istr.readString(); this.ip = istr.readString(); this.port = istr.readString(); this.codec = istr.readString(); this.stream = istr.readString(); this.framerate = istr.readString(); this.agentid = istr.readString(); } static get minWireSize() { return 8; } }; Slice$6.defineStruct(Dispatcher.ChangeVideoRT, true, true); Dispatcher.ReleaseVideoT = class { constructor(sid = "", cid = "", employeeid = "", ip = "", port = "", streamid = "", employeeiddst = "", agentid = "") { this.sid = sid; this.cid = cid; this.employeeid = employeeid; this.ip = ip; this.port = port; this.streamid = streamid; this.employeeiddst = employeeiddst; this.agentid = agentid; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.cid); ostr.writeString(this.employeeid); ostr.writeString(this.ip); ostr.writeString(this.port); ostr.writeString(this.streamid); ostr.writeString(this.employeeiddst); ostr.writeString(this.agentid); } _read(istr) { this.sid = istr.readString(); this.cid = istr.readString(); this.employeeid = istr.readString(); this.ip = istr.readString(); this.port = istr.readString(); this.streamid = istr.readString(); this.employeeiddst = istr.readString(); this.agentid = istr.readString(); } static get minWireSize() { return 8; } }; Slice$6.defineStruct(Dispatcher.ReleaseVideoT, true, true); Dispatcher.ReleaseVideoRT = class { constructor(sid = "", agentid = "") { this.sid = sid; this.agentid = agentid; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.agentid); } _read(istr) { this.sid = istr.readString(); this.agentid = istr.readString(); } static get minWireSize() { return 2; } }; Slice$6.defineStruct(Dispatcher.ReleaseVideoRT, true, true); Dispatcher.PushVideoT = class { constructor(sid = "", cid = "", employeeid = "", streamid = "", revid = "", IsPush = Dispatcher.PushVideoType.PushVideoTypeNone, agentid = "") { this.sid = sid; this.cid = cid; this.employeeid = employeeid; this.streamid = streamid; this.revid = revid; this.IsPush = IsPush; this.agentid = agentid; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.cid); ostr.writeString(this.employeeid); ostr.writeString(this.streamid); ostr.writeString(this.revid); Dispatcher.PushVideoType._write(ostr, this.IsPush); ostr.writeString(this.agentid); } _read(istr) { this.sid = istr.readString(); this.cid = istr.readString(); this.employeeid = istr.readString(); this.streamid = istr.readString(); this.revid = istr.readString(); this.IsPush = Dispatcher.PushVideoType._read(istr); this.agentid = istr.readString(); } static get minWireSize() { return 7; } }; Slice$6.defineStruct(Dispatcher.PushVideoT, true, true); Dispatcher.PushVideoRT = class { constructor(sid = "", agentid = "") { this.sid = sid; this.agentid = agentid; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.agentid); } _read(istr) { this.sid = istr.readString(); this.agentid = istr.readString(); } static get minWireSize() { return 2; } }; Slice$6.defineStruct(Dispatcher.PushVideoRT, true, true); Dispatcher.SendVideoEvT = class { constructor(sid = "", ip = "", port = "", agentid = "") { this.sid = sid; this.ip = ip; this.port = port; this.agentid = agentid; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.ip); ostr.writeString(this.port); ostr.writeString(this.agentid); } _read(istr) { this.sid = istr.readString(); this.ip = istr.readString(); this.port = istr.readString(); this.agentid = istr.readString(); } static get minWireSize() { return 4; } }; Slice$6.defineStruct(Dispatcher.SendVideoEvT, true, true); Dispatcher.GetVideoEvT = class { constructor(sid = "", streamid = "", ip = "", port = "", codec = "", stream = "", framerate = "", employeeid = "", cid = "", agentid = "") { this.sid = sid; this.streamid = streamid; this.ip = ip; this.port = port; this.codec = codec; this.stream = stream; this.framerate = framerate; this.employeeid = employeeid; this.cid = cid; this.agentid = agentid; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.streamid); ostr.writeString(this.ip); ostr.writeString(this.port); ostr.writeString(this.codec); ostr.writeString(this.stream); ostr.writeString(this.framerate); ostr.writeString(this.employeeid); ostr.writeString(this.cid); ostr.writeString(this.agentid); } _read(istr) { this.sid = istr.readString(); this.streamid = istr.readString(); this.ip = istr.readString(); this.port = istr.readString(); this.codec = istr.readString(); this.stream = istr.readString(); this.framerate = istr.readString(); this.employeeid = istr.readString(); this.cid = istr.readString(); this.agentid = istr.readString(); } static get minWireSize() { return 10; } }; Slice$6.defineStruct(Dispatcher.GetVideoEvT, true, true); Dispatcher.GetKeyFrameT = class { constructor(cid = "", employeeid = "", deviceid = "") { this.cid = cid; this.employeeid = employeeid; this.deviceid = deviceid; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.employeeid); ostr.writeString(this.deviceid); } _read(istr) { this.cid = istr.readString(); this.employeeid = istr.readString(); this.deviceid = istr.readString(); } static get minWireSize() { return 3; } }; Slice$6.defineStruct(Dispatcher.GetKeyFrameT, true, true); // const _ModuleRegistry$7 = ice.Ice._ModuleRegistry; const Slice$7 = ice.Ice.Slice; const iceC_Dispatcher_CallingVCB_ids = [ "::Dispatcher::CallingVCB", "::Ice::Object" ]; Dispatcher.CallingVCB = class extends ice.Ice.Object {}; Dispatcher.CallingVCBPrx = class extends ice.Ice.ObjectPrx {}; Slice$7.defineOperations(Dispatcher.CallingVCB, Dispatcher.CallingVCBPrx, iceC_Dispatcher_CallingVCB_ids, 0, { "IFCNotifySendVideoEvt": [, 2, 2, , , [ [Dispatcher.SendVideoEvT] ], , , , ], "IFCNotifyGetVideoEvt": [, 2, 2, , , [ [Dispatcher.GetVideoEvT] ], , , , ] }); // const _ModuleRegistry$8 = ice.Ice._ModuleRegistry; const Slice$8 = ice.Ice.Slice; Dispatcher.GetMemberVideoRT = class { constructor(sid = "", cid = "", fsip = "", fsport = "") { this.sid = sid; this.cid = cid; this.fsip = fsip; this.fsport = fsport; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.cid); ostr.writeString(this.fsip); ostr.writeString(this.fsport); } _read(istr) { this.sid = istr.readString(); this.cid = istr.readString(); this.fsip = istr.readString(); this.fsport = istr.readString(); } static get minWireSize() { return 4; } }; Slice$8.defineStruct(Dispatcher.GetMemberVideoRT, true, true); Slice$8.defineSequence(Dispatcher, "ReceiveNumSeqHelper", "Ice.StringHelper", false); Dispatcher.MCUPushMemberToOtherT = class { constructor(cid = "", pushednum = "", ReceiveNumbers = null) { this.cid = cid; this.pushednum = pushednum; this.ReceiveNumbers = ReceiveNumbers; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.pushednum); Dispatcher.ReceiveNumSeqHelper.write(ostr, this.ReceiveNumbers); } _read(istr) { this.cid = istr.readString(); this.pushednum = istr.readString(); this.ReceiveNumbers = Dispatcher.ReceiveNumSeqHelper.read(istr); } static get minWireSize() { return 3; } }; Slice$8.defineStruct(Dispatcher.MCUPushMemberToOtherT, true, true); Dispatcher.StopMCUPushMemberToOtherT = class { constructor(cid = "") { this.cid = cid; } _write(ostr) { ostr.writeString(this.cid); } _read(istr) { this.cid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$8.defineStruct(Dispatcher.StopMCUPushMemberToOtherT, true, true); Dispatcher.SendVideoRT1 = class { constructor(sid = "", ip = "", port = "", agentid = "", codec = "") { this.sid = sid; this.ip = ip; this.port = port; this.agentid = agentid; this.codec = codec; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.ip); ostr.writeString(this.port); ostr.writeString(this.agentid); ostr.writeString(this.codec); } _read(istr) { this.sid = istr.readString(); this.ip = istr.readString(); this.port = istr.readString(); this.agentid = istr.readString(); this.codec = istr.readString(); } static get minWireSize() { return 5; } }; Slice$8.defineStruct(Dispatcher.SendVideoRT1, true, true); const iceC_Dispatcher_CallingVOP_ids = [ "::Dispatcher::CallingVOP", "::Ice::Object" ]; Dispatcher.CallingVOP = class extends ice.Ice.Object {}; Dispatcher.CallingVOPPrx = class extends ice.Ice.ObjectPrx {}; Slice$8.defineOperations(Dispatcher.CallingVOP, Dispatcher.CallingVOPPrx, iceC_Dispatcher_CallingVOP_ids, 0, { "IFCReqSendVideo": [, , , , [Dispatcher.SendVideoRT], [ [Dispatcher.Identity], [Dispatcher.SendVideoT] ], , [ Dispatcher.Error ], , ], "IFCReqSendVideo2": [, , , , [Dispatcher.SendVideoRT1], [ [Dispatcher.Identity], [Dispatcher.SendVideoT] ], , [ Dispatcher.Error ], , ], "IFCReqSendVideoByJson": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetVideo": [, , , , [Dispatcher.GetVideoRT], [ [Dispatcher.Identity], [Dispatcher.GetVideoT] ], , [ Dispatcher.Error ], , ], "IFCReqWebrtcGetVideo": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqChangeVideo": [, , , , [Dispatcher.ChangeVideoRT], [ [Dispatcher.Identity], [Dispatcher.ChangeVideoT] ], , [ Dispatcher.Error ], , ], "IFCReqReleaseVideo": [, , , , [Dispatcher.ReleaseVideoRT], [ [Dispatcher.Identity], [Dispatcher.ReleaseVideoT] ], , [ Dispatcher.Error ], , ], "IFCReqReleaseVideoByJson": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqPushVideo": [, , , , [Dispatcher.PushVideoRT], [ [Dispatcher.Identity], [Dispatcher.PushVideoT] ], , [ Dispatcher.Error ], , ], "IFCReqGetKeyFrame": [, , , , , [ [Dispatcher.Identity], [Dispatcher.GetKeyFrameT] ], , [ Dispatcher.Error ], , ], "IFCReqGetMemberVideo": [, , , , [Dispatcher.GetMemberVideoRT], [ [Dispatcher.Identity], [Dispatcher.GetVideoT] ], , [ Dispatcher.Error ], , ], "IFCReqMcuPushMemberToOther": [, , , , , [ [Dispatcher.Identity], [Dispatcher.MCUPushMemberToOtherT] ], , [ Dispatcher.Error ], , ], "IFCReqStopMcuPushMemberToOther": [, , , , , [ [Dispatcher.Identity], [Dispatcher.StopMCUPushMemberToOtherT] ], , [ Dispatcher.Error ], , ] }); // const _ModuleRegistry$9 = ice.Ice._ModuleRegistry; const Slice$9 = ice.Ice.Slice; let DispatcherDB = _ModuleRegistry$9.module("DispatcherDB"); DispatcherDB.EMPLOYEEINFO = class { constructor(mID = 0, mEmployeeID = "", mPassword = "", mEmployeeLevel = 0, mDepartID = 0, mRoleID = 0, mName = "", mAddTime = "", mModifyTime = "", mTheState = 0, mTheType = 0, mRemark = "", mLatitude = 0.0, mLongitude = 0.0, mIsRecord = 0, mMonName = "", mMonPasswd = "", mMonIP = "", mMonPort = 0, mMonFlag = "", mIsVideo = 0) { this.mID = mID; this.mEmployeeID = mEmployeeID; this.mPassword = mPassword; this.mEmployeeLevel = mEmployeeLevel; this.mDepartID = mDepartID; this.mRoleID = mRoleID; this.mName = mName; this.mAddTime = mAddTime; this.mModifyTime = mModifyTime; this.mTheState = mTheState; this.mTheType = mTheType; this.mRemark = mRemark; this.mLatitude = mLatitude; this.mLongitude = mLongitude; this.mIsRecord = mIsRecord; this.mMonName = mMonName; this.mMonPasswd = mMonPasswd; this.mMonIP = mMonIP; this.mMonPort = mMonPort; this.mMonFlag = mMonFlag; this.mIsVideo = mIsVideo; } _write(ostr) { ostr.writeInt(this.mID); ostr.writeString(this.mEmployeeID); ostr.writeString(this.mPassword); ostr.writeInt(this.mEmployeeLevel); ostr.writeInt(this.mDepartID); ostr.writeInt(this.mRoleID); ostr.writeString(this.mName); ostr.writeString(this.mAddTime); ostr.writeString(this.mModifyTime); ostr.writeInt(this.mTheState); ostr.writeInt(this.mTheType); ostr.writeString(this.mRemark); ostr.writeFloat(this.mLatitude); ostr.writeFloat(this.mLongitude); ostr.writeInt(this.mIsRecord); ostr.writeString(this.mMonName); ostr.writeString(this.mMonPasswd); ostr.writeString(this.mMonIP); ostr.writeInt(this.mMonPort); ostr.writeString(this.mMonFlag); ostr.writeInt(this.mIsVideo); } _read(istr) { this.mID = istr.readInt(); this.mEmployeeID = istr.readString(); this.mPassword = istr.readString(); this.mEmployeeLevel = istr.readInt(); this.mDepartID = istr.readInt(); this.mRoleID = istr.readInt(); this.mName = istr.readString(); this.mAddTime = istr.readString(); this.mModifyTime = istr.readString(); this.mTheState = istr.readInt(); this.mTheType = istr.readInt(); this.mRemark = istr.readString(); this.mLatitude = istr.readFloat(); this.mLongitude = istr.readFloat(); this.mIsRecord = istr.readInt(); this.mMonName = istr.readString(); this.mMonPasswd = istr.readString(); this.mMonIP = istr.readString(); this.mMonPort = istr.readInt(); this.mMonFlag = istr.readString(); this.mIsVideo = istr.readInt(); } static get minWireSize() { return 54; } }; Slice$9.defineStruct(DispatcherDB.EMPLOYEEINFO, false, true); Slice$9.defineSequence(DispatcherDB, "EMPLOYEEINFOSeqHelper", "DispatcherDB.EMPLOYEEINFO", false); DispatcherDB.GROUPEMPLOYEE = class { constructor(mID = 0, mGroupID = 0, mEmployeeID = "", mAddTime = "") { this.mID = mID; this.mGroupID = mGroupID; this.mEmployeeID = mEmployeeID; this.mAddTime = mAddTime; } _write(ostr) { ostr.writeInt(this.mID); ostr.writeInt(this.mGroupID); ostr.writeString(this.mEmployeeID); ostr.writeString(this.mAddTime); } _read(istr) { this.mID = istr.readInt(); this.mGroupID = istr.readInt(); this.mEmployeeID = istr.readString(); this.mAddTime = istr.readString(); } static get minWireSize() { return 10; } }; Slice$9.defineStruct(DispatcherDB.GROUPEMPLOYEE, true, true); Slice$9.defineSequence(DispatcherDB, "GROUPEMPLOYEESeqHelper", "DispatcherDB.GROUPEMPLOYEE", false); DispatcherDB.EmployeeRelatedAll = class { constructor(mID = 0, mEmployeeID = "", mPassword = "", mEmployeeLevel = 0, mDepartID = 0, mRoleID = 0, mName = "", mAddTime = "", mModifyTime = "", mTheState = 0, mTheType = 0, mRemark = "", mGroupID = 0, mGroupName = "", mGroupParentID = 0, mGroupNum = "", mGroupType = 0, mRoleName = "") { this.mID = mID; this.mEmployeeID = mEmployeeID; this.mPassword = mPassword; this.mEmployeeLevel = mEmployeeLevel; this.mDepartID = mDepartID; this.mRoleID = mRoleID; this.mName = mName; this.mAddTime = mAddTime; this.mModifyTime = mModifyTime; this.mTheState = mTheState; this.mTheType = mTheType; this.mRemark = mRemark; this.mGroupID = mGroupID; this.mGroupName = mGroupName; this.mGroupParentID = mGroupParentID; this.mGroupNum = mGroupNum; this.mGroupType = mGroupType; this.mRoleName = mRoleName; } _write(ostr) { ostr.writeInt(this.mID); ostr.writeString(this.mEmployeeID); ostr.writeString(this.mPassword); ostr.writeInt(this.mEmployeeLevel); ostr.writeInt(this.mDepartID); ostr.writeInt(this.mRoleID); ostr.writeString(this.mName); ostr.writeString(this.mAddTime); ostr.writeString(this.mModifyTime); ostr.writeInt(this.mTheState); ostr.writeInt(this.mTheType); ostr.writeString(this.mRemark); ostr.writeInt(this.mGroupID); ostr.writeString(this.mGroupName); ostr.writeInt(this.mGroupParentID); ostr.writeString(this.mGroupNum); ostr.writeInt(this.mGroupType); ostr.writeString(this.mRoleName); } _read(istr) { this.mID = istr.readInt(); this.mEmployeeID = istr.readString(); this.mPassword = istr.readString(); this.mEmployeeLevel = istr.readInt(); this.mDepartID = istr.readInt(); this.mRoleID = istr.readInt(); this.mName = istr.readString(); this.mAddTime = istr.readString(); this.mModifyTime = istr.readString(); this.mTheState = istr.readInt(); this.mTheType = istr.readInt(); this.mRemark = istr.readString(); this.mGroupID = istr.readInt(); this.mGroupName = istr.readString(); this.mGroupParentID = istr.readInt(); this.mGroupNum = istr.readString(); this.mGroupType = istr.readInt(); this.mRoleName = istr.readString(); } static get minWireSize() { return 45; } }; Slice$9.defineStruct(DispatcherDB.EmployeeRelatedAll, true, true); Slice$9.defineSequence(DispatcherDB, "EmployeeRelatedAllSeqHelper", "DispatcherDB.EmployeeRelatedAll", false); DispatcherDB.DEVICECONFIG = class { constructor(mID = 0, mStartDevice = "", mSumDevice = 0, mServerIP = "", mServerPort = 0, mTheState = 0, mModifyTime = "", mAddTime = "", mTheType = 0, mUserName = "", mUserPWD = "") { this.mID = mID; this.mStartDevice = mStartDevice; this.mSumDevice = mSumDevice; this.mServerIP = mServerIP; this.mServerPort = mServerPort; this.mTheState = mTheState; this.mModifyTime = mModifyTime; this.mAddTime = mAddTime; this.mTheType = mTheType; this.mUserName = mUserName; this.mUserPWD = mUserPWD; } _write(ostr) { ostr.writeInt(this.mID); ostr.writeString(this.mStartDevice); ostr.writeInt(this.mSumDevice); ostr.writeString(this.mServerIP); ostr.writeInt(this.mServerPort); ostr.writeInt(this.mTheState); ostr.writeString(this.mModifyTime); ostr.writeString(this.mAddTime); ostr.writeInt(this.mTheType); ostr.writeString(this.mUserName); ostr.writeString(this.mUserPWD); } _read(istr) { this.mID = istr.readInt(); this.mStartDevice = istr.readString(); this.mSumDevice = istr.readInt(); this.mServerIP = istr.readString(); this.mServerPort = istr.readInt(); this.mTheState = istr.readInt(); this.mModifyTime = istr.readString(); this.mAddTime = istr.readString(); this.mTheType = istr.readInt(); this.mUserName = istr.readString(); this.mUserPWD = istr.readString(); } static get minWireSize() { return 26; } }; Slice$9.defineStruct(DispatcherDB.DEVICECONFIG, true, true); Slice$9.defineSequence(DispatcherDB, "DEVICECONFIGSeqHelper", "DispatcherDB.DEVICECONFIG", false); DispatcherDB.SYSPARAMETER = class { constructor(mTheKey = "", mTheValue = "", mTheState = 0) { this.mTheKey = mTheKey; this.mTheValue = mTheValue; this.mTheState = mTheState; } _write(ostr) { ostr.writeString(this.mTheKey); ostr.writeString(this.mTheValue); ostr.writeInt(this.mTheState); } _read(istr) { this.mTheKey = istr.readString(); this.mTheValue = istr.readString(); this.mTheState = istr.readInt(); } static get minWireSize() { return 6; } }; Slice$9.defineStruct(DispatcherDB.SYSPARAMETER, true, true); Slice$9.defineSequence(DispatcherDB, "SYSPARAMETERSeqHelper", "DispatcherDB.SYSPARAMETER", false); DispatcherDB.SYSCONFIGREAD = class { constructor(mTableName = "", mAddTime = "", mReadTime = "", mState = 0, mValue1 = "") { this.mTableName = mTableName; this.mAddTime = mAddTime; this.mReadTime = mReadTime; this.mState = mState; this.mValue1 = mValue1; } _write(ostr) { ostr.writeString(this.mTableName); ostr.writeString(this.mAddTime); ostr.writeString(this.mReadTime); ostr.writeInt(this.mState); ostr.writeString(this.mValue1); } _read(istr) { this.mTableName = istr.readString(); this.mAddTime = istr.readString(); this.mReadTime = istr.readString(); this.mState = istr.readInt(); this.mValue1 = istr.readString(); } static get minWireSize() { return 8; } }; Slice$9.defineStruct(DispatcherDB.SYSCONFIGREAD, true, true); Slice$9.defineSequence(DispatcherDB, "SYSCONFIGREADSeqHelper", "DispatcherDB.SYSCONFIGREAD", false); DispatcherDB.CALLCALLLOGType = class { constructor(mCid = "", mCaller = "", mCalled = "", mCreateTime = "", mReleaseTime = "", mTimeLength = 0, mCallType = 0, mCallResult = 0, mReleaseReason = 0) { this.mCid = mCid; this.mCaller = mCaller; this.mCalled = mCalled; this.mCreateTime = mCreateTime; this.mReleaseTime = mReleaseTime; this.mTimeLength = mTimeLength; this.mCallType = mCallType; this.mCallResult = mCallResult; this.mReleaseReason = mReleaseReason; } _write(ostr) { ostr.writeString(this.mCid); ostr.writeString(this.mCaller); ostr.writeString(this.mCalled); ostr.writeString(this.mCreateTime); ostr.writeString(this.mReleaseTime); ostr.writeInt(this.mTimeLength); ostr.writeInt(this.mCallType); ostr.writeInt(this.mCallResult); ostr.writeInt(this.mReleaseReason); } _read(istr) { this.mCid = istr.readString(); this.mCaller = istr.readString(); this.mCalled = istr.readString(); this.mCreateTime = istr.readString(); this.mReleaseTime = istr.readString(); this.mTimeLength = istr.readInt(); this.mCallType = istr.readInt(); this.mCallResult = istr.readInt(); this.mReleaseReason = istr.readInt(); } static get minWireSize() { return 21; } }; Slice$9.defineStruct(DispatcherDB.CALLCALLLOGType, true, true); Slice$9.defineSequence(DispatcherDB, "CALLCALLLOGSeqHelper", "DispatcherDB.CALLCALLLOGType", false); DispatcherDB.CALLRECORDType = class { constructor(mCid = "", mRecordName = "", mSubPath = "", mReadTimes = 0, mRecordServerID = 0, mCreateTime = "", mReleaseTime = "", mTimeLength = 0, mRecordType = 0, mWebPath = "") { this.mCid = mCid; this.mRecordName = mRecordName; this.mSubPath = mSubPath; this.mReadTimes = mReadTimes; this.mRecordServerID = mRecordServerID; this.mCreateTime = mCreateTime; this.mReleaseTime = mReleaseTime; this.mTimeLength = mTimeLength; this.mRecordType = mRecordType; this.mWebPath = mWebPath; } _write(ostr) { ostr.writeString(this.mCid); ostr.writeString(this.mRecordName); ostr.writeString(this.mSubPath); ostr.writeInt(this.mReadTimes); ostr.writeInt(this.mRecordServerID); ostr.writeString(this.mCreateTime); ostr.writeString(this.mReleaseTime); ostr.writeInt(this.mTimeLength); ostr.writeInt(this.mRecordType); ostr.writeString(this.mWebPath); } _read(istr) { this.mCid = istr.readString(); this.mRecordName = istr.readString(); this.mSubPath = istr.readString(); this.mReadTimes = istr.readInt(); this.mRecordServerID = istr.readInt(); this.mCreateTime = istr.readString(); this.mReleaseTime = istr.readString(); this.mTimeLength = istr.readInt(); this.mRecordType = istr.readInt(); this.mWebPath = istr.readString(); } static get minWireSize() { return 22; } }; Slice$9.defineStruct(DispatcherDB.CALLRECORDType, true, true); Slice$9.defineSequence(DispatcherDB, "CALLRECORDSeqHelper", "DispatcherDB.CALLRECORDType", false); DispatcherDB.VIDEO = class { constructor(mID = 0, mVideoIP = "", mVideoPort = "", mUser = "", mPassWord = "", mShowName = "", mTheType = 0, mBindEmployeeID = "") { this.mID = mID; this.mVideoIP = mVideoIP; this.mVideoPort = mVideoPort; this.mUser = mUser; this.mPassWord = mPassWord; this.mShowName = mShowName; this.mTheType = mTheType; this.mBindEmployeeID = mBindEmployeeID; } _write(ostr) { ostr.writeInt(this.mID); ostr.writeString(this.mVideoIP); ostr.writeString(this.mVideoPort); ostr.writeString(this.mUser); ostr.writeString(this.mPassWord); ostr.writeString(this.mShowName); ostr.writeInt(this.mTheType); ostr.writeString(this.mBindEmployeeID); } _read(istr) { this.mID = istr.readInt(); this.mVideoIP = istr.readString(); this.mVideoPort = istr.readString(); this.mUser = istr.readString(); this.mPassWord = istr.readString(); this.mShowName = istr.readString(); this.mTheType = istr.readInt(); this.mBindEmployeeID = istr.readString(); } static get minWireSize() { return 14; } }; Slice$9.defineStruct(DispatcherDB.VIDEO, true, true); Slice$9.defineSequence(DispatcherDB, "VIDEOSeqHelper", "DispatcherDB.VIDEO", false); DispatcherDB.VIDEORECORDType = class { constructor(mCid = "", mRecordName = "", mSubPath = "", mReadTimes = 0, mRecordServerID = 0, mCreateTime = "", mReleaseTime = "", mTimeLength = 0, mRecordType = 0, mWebPath = "") { this.mCid = mCid; this.mRecordName = mRecordName; this.mSubPath = mSubPath; this.mReadTimes = mReadTimes; this.mRecordServerID = mRecordServerID; this.mCreateTime = mCreateTime; this.mReleaseTime = mReleaseTime; this.mTimeLength = mTimeLength; this.mRecordType = mRecordType; this.mWebPath = mWebPath; } _write(ostr) { ostr.writeString(this.mCid); ostr.writeString(this.mRecordName); ostr.writeString(this.mSubPath); ostr.writeInt(this.mReadTimes); ostr.writeInt(this.mRecordServerID); ostr.writeString(this.mCreateTime); ostr.writeString(this.mReleaseTime); ostr.writeInt(this.mTimeLength); ostr.writeInt(this.mRecordType); ostr.writeString(this.mWebPath); } _read(istr) { this.mCid = istr.readString(); this.mRecordName = istr.readString(); this.mSubPath = istr.readString(); this.mReadTimes = istr.readInt(); this.mRecordServerID = istr.readInt(); this.mCreateTime = istr.readString(); this.mReleaseTime = istr.readString(); this.mTimeLength = istr.readInt(); this.mRecordType = istr.readInt(); this.mWebPath = istr.readString(); } static get minWireSize() { return 22; } }; Slice$9.defineStruct(DispatcherDB.VIDEORECORDType, true, true); Slice$9.defineSequence(DispatcherDB, "VIDEORECORDSeqHelper", "DispatcherDB.VIDEORECORDType", false); DispatcherDB.MSGINFO = class { constructor(mID = 0, mMsgID = "", mSendID = "", mSendName = "", mMsgBody = "", mSendTime = "", mIsUpload = 0, mMsgType = 0) { this.mID = mID; this.mMsgID = mMsgID; this.mSendID = mSendID; this.mSendName = mSendName; this.mMsgBody = mMsgBody; this.mSendTime = mSendTime; this.mIsUpload = mIsUpload; this.mMsgType = mMsgType; } _write(ostr) { ostr.writeInt(this.mID); ostr.writeString(this.mMsgID); ostr.writeString(this.mSendID); ostr.writeString(this.mSendName); ostr.writeString(this.mMsgBody); ostr.writeString(this.mSendTime); ostr.writeInt(this.mIsUpload); ostr.writeInt(this.mMsgType); } _read(istr) { this.mID = istr.readInt(); this.mMsgID = istr.readString(); this.mSendID = istr.readString(); this.mSendName = istr.readString(); this.mMsgBody = istr.readString(); this.mSendTime = istr.readString(); this.mIsUpload = istr.readInt(); this.mMsgType = istr.readInt(); } static get minWireSize() { return 17; } }; Slice$9.defineStruct(DispatcherDB.MSGINFO, true, true); Slice$9.defineSequence(DispatcherDB, "MSGINFOSeqHelper", "DispatcherDB.MSGINFO", false); DispatcherDB.MSGSENDRS = class { constructor(mID = 0, mMsgID = "", mReceiverID = "", mReceiverName = "", mIsFinish = "", mRecvTime = "") { this.mID = mID; this.mMsgID = mMsgID; this.mReceiverID = mReceiverID; this.mReceiverName = mReceiverName; this.mIsFinish = mIsFinish; this.mRecvTime = mRecvTime; } _write(ostr) { ostr.writeInt(this.mID); ostr.writeString(this.mMsgID); ostr.writeString(this.mReceiverID); ostr.writeString(this.mReceiverName); ostr.writeString(this.mIsFinish); ostr.writeString(this.mRecvTime); } _read(istr) { this.mID = istr.readInt(); this.mMsgID = istr.readString(); this.mReceiverID = istr.readString(); this.mReceiverName = istr.readString(); this.mIsFinish = istr.readString(); this.mRecvTime = istr.readString(); } static get minWireSize() { return 9; } }; Slice$9.defineStruct(DispatcherDB.MSGSENDRS, true, true); Slice$9.defineSequence(DispatcherDB, "MSGSENDRSSeqHelper", "DispatcherDB.MSGSENDRS", false); DispatcherDB.ROUTECFG = class { constructor(mID = 0, mRouteNum = "", mIP = "") { this.mID = mID; this.mRouteNum = mRouteNum; this.mIP = mIP; } _write(ostr) { ostr.writeInt(this.mID); ostr.writeString(this.mRouteNum); ostr.writeString(this.mIP); } _read(istr) { this.mID = istr.readInt(); this.mRouteNum = istr.readString(); this.mIP = istr.readString(); } static get minWireSize() { return 6; } }; Slice$9.defineStruct(DispatcherDB.ROUTECFG, true, true); Slice$9.defineSequence(DispatcherDB, "ROUTECFGSeqHelper", "DispatcherDB.ROUTECFG", false); DispatcherDB.IVRCFG = class { constructor(mID = 0, mIvrName = "", mIvrNum = "") { this.mID = mID; this.mIvrName = mIvrName; this.mIvrNum = mIvrNum; } _write(ostr) { ostr.writeInt(this.mID); ostr.writeString(this.mIvrName); ostr.writeString(this.mIvrNum); } _read(istr) { this.mID = istr.readInt(); this.mIvrName = istr.readString(); this.mIvrNum = istr.readString(); } static get minWireSize() { return 6; } }; Slice$9.defineStruct(DispatcherDB.IVRCFG, true, true); Slice$9.defineSequence(DispatcherDB, "IVRCFGSeqHelper", "DispatcherDB.IVRCFG", false); DispatcherDB.MDVSCFG = class { constructor(mID = 0, mMdvsName = "", mIP = "") { this.mID = mID; this.mMdvsName = mMdvsName; this.mIP = mIP; } _write(ostr) { ostr.writeInt(this.mID); ostr.writeString(this.mMdvsName); ostr.writeString(this.mIP); } _read(istr) { this.mID = istr.readInt(); this.mMdvsName = istr.readString(); this.mIP = istr.readString(); } static get minWireSize() { return 6; } }; Slice$9.defineStruct(DispatcherDB.MDVSCFG, true, true); Slice$9.defineSequence(DispatcherDB, "MDVSCFGSeqHelper", "DispatcherDB.MDVSCFG", false); DispatcherDB.GISDETAIL = class { constructor(mEmployeeid = "", mLatitude = 0.0, mLongitude = 0.0, mPositionTime = "", mMessage = "", type = 0) { this.mEmployeeid = mEmployeeid; this.mLatitude = mLatitude; this.mLongitude = mLongitude; this.mPositionTime = mPositionTime; this.mMessage = mMessage; this.type = type; } _write(ostr) { ostr.writeString(this.mEmployeeid); ostr.writeDouble(this.mLatitude); ostr.writeDouble(this.mLongitude); ostr.writeString(this.mPositionTime); ostr.writeString(this.mMessage); ostr.writeInt(this.type); } _read(istr) { this.mEmployeeid = istr.readString(); this.mLatitude = istr.readDouble(); this.mLongitude = istr.readDouble(); this.mPositionTime = istr.readString(); this.mMessage = istr.readString(); this.type = istr.readInt(); } static get minWireSize() { return 23; } }; Slice$9.defineStruct(DispatcherDB.GISDETAIL, false, true); Slice$9.defineSequence(DispatcherDB, "GISDETAILSeqHelper", "DispatcherDB.GISDETAIL", false); DispatcherDB.PREPLANINFO = class { constructor(mPlanName = "", mPlanID = 0, mPlanPasswd = "", mPlanType = 0, mPlanAddr = "", mPlanAlloc = "") { this.mPlanName = mPlanName; this.mPlanID = mPlanID; this.mPlanPasswd = mPlanPasswd; this.mPlanType = mPlanType; this.mPlanAddr = mPlanAddr; this.mPlanAlloc = mPlanAlloc; } _write(ostr) { ostr.writeString(this.mPlanName); ostr.writeInt(this.mPlanID); ostr.writeString(this.mPlanPasswd); ostr.writeInt(this.mPlanType); ostr.writeString(this.mPlanAddr); ostr.writeString(this.mPlanAlloc); } _read(istr) { this.mPlanName = istr.readString(); this.mPlanID = istr.readInt(); this.mPlanPasswd = istr.readString(); this.mPlanType = istr.readInt(); this.mPlanAddr = istr.readString(); this.mPlanAlloc = istr.readString(); } static get minWireSize() { return 12; } }; Slice$9.defineStruct(DispatcherDB.PREPLANINFO, true, true); Slice$9.defineSequence(DispatcherDB, "PREPLANINFOSeqHelper", "DispatcherDB.PREPLANINFO", false); DispatcherDB.PREPLANINSTRUMENT = class { constructor(mPlanInstID = 0, mPlanInstName = "", mPlanInstType = 0) { this.mPlanInstID = mPlanInstID; this.mPlanInstName = mPlanInstName; this.mPlanInstType = mPlanInstType; } _write(ostr) { ostr.writeInt(this.mPlanInstID); ostr.writeString(this.mPlanInstName); ostr.writeInt(this.mPlanInstType); } _read(istr) { this.mPlanInstID = istr.readInt(); this.mPlanInstName = istr.readString(); this.mPlanInstType = istr.readInt(); } static get minWireSize() { return 9; } }; Slice$9.defineStruct(DispatcherDB.PREPLANINSTRUMENT, true, true); Slice$9.defineSequence(DispatcherDB, "PREPLANINSTRUMENTSeqHelper", "DispatcherDB.PREPLANINSTRUMENT", false); DispatcherDB.PREPLANINSTRUREF = class { constructor(mPlanID = 0, mPlanInstID = 0) { this.mPlanID = mPlanID; this.mPlanInstID = mPlanInstID; } _write(ostr) { ostr.writeInt(this.mPlanID); ostr.writeInt(this.mPlanInstID); } _read(istr) { this.mPlanID = istr.readInt(); this.mPlanInstID = istr.readInt(); } static get minWireSize() { return 8; } }; Slice$9.defineStruct(DispatcherDB.PREPLANINSTRUREF, true, false); Slice$9.defineSequence(DispatcherDB, "PREPLANINSTRUREFSeqHelper", "DispatcherDB.PREPLANINSTRUREF", true); DispatcherDB.PREPLANMEMBER = class { constructor(mPlanInstID = 0, mEmployeeID = "") { this.mPlanInstID = mPlanInstID; this.mEmployeeID = mEmployeeID; } _write(ostr) { ostr.writeInt(this.mPlanInstID); ostr.writeString(this.mEmployeeID); } _read(istr) { this.mPlanInstID = istr.readInt(); this.mEmployeeID = istr.readString(); } static get minWireSize() { return 5; } }; Slice$9.defineStruct(DispatcherDB.PREPLANMEMBER, true, true); Slice$9.defineSequence(DispatcherDB, "PREPLANMEMBERSeqHelper", "DispatcherDB.PREPLANMEMBER", false); // const _ModuleRegistry$a = ice.Ice._ModuleRegistry; const Slice$a = ice.Ice.Slice; const iceC_Dispatcher_CommSrv_ids = [ "::Dispatcher::CommSrv", "::Ice::Object" ]; Dispatcher$1.CommSrv = class extends ice.Ice.Object {}; Dispatcher$1.CommSrvPrx = class extends ice.Ice.ObjectPrx {}; Slice$a.defineOperations(Dispatcher$1.CommSrv, Dispatcher$1.CommSrvPrx, iceC_Dispatcher_CommSrv_ids, 0); const iceC_Dispatcher_CommCli_ids = [ "::Dispatcher::CommCli", "::Ice::Object" ]; /** * 事件类型 * **/ Dispatcher$1.CommCli = class extends ice.Ice.Object {}; Dispatcher$1.CommCliPrx = class extends ice.Ice.ObjectPrx {}; Slice$a.defineOperations(Dispatcher$1.CommCli, Dispatcher$1.CommCliPrx, iceC_Dispatcher_CommCli_ids, 0); // const _ModuleRegistry$b = ice.Ice._ModuleRegistry; const Slice$b = ice.Ice.Slice; Dispatcher.TreeT = class { constructor(userId = "", groupnum = "", dnsprefix = "", type = 0) { this.userId = userId; this.groupnum = groupnum; this.dnsprefix = dnsprefix; this.type = type; } _write(ostr) { ostr.writeString(this.userId); ostr.writeString(this.groupnum); ostr.writeString(this.dnsprefix); ostr.writeInt(this.type); } _read(istr) { this.userId = istr.readString(); this.groupnum = istr.readString(); this.dnsprefix = istr.readString(); this.type = istr.readInt(); } static get minWireSize() { return 7; } }; Slice$b.defineStruct(Dispatcher.TreeT, true, true); const iceC_Dispatcher_UserT_ids = [ "::Dispatcher::UserT", "::Ice::Object" ]; Dispatcher.UserT = class extends ice.Ice.Value { constructor(userid = "", username = "", type = 8, dnsprefix = "", islocal = 0, rstate = Dispatcher.RegisterState.RegisterStateNone, cstate = Dispatcher.CallState.CallStateNone, othernumber = "", othername = "") { super(); this.userid = userid; this.username = username; this.type = type; this.dnsprefix = dnsprefix; this.islocal = islocal; this.rstate = rstate; this.cstate = cstate; this.othernumber = othernumber; this.othername = othername; } _iceWriteMemberImpl(ostr) { ostr.writeString(this.userid); ostr.writeString(this.username); ostr.writeInt(this.type); ostr.writeString(this.dnsprefix); ostr.writeInt(this.islocal); Dispatcher.RegisterState._write(ostr, this.rstate); Dispatcher.CallState._write(ostr, this.cstate); ostr.writeString(this.othernumber); ostr.writeString(this.othername); } _iceReadMemberImpl(istr) { this.userid = istr.readString(); this.username = istr.readString(); this.type = istr.readInt(); this.dnsprefix = istr.readString(); this.islocal = istr.readInt(); this.rstate = Dispatcher.RegisterState._read(istr); this.cstate = Dispatcher.CallState._read(istr); this.othernumber = istr.readString(); this.othername = istr.readString(); } }; Slice$b.defineValue(Dispatcher.UserT, iceC_Dispatcher_UserT_ids[0], false); Slice$b.defineSequence(Dispatcher, "UserSeqHelper", "Ice.ObjectHelper", false, "Dispatcher.UserT"); Slice$b.defineSequence(Dispatcher, "GroupSeqHelper", "Ice.ObjectHelper", false, "Dispatcher.GroupT"); const iceC_Dispatcher_GroupT_ids = [ "::Dispatcher::GroupT", "::Ice::Object" ]; Dispatcher.GroupT = class extends ice.Ice.Value { constructor(id = 0, groupnum = "", groupname = "", type = Dispatcher.GroupType.GroupTypeNone, user = null, group = null, dnsprefix = "", islocal = 0, canshowall = 0, level = 0) { super(); this.id = id; this.groupnum = groupnum; this.groupname = groupname; this.type = type; this.user = user; this.group = group; this.dnsprefix = dnsprefix; this.islocal = islocal; this.canshowall = canshowall; this.level = level; } _iceWriteMemberImpl(ostr) { ostr.writeInt(this.id); ostr.writeString(this.groupnum); ostr.writeString(this.groupname); Dispatcher.GroupType._write(ostr, this.type); Dispatcher.UserSeqHelper.write(ostr, this.user); Dispatcher.GroupSeqHelper.write(ostr, this.group); ostr.writeString(this.dnsprefix); ostr.writeInt(this.islocal); ostr.writeInt(this.canshowall); ostr.writeInt(this.level); } _iceReadMemberImpl(istr) { this.id = istr.readInt(); this.groupnum = istr.readString(); this.groupname = istr.readString(); this.type = Dispatcher.GroupType._read(istr); this.user = Dispatcher.UserSeqHelper.read(istr); this.group = Dispatcher.GroupSeqHelper.read(istr); this.dnsprefix = istr.readString(); this.islocal = istr.readInt(); this.canshowall = istr.readInt(); this.level = istr.readInt(); } }; Slice$b.defineValue(Dispatcher.GroupT, iceC_Dispatcher_GroupT_ids[0], false); const iceC_Dispatcher_TreeRT_ids = [ "::Dispatcher::TreeRT", "::Ice::Object" ]; Dispatcher.TreeRT = class extends ice.Ice.Value { constructor(roots = null) { super(); this.roots = roots; } _iceWriteMemberImpl(ostr) { Dispatcher.GroupSeqHelper.write(ostr, this.roots); } _iceReadMemberImpl(istr) { this.roots = Dispatcher.GroupSeqHelper.read(istr); } }; Slice$b.defineValue(Dispatcher.TreeRT, iceC_Dispatcher_TreeRT_ids[0], false); Dispatcher.VersionElem = class { constructor(name = "", type = "", version = "", time = "") { this.name = name; this.type = type; this.version = version; this.time = time; } _write(ostr) { ostr.writeString(this.name); ostr.writeString(this.type); ostr.writeString(this.version); ostr.writeString(this.time); } _read(istr) { this.name = istr.readString(); this.type = istr.readString(); this.version = istr.readString(); this.time = istr.readString(); } static get minWireSize() { return 4; } }; Slice$b.defineStruct(Dispatcher.VersionElem, true, true); Slice$b.defineSequence(Dispatcher, "VersionSeqHelper", "Dispatcher.VersionElem", false); Dispatcher.VersionEventT = class { constructor(vseq = null) { this.vseq = vseq; } _write(ostr) { Dispatcher.VersionSeqHelper.write(ostr, this.vseq); } _read(istr) { this.vseq = Dispatcher.VersionSeqHelper.read(istr); } static get minWireSize() { return 1; } }; Slice$b.defineStruct(Dispatcher.VersionEventT, true, true); Dispatcher.GetVersionT = class { constructor(dummy = "") { this.dummy = dummy; } _write(ostr) { ostr.writeString(this.dummy); } _read(istr) { this.dummy = istr.readString(); } static get minWireSize() { return 1; } }; Slice$b.defineStruct(Dispatcher.GetVersionT, true, true); Dispatcher.GetVersionRT = class { constructor(vseq = null) { this.vseq = vseq; } _write(ostr) { Dispatcher.VersionSeqHelper.write(ostr, this.vseq); } _read(istr) { this.vseq = Dispatcher.VersionSeqHelper.read(istr); } static get minWireSize() { return 1; } }; Slice$b.defineStruct(Dispatcher.GetVersionRT, true, true); // const _ModuleRegistry$c = ice.Ice._ModuleRegistry; const Slice$c = ice.Ice.Slice; const iceC_Dispatcher_ConfigureCB_ids = [ "::Dispatcher::ConfigureCB", "::Ice::Object" ]; Dispatcher.ConfigureCB = class extends ice.Ice.Object {}; Dispatcher.ConfigureCBPrx = class extends ice.Ice.ObjectPrx {}; Slice$c.defineOperations(Dispatcher.ConfigureCB, Dispatcher.ConfigureCBPrx, iceC_Dispatcher_ConfigureCB_ids, 0); const iceC_Dispatcher_ConfigureCBSub_ids = [ "::Dispatcher::ConfigureCBSub", "::Ice::Object" ]; Dispatcher.ConfigureCBSub = class extends ice.Ice.Object {}; Dispatcher.ConfigureCBSubPrx = class extends ice.Ice.ObjectPrx {}; Slice$c.defineOperations(Dispatcher.ConfigureCBSub, Dispatcher.ConfigureCBSubPrx, iceC_Dispatcher_ConfigureCBSub_ids, 0); // const _ModuleRegistry$d = ice.Ice._ModuleRegistry; const Slice$d = ice.Ice.Slice; const iceC_Dispatcher_FXDeviceNumberRT_ids = [ "::Dispatcher::FXDeviceNumberRT", "::Ice::Object" ]; Dispatcher.FXDeviceNumberRT = class extends ice.Ice.Value { constructor(dev = "", num = "", name = "", orgid = "", domain = "", latitude = "", longitude = "", remarks = "", status = 0) { super(); this.dev = dev; this.num = num; this.name = name; this.orgid = orgid; this.domain = domain; this.latitude = latitude; this.longitude = longitude; this.remarks = remarks; this.status = status; } _iceWriteMemberImpl(ostr) { ostr.writeString(this.dev); ostr.writeString(this.num); ostr.writeString(this.name); ostr.writeString(this.orgid); ostr.writeString(this.domain); ostr.writeString(this.latitude); ostr.writeString(this.longitude); ostr.writeString(this.remarks); ostr.writeInt(this.status); } _iceReadMemberImpl(istr) { this.dev = istr.readString(); this.num = istr.readString(); this.name = istr.readString(); this.orgid = istr.readString(); this.domain = istr.readString(); this.latitude = istr.readString(); this.longitude = istr.readString(); this.remarks = istr.readString(); this.status = istr.readInt(); } }; Slice$d.defineValue(Dispatcher.FXDeviceNumberRT, iceC_Dispatcher_FXDeviceNumberRT_ids[0], false); Slice$d.defineSequence(Dispatcher, "NumbersRTHelper", "Ice.ObjectHelper", false, "Dispatcher.FXDeviceNumberRT"); Slice$d.defineSequence(Dispatcher, "OrgsRTHelper", "Ice.ObjectHelper", false, "Dispatcher.FXOrgRT"); const iceC_Dispatcher_FXOrgRT_ids = [ "::Dispatcher::FXOrgRT", "::Ice::Object" ]; Dispatcher.FXOrgRT = class extends ice.Ice.Value { constructor(id = "", name = "", parentid = "", ldap = "", domain = "", remarks = "", ordernum = "", Orgs = null, Numbers = null) { super(); this.id = id; this.name = name; this.parentid = parentid; this.ldap = ldap; this.domain = domain; this.remarks = remarks; this.ordernum = ordernum; this.Orgs = Orgs; this.Numbers = Numbers; } _iceWriteMemberImpl(ostr) { ostr.writeString(this.id); ostr.writeString(this.name); ostr.writeString(this.parentid); ostr.writeString(this.ldap); ostr.writeString(this.domain); ostr.writeString(this.remarks); ostr.writeString(this.ordernum); Dispatcher.OrgsRTHelper.write(ostr, this.Orgs); Dispatcher.NumbersRTHelper.write(ostr, this.Numbers); } _iceReadMemberImpl(istr) { this.id = istr.readString(); this.name = istr.readString(); this.parentid = istr.readString(); this.ldap = istr.readString(); this.domain = istr.readString(); this.remarks = istr.readString(); this.ordernum = istr.readString(); this.Orgs = Dispatcher.OrgsRTHelper.read(istr); this.Numbers = Dispatcher.NumbersRTHelper.read(istr); } }; Slice$d.defineValue(Dispatcher.FXOrgRT, iceC_Dispatcher_FXOrgRT_ids[0], false); const iceC_Dispatcher_FXDeviceRT_ids = [ "::Dispatcher::FXDeviceRT", "::Ice::Object" ]; Dispatcher.FXDeviceRT = class extends ice.Ice.Value { constructor(id = "", name = "", remarks = "", Orgs = null) { super(); this.id = id; this.name = name; this.remarks = remarks; this.Orgs = Orgs; } _iceWriteMemberImpl(ostr) { ostr.writeString(this.id); ostr.writeString(this.name); ostr.writeString(this.remarks); Dispatcher.OrgsRTHelper.write(ostr, this.Orgs); } _iceReadMemberImpl(istr) { this.id = istr.readString(); this.name = istr.readString(); this.remarks = istr.readString(); this.Orgs = Dispatcher.OrgsRTHelper.read(istr); } }; Slice$d.defineValue(Dispatcher.FXDeviceRT, iceC_Dispatcher_FXDeviceRT_ids[0], false); Dispatcher.LocalDNSPrefixRT = class { constructor(prefix = "") { this.prefix = prefix; } _write(ostr) { ostr.writeString(this.prefix); } _read(istr) { this.prefix = istr.readString(); } static get minWireSize() { return 1; } }; Slice$d.defineStruct(Dispatcher.LocalDNSPrefixRT, true, true); Slice$d.defineSequence(Dispatcher, "FXDeviceSeqHelper", "Ice.ObjectHelper", false, "Dispatcher.FXDeviceRT"); Dispatcher.GetFXDeviceT = class { constructor(getdetail = true, remarks = "") { this.getdetail = getdetail; this.remarks = remarks; } _write(ostr) { ostr.writeBool(this.getdetail); ostr.writeString(this.remarks); } _read(istr) { this.getdetail = istr.readBool(); this.remarks = istr.readString(); } static get minWireSize() { return 2; } }; Slice$d.defineStruct(Dispatcher.GetFXDeviceT, true, true); Dispatcher.GetFXDeviceDetailT = class { constructor(fxDeviceid = "", orgid = "", remarks = "") { this.fxDeviceid = fxDeviceid; this.orgid = orgid; this.remarks = remarks; } _write(ostr) { ostr.writeString(this.fxDeviceid); ostr.writeString(this.orgid); ostr.writeString(this.remarks); } _read(istr) { this.fxDeviceid = istr.readString(); this.orgid = istr.readString(); this.remarks = istr.readString(); } static get minWireSize() { return 3; } }; Slice$d.defineStruct(Dispatcher.GetFXDeviceDetailT, true, true); Dispatcher.KeyConfig = class { constructor(Key = "", Value1 = "") { this.Key = Key; this.Value1 = Value1; } _write(ostr) { ostr.writeString(this.Key); ostr.writeString(this.Value1); } _read(istr) { this.Key = istr.readString(); this.Value1 = istr.readString(); } static get minWireSize() { return 2; } }; Slice$d.defineStruct(Dispatcher.KeyConfig, true, true); Slice$d.defineSequence(Dispatcher, "KeyConfigSeqHelper", "Dispatcher.KeyConfig", false); Dispatcher.MealConfig = class { constructor(id = 0, SetMealName = "", SetMealState = 0, Details = null) { this.id = id; this.SetMealName = SetMealName; this.SetMealState = SetMealState; this.Details = Details; } _write(ostr) { ostr.writeInt(this.id); ostr.writeString(this.SetMealName); ostr.writeInt(this.SetMealState); Dispatcher.KeyConfigSeqHelper.write(ostr, this.Details); } _read(istr) { this.id = istr.readInt(); this.SetMealName = istr.readString(); this.SetMealState = istr.readInt(); this.Details = Dispatcher.KeyConfigSeqHelper.read(istr); } static get minWireSize() { return 10; } }; Slice$d.defineStruct(Dispatcher.MealConfig, true, true); Dispatcher.KeyConfig1 = class { constructor(TheKey = "", TheValue = "") { this.TheKey = TheKey; this.TheValue = TheValue; } _write(ostr) { ostr.writeString(this.TheKey); ostr.writeString(this.TheValue); } _read(istr) { this.TheKey = istr.readString(); this.TheValue = istr.readString(); } static get minWireSize() { return 2; } }; Slice$d.defineStruct(Dispatcher.KeyConfig1, true, true); Slice$d.defineSequence(Dispatcher, "KeyConfigSeq1Helper", "Dispatcher.KeyConfig1", false); Dispatcher.MealConfig1 = class { constructor(id = 0, SetMealName = "", SetMealState = 0, Details = null) { this.id = id; this.SetMealName = SetMealName; this.SetMealState = SetMealState; this.Details = Details; } _write(ostr) { ostr.writeInt(this.id); ostr.writeString(this.SetMealName); ostr.writeInt(this.SetMealState); Dispatcher.KeyConfigSeq1Helper.write(ostr, this.Details); } _read(istr) { this.id = istr.readInt(); this.SetMealName = istr.readString(); this.SetMealState = istr.readInt(); this.Details = Dispatcher.KeyConfigSeq1Helper.read(istr); } static get minWireSize() { return 10; } }; Slice$d.defineStruct(Dispatcher.MealConfig1, true, true); const iceC_Dispatcher_ConfigureOP_ids = [ "::Dispatcher::ConfigureOP", "::Ice::Object" ]; Dispatcher.ConfigureOP = class extends ice.Ice.Object {}; Dispatcher.ConfigureOPPrx = class extends ice.Ice.ObjectPrx {}; Slice$d.defineOperations(Dispatcher.ConfigureOP, Dispatcher.ConfigureOPPrx, iceC_Dispatcher_ConfigureOP_ids, 0, { "IFCReqGetOrganization": [, , , , ["Dispatcher.TreeRT", true], [ [Dispatcher.Identity], [Dispatcher.TreeT] ], , [ Dispatcher.Error ], , true ], "IFCReqGetVersion": [, , , , [Dispatcher.GetVersionRT], [ [Dispatcher.Identity], [Dispatcher.GetVersionT] ], , [ Dispatcher.Error ], , ], "IFCReqGetLocalUserByType": [, , , , ["Dispatcher.TreeRT", true], [ [Dispatcher.Identity], [Dispatcher.TreeT] ], , [ Dispatcher.Error ], , true ], "IFCReqGet28181Devices": [, , , , ["Dispatcher.FXDeviceSeqHelper"], [ [Dispatcher.Identity], [Dispatcher.GetFXDeviceT] ], , [ Dispatcher.Error ], , true ], "IFCReqGet28181DeviceDetail": [, , , , ["Dispatcher.FXDeviceSeqHelper"], [ [Dispatcher.Identity], [Dispatcher.GetFXDeviceDetailT] ], , [ Dispatcher.Error ], , true ], "IFCReqGetConfigByKey": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetLocalPrefix": [, , , , [Dispatcher.LocalDNSPrefixRT], [ [Dispatcher.Identity] ], , [ Dispatcher.Error ], , ], "IFCReqGetConfigByKeys": [, , , , ["Dispatcher.KeyConfigSeqHelper"], [ [Dispatcher.Identity], ["Dispatcher.KeyConfigSeqHelper"] ], , [ Dispatcher.Error ], , ], "IFCReqGetMealConfig": [, , , , [Dispatcher.MealConfig], [ [Dispatcher.Identity] ], , [ Dispatcher.Error ], , ], "IFCReqGetConfigByKeys2": [, , , , ["Dispatcher.KeyConfigSeq1Helper"], [ [Dispatcher.Identity], ["Dispatcher.KeyConfigSeq1Helper"] ], , [ Dispatcher.Error ], , ], "IFCReqGetMealConfig2": [, , , , [Dispatcher.MealConfig1], [ [Dispatcher.Identity] ], , [ Dispatcher.Error ], , ], "IFCReqGetOrganizationByJson": [, , , , [7], [ [Dispatcher.Identity], [Dispatcher.TreeT] ], , [ Dispatcher.Error ], , ], "IFCReqGetGroupDetail": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqSetDeviceChange2": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetLicenseInfo": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetRecordInfo": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetEMServerInfo": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetEmployeeBindingNumbers": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ] }); const iceC_Dispatcher_ConfigureSB_ids = [ "::Dispatcher::ConfigureSB", "::Ice::Object" ]; Dispatcher.ConfigureSB = class extends ice.Ice.Object {}; Dispatcher.ConfigureSBPrx = class extends ice.Ice.ObjectPrx {}; Slice$d.defineOperations(Dispatcher.ConfigureSB, Dispatcher.ConfigureSBPrx, iceC_Dispatcher_ConfigureSB_ids, 0); // const _ModuleRegistry$e = ice.Ice._ModuleRegistry; const Slice$e = ice.Ice.Slice; Dispatcher.DecoderDeviceInfo = class { constructor(id = "", videoip = "", videoport = "", user = "", Password = "", showname = "", thetype = 0) { this.id = id; this.videoip = videoip; this.videoport = videoport; this.user = user; this.Password = Password; this.showname = showname; this.thetype = thetype; } _write(ostr) { ostr.writeString(this.id); ostr.writeString(this.videoip); ostr.writeString(this.videoport); ostr.writeString(this.user); ostr.writeString(this.Password); ostr.writeString(this.showname); ostr.writeInt(this.thetype); } _read(istr) { this.id = istr.readString(); this.videoip = istr.readString(); this.videoport = istr.readString(); this.user = istr.readString(); this.Password = istr.readString(); this.showname = istr.readString(); this.thetype = istr.readInt(); } static get minWireSize() { return 10; } }; Slice$e.defineStruct(Dispatcher.DecoderDeviceInfo, true, true); Slice$e.defineSequence(Dispatcher, "DecoderDeviceInfoSeqHelper", "Dispatcher.DecoderDeviceInfo", false); Dispatcher.DecoderDisplayChan = class { constructor(byChan = 0) { this.byChan = byChan; } _write(ostr) { ostr.writeByte(this.byChan); } _read(istr) { this.byChan = istr.readByte(); } static get minWireSize() { return 1; } }; Slice$e.defineStruct(Dispatcher.DecoderDisplayChan, true, false); Slice$e.defineSequence(Dispatcher, "DecoderDisplayChanSeqHelper", "Dispatcher.DecoderDisplayChan", true); Dispatcher.DecoderDisplayCfg = class { constructor(Channelid = 0, dwWindowMode = 0, byAudio = 0, byVedioFormat = 0, dwResolution = 0, byJoinDecChans = null, byDispChanType = 0) { this.Channelid = Channelid; this.dwWindowMode = dwWindowMode; this.byAudio = byAudio; this.byVedioFormat = byVedioFormat; this.dwResolution = dwResolution; this.byJoinDecChans = byJoinDecChans; this.byDispChanType = byDispChanType; } _write(ostr) { ostr.writeInt(this.Channelid); ostr.writeInt(this.dwWindowMode); ostr.writeByte(this.byAudio); ostr.writeByte(this.byVedioFormat); ostr.writeInt(this.dwResolution); Dispatcher.DecoderDisplayChanSeqHelper.write(ostr, this.byJoinDecChans); ostr.writeByte(this.byDispChanType); } _read(istr) { this.Channelid = istr.readInt(); this.dwWindowMode = istr.readInt(); this.byAudio = istr.readByte(); this.byVedioFormat = istr.readByte(); this.dwResolution = istr.readInt(); this.byJoinDecChans = Dispatcher.DecoderDisplayChanSeqHelper.read(istr); this.byDispChanType = istr.readByte(); } static get minWireSize() { return 16; } }; Slice$e.defineStruct(Dispatcher.DecoderDisplayCfg, true, true); Slice$e.defineSequence(Dispatcher, "DecoderDisplayCfgSeqHelper", "Dispatcher.DecoderDisplayCfg", false); // const _ModuleRegistry$f = ice.Ice._ModuleRegistry; const Slice$f = ice.Ice.Slice; const iceC_Dispatcher_DecoderCB_ids = [ "::Dispatcher::DecoderCB", "::Ice::Object" ]; Dispatcher.DecoderCB = class extends ice.Ice.Object {}; Dispatcher.DecoderCBPrx = class extends ice.Ice.ObjectPrx {}; Slice$f.defineOperations(Dispatcher.DecoderCB, Dispatcher.DecoderCBPrx, iceC_Dispatcher_DecoderCB_ids, 0); // const _ModuleRegistry$g = ice.Ice._ModuleRegistry; const Slice$g = ice.Ice.Slice; Dispatcher.GetDisplayCfg = class { constructor(Decoderid = "") { this.Decoderid = Decoderid; } _write(ostr) { ostr.writeString(this.Decoderid); } _read(istr) { this.Decoderid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$g.defineStruct(Dispatcher.GetDisplayCfg, true, true); Dispatcher.SetDecoderCfg = class { constructor(Decoderid = "", Cfg = new Dispatcher.DecoderDisplayCfg()) { this.Decoderid = Decoderid; this.Cfg = Cfg; } _write(ostr) { ostr.writeString(this.Decoderid); Dispatcher.DecoderDisplayCfg.write(ostr, this.Cfg); } _read(istr) { this.Decoderid = istr.readString(); this.Cfg = Dispatcher.DecoderDisplayCfg.read(istr, this.Cfg); } static get minWireSize() { return 17; } }; Slice$g.defineStruct(Dispatcher.SetDecoderCfg, true, true); Dispatcher.RetDecoderAllCfg = class { constructor(Decoderid = "", Cfgs = null) { this.Decoderid = Decoderid; this.Cfgs = Cfgs; } _write(ostr) { ostr.writeString(this.Decoderid); Dispatcher.DecoderDisplayCfgSeqHelper.write(ostr, this.Cfgs); } _read(istr) { this.Decoderid = istr.readString(); this.Cfgs = Dispatcher.DecoderDisplayCfgSeqHelper.read(istr); } static get minWireSize() { return 2; } }; Slice$g.defineStruct(Dispatcher.RetDecoderAllCfg, true, true); Dispatcher.opDecoderInfo = class { constructor(Decoderid = "", Channel = "", cid = "", disNumber = "") { this.Decoderid = Decoderid; this.Channel = Channel; this.cid = cid; this.disNumber = disNumber; } _write(ostr) { ostr.writeString(this.Decoderid); ostr.writeString(this.Channel); ostr.writeString(this.cid); ostr.writeString(this.disNumber); } _read(istr) { this.Decoderid = istr.readString(); this.Channel = istr.readString(); this.cid = istr.readString(); this.disNumber = istr.readString(); } static get minWireSize() { return 4; } }; Slice$g.defineStruct(Dispatcher.opDecoderInfo, true, true); Dispatcher.opTransferRTPInfo = class { constructor(cid = "", Number = "", disip = "", disport = 0) { this.cid = cid; this.Number = Number; this.disip = disip; this.disport = disport; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.Number); ostr.writeString(this.disip); ostr.writeInt(this.disport); } _read(istr) { this.cid = istr.readString(); this.Number = istr.readString(); this.disip = istr.readString(); this.disport = istr.readInt(); } static get minWireSize() { return 7; } }; Slice$g.defineStruct(Dispatcher.opTransferRTPInfo, true, true); Dispatcher.opDecoderByUrlInfo = class { constructor(Decoderid = "", Channel = "", url = "") { this.Decoderid = Decoderid; this.Channel = Channel; this.url = url; } _write(ostr) { ostr.writeString(this.Decoderid); ostr.writeString(this.Channel); ostr.writeString(this.url); } _read(istr) { this.Decoderid = istr.readString(); this.Channel = istr.readString(); this.url = istr.readString(); } static get minWireSize() { return 3; } }; Slice$g.defineStruct(Dispatcher.opDecoderByUrlInfo, true, true); Dispatcher.opDecoderByVideoInfo = class { constructor(Decoderid = "", Channel = "", VideoUser = "", VideoPwd = "", VideoIP = "", VideoPort = "", VideoChannel = "", VideoType = Dispatcher.emVideoDeviceType.VDTNONE) { this.Decoderid = Decoderid; this.Channel = Channel; this.VideoUser = VideoUser; this.VideoPwd = VideoPwd; this.VideoIP = VideoIP; this.VideoPort = VideoPort; this.VideoChannel = VideoChannel; this.VideoType = VideoType; } _write(ostr) { ostr.writeString(this.Decoderid); ostr.writeString(this.Channel); ostr.writeString(this.VideoUser); ostr.writeString(this.VideoPwd); ostr.writeString(this.VideoIP); ostr.writeString(this.VideoPort); ostr.writeString(this.VideoChannel); Dispatcher.emVideoDeviceType._write(ostr, this.VideoType); } _read(istr) { this.Decoderid = istr.readString(); this.Channel = istr.readString(); this.VideoUser = istr.readString(); this.VideoPwd = istr.readString(); this.VideoIP = istr.readString(); this.VideoPort = istr.readString(); this.VideoChannel = istr.readString(); this.VideoType = Dispatcher.emVideoDeviceType._read(istr); } static get minWireSize() { return 8; } }; Slice$g.defineStruct(Dispatcher.opDecoderByVideoInfo, true, true); Dispatcher.opChannelStatus = class { constructor(Decoderid = "", Channel = "") { this.Decoderid = Decoderid; this.Channel = Channel; } _write(ostr) { ostr.writeString(this.Decoderid); ostr.writeString(this.Channel); } _read(istr) { this.Decoderid = istr.readString(); this.Channel = istr.readString(); } static get minWireSize() { return 2; } }; Slice$g.defineStruct(Dispatcher.opChannelStatus, true, true); Dispatcher.RetDecoderAbility = class { constructor(Decoderid = "", VideoType = Dispatcher.emVideoDeviceType.VDTNONE, InChannelsNum = 0) { this.Decoderid = Decoderid; this.VideoType = VideoType; this.InChannelsNum = InChannelsNum; } _write(ostr) { ostr.writeString(this.Decoderid); Dispatcher.emVideoDeviceType._write(ostr, this.VideoType); ostr.writeInt(this.InChannelsNum); } _read(istr) { this.Decoderid = istr.readString(); this.VideoType = Dispatcher.emVideoDeviceType._read(istr); this.InChannelsNum = istr.readInt(); } static get minWireSize() { return 6; } }; Slice$g.defineStruct(Dispatcher.RetDecoderAbility, true, true); const iceC_Dispatcher_DecoderOP_ids = [ "::Dispatcher::DecoderOP", "::Ice::Object" ]; Dispatcher.DecoderOP = class extends ice.Ice.Object {}; Dispatcher.DecoderOPPrx = class extends ice.Ice.ObjectPrx {}; Slice$g.defineOperations(Dispatcher.DecoderOP, Dispatcher.DecoderOPPrx, iceC_Dispatcher_DecoderOP_ids, 0, { "IFCReqGetDecoderDevice": [, , , , ["Dispatcher.DecoderDeviceInfoSeqHelper"], [ [Dispatcher.Identity] ], , [ Dispatcher.Error ], , ], "IFCReqGetDisplayConfig": [, , , , [Dispatcher.RetDecoderAllCfg], [ [Dispatcher.Identity], [Dispatcher.GetDisplayCfg] ], , , , ], "IFCReqGetDecoderAbility": [, , , , [Dispatcher.RetDecoderAbility], [ [Dispatcher.Identity], [Dispatcher.GetDisplayCfg] ], , , , ], "IFCReqGetChannelDecodeState": [, , , , [1], [ [Dispatcher.Identity], [Dispatcher.opChannelStatus] ], , , , ], "IFCReqSetDisplayConfig": [, , , , [1], [ [Dispatcher.Identity], [Dispatcher.SetDecoderCfg] ], , , , ], "IFCReqStartDecode": [, , , , [1], [ [Dispatcher.Identity], [Dispatcher.opDecoderInfo] ], , , , ], "IFCReqStartDecodeByJson": [, , , , [1], [ [Dispatcher.Identity], [7] ], , , , ], "IFCReqStartDecodeByURL": [, , , , [1], [ [Dispatcher.Identity], [Dispatcher.opDecoderByUrlInfo] ], , , , ], "IFCReqStopDecode": [, , , , [1], [ [Dispatcher.Identity], [Dispatcher.opDecoderInfo] ], , , , ], "IFCReqStopDecodeByURL": [, , , , [1], [ [Dispatcher.Identity], [Dispatcher.opDecoderByUrlInfo] ], , , , ], "IFCReqTransferRtp": [, , , , [1], [ [Dispatcher.Identity], [Dispatcher.opTransferRTPInfo] ], , , , ], "IFCReqStopTransferRtp": [, , , , [1], [ [Dispatcher.Identity], [Dispatcher.opTransferRTPInfo] ], , , , ], "IFCReqStartDecodeByVideoInfo": [, , , , [1], [ [Dispatcher.Identity], [Dispatcher.opDecoderByVideoInfo] ], , , , ], "IFCReqStopDecodeByVideoInfo": [, , , , [1], [ [Dispatcher.Identity], [Dispatcher.opDecoderByVideoInfo] ], , , , ], "IFCReqGetDisplayConfig2": [, , , , [7], [ [Dispatcher.Identity], [Dispatcher.GetDisplayCfg] ], , , , ], "IFCReqSetWindows": [, , , , [7], [ [Dispatcher.Identity], [7], [7] ], , , , ], "IFCReqGetSubWindowsStatus": [, , , , [7], [ [Dispatcher.Identity], [7], [7] ], , , , ], "IFCReqSetDisplayPosition": [, , , , [1], [ [Dispatcher.Identity], [7], [7] ], , , , ], "IFCReqSetScreenMode": [, , , , [1], [ [Dispatcher.Identity], [7], [7] ], , , , ] }); // const _ModuleRegistry$h = ice.Ice._ModuleRegistry; const Slice$h = ice.Ice.Slice; let EM = _ModuleRegistry$h.module("EM"); EM.EMError = class extends ice.Ice.UserException { constructor(code = 0, desc = "", _cause = "") { super(_cause); this.code = code; this.desc = desc; } static get _parent() { return ice.Ice.UserException; } static get _id() { return "::EM::EMError"; } _mostDerivedType() { return EM.EMError; } _writeMemberImpl(ostr) { ostr.writeInt(this.code); ostr.writeString(this.desc); } _readMemberImpl(istr) { this.code = istr.readInt(); this.desc = istr.readString(); } }; // const _ModuleRegistry$i = ice.Ice._ModuleRegistry; const Slice$i = ice.Ice.Slice; let EM$1 = _ModuleRegistry$i.module("EM"); EM$1.EMIdentity = class { constructor(user = "") { this.user = user; } _write(ostr) { ostr.writeString(this.user); } _read(istr) { this.user = istr.readString(); } static get minWireSize() { return 1; } }; Slice$i.defineStruct(EM$1.EMIdentity, true, true); // const _ModuleRegistry$j = ice.Ice._ModuleRegistry; const Slice$j = ice.Ice.Slice; const iceC_EM_EMEventCB_ids = [ "::EM::EMEventCB", "::Ice::Object" ]; EM.EMEventCB = class extends ice.Ice.Object {}; EM.EMEventCBPrx = class extends ice.Ice.ObjectPrx {}; Slice$j.defineOperations(EM.EMEventCB, EM.EMEventCBPrx, iceC_EM_EMEventCB_ids, 0, { "EMCBNotifyNewEvent": [, 2, 2, , , [ [7] ], , [ EM.EMError ], , ], "EMCBNotifyEventStateChanged": [, 2, 2, , , [ [7] ], , [ EM.EMError ], , ], "EMCBNotifyNewTask": [, 2, 2, , , [ [7] ], , [ EM.EMError ], , ], "EMCBNotifyTaskStateChanged": [, 2, 2, , , [ [7] ], , [ EM.EMError ], , ] }); // const _ModuleRegistry$k = ice.Ice._ModuleRegistry; const Slice$k = ice.Ice.Slice; const iceC_EM_EMMaterialCB_ids = [ "::EM::EMMaterialCB", "::Ice::Object" ]; EM.EMMaterialCB = class extends ice.Ice.Object {}; EM.EMMaterialCBPrx = class extends ice.Ice.ObjectPrx {}; Slice$k.defineOperations(EM.EMMaterialCB, EM.EMMaterialCBPrx, iceC_EM_EMMaterialCB_ids, 0, { "EMCBNotifyWarehouseChanged": [, 2, 2, , , [ [7], [7] ], , [ EM.EMError ], , ], "EMCBNotifyMaterialChanged": [, 2, 2, , , [ [7], [7] ], , [ EM.EMError ], , ] }); // const _ModuleRegistry$l = ice.Ice._ModuleRegistry; const Slice$l = ice.Ice.Slice; const iceC_EM_EMCli_ids = [ "::EM::EMCli", "::EM::EMEventCB", "::EM::EMMaterialCB", "::Ice::Object" ]; EM.EMCli = class extends ice.Ice.Object { static get _iceImplements() { return [ EM.EMEventCB, EM.EMMaterialCB ]; } }; EM.EMCliPrx = class extends ice.Ice.ObjectPrx { static get _implements() { return [ EM.EMEventCBPrx, EM.EMMaterialCBPrx ]; } }; Slice$l.defineOperations(EM.EMCli, EM.EMCliPrx, iceC_EM_EMCli_ids, 0, { "EMHeartbeatCB": [, 2, 2, , , [ [7] ], , [ EM.EMError ], , ], "EMDataChangedCB": [, 2, 2, , , [ [7] ], , [ EM.EMError ], , ] }); // const _ModuleRegistry$m = ice.Ice._ModuleRegistry; const Slice$m = ice.Ice.Slice; const iceC_EM_EMDutyOP_ids = [ "::EM::EMDutyOP", "::Ice::Object" ]; EM.EMDutyOP = class extends ice.Ice.Object {}; EM.EMDutyOPPrx = class extends ice.Ice.ObjectPrx {}; Slice$m.defineOperations(EM.EMDutyOP, EM.EMDutyOPPrx, iceC_EM_EMDutyOP_ids, 0, { "EMDutyAddOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMDutyDelOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMDutyFixOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMDutyGetOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ] }); // const _ModuleRegistry$n = ice.Ice._ModuleRegistry; const Slice$n = ice.Ice.Slice; const iceC_EM_EMEventOP_ids = [ "::EM::EMEventOP", "::Ice::Object" ]; EM.EMEventOP = class extends ice.Ice.Object {}; EM.EMEventOPPrx = class extends ice.Ice.ObjectPrx {}; Slice$n.defineOperations(EM.EMEventOP, EM.EMEventOPPrx, iceC_EM_EMEventOP_ids, 0, { "EMEventGetParam": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMEventReportOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMEventViewOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMEventConfirmOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMEventStartProcessOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMEventProcessOverOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMEventDistributeOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMEventReturnOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMGetEventsOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMGetTaskBySelfOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMGetEventDetialOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMGetStatisticsDataByEmployeeOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMGetStatisticsDataByStateOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMGetStatisticsDataByLevelOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMGetStatisticsDataByTypeOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ] }); // const _ModuleRegistry$o = ice.Ice._ModuleRegistry; const Slice$o = ice.Ice.Slice; const iceC_EM_EMIFCCli_ids = [ "::EM::EMIFCCli", "::Ice::Object" ]; EM.EMIFCCli = class extends ice.Ice.Object {}; EM.EMIFCCliPrx = class extends ice.Ice.ObjectPrx {}; Slice$o.defineOperations(EM.EMIFCCli, EM.EMIFCCliPrx, iceC_EM_EMIFCCli_ids, 0, { "EMCBSendDBChange": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMCBHeartBeat": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ] }); // const _ModuleRegistry$p = ice.Ice._ModuleRegistry; const Slice$p = ice.Ice.Slice; const iceC_EM_EMIFCSrv_ids = [ "::EM::EMIFCSrv", "::Ice::Object" ]; EM.EMIFCSrv = class extends ice.Ice.Object {}; EM.EMIFCSrvPrx = class extends ice.Ice.ObjectPrx {}; Slice$p.defineOperations(EM.EMIFCSrv, EM.EMIFCSrvPrx, iceC_EM_EMIFCSrv_ids, 0, { "EMOPSetClientInfo": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ] }); // const _ModuleRegistry$q = ice.Ice._ModuleRegistry; const Slice$q = ice.Ice.Slice; const iceC_EM_EMMaterialOP_ids = [ "::EM::EMMaterialOP", "::Ice::Object" ]; EM.EMMaterialOP = class extends ice.Ice.Object {}; EM.EMMaterialOPPrx = class extends ice.Ice.ObjectPrx {}; Slice$q.defineOperations(EM.EMMaterialOP, EM.EMMaterialOPPrx, iceC_EM_EMMaterialOP_ids, 0, { "EMMaterialAddWareHouseOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMMaterialDelWareHouseOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMMaterialFixWareHouseInfoOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMMaterialGetWareHouseOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMMaterialAddMaterialOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMMaterialDelMaterialOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMMaterialFixMaterialInfoOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMMaterialGetMaterialOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ] }); // const _ModuleRegistry$r = ice.Ice._ModuleRegistry; const Slice$r = ice.Ice.Slice; const iceC_EM_EMPlanOP_ids = [ "::EM::EMPlanOP", "::Ice::Object" ]; EM.EMPlanOP = class extends ice.Ice.Object {}; EM.EMPlanOPPrx = class extends ice.Ice.ObjectPrx {}; Slice$r.defineOperations(EM.EMPlanOP, EM.EMPlanOPPrx, iceC_EM_EMPlanOP_ids, 0, { "EMPlanGetFilesOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ] }); // const _ModuleRegistry$s = ice.Ice._ModuleRegistry; const Slice$s = ice.Ice.Slice; const iceC_EM_EMSrv_ids = [ "::EM::EMDutyOP", "::EM::EMEventOP", "::EM::EMMaterialOP", "::EM::EMPlanOP", "::EM::EMSrv", "::Ice::Object" ]; EM.EMSrv = class extends ice.Ice.Object { static get _iceImplements() { return [ EM.EMEventOP, EM.EMPlanOP, EM.EMMaterialOP, EM.EMDutyOP ]; } }; EM.EMSrvPrx = class extends ice.Ice.ObjectPrx { static get _implements() { return [ EM.EMEventOPPrx, EM.EMPlanOPPrx, EM.EMMaterialOPPrx, EM.EMDutyOPPrx ]; } }; Slice$s.defineOperations(EM.EMSrv, EM.EMSrvPrx, iceC_EM_EMSrv_ids, 4, { "EMRegisterOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMUnRegisterOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ], "EMHeartbeatOP": [, 2, 2, , [7], [ [EM.EMIdentity], [7] ], , [ EM.EMError ], , ] }); // const _ModuleRegistry$t = ice.Ice._ModuleRegistry; const Slice$t = ice.Ice.Slice; let Dispatcher$2 = _ModuleRegistry$t.module("Dispatcher"); Object.defineProperty(Dispatcher$2, 'EventEmployeeStateReg', { value: "Employee.State.Reg" }); Object.defineProperty(Dispatcher$2, 'EventEmployeeStateCall', { value: "Employee.State.Call" }); Object.defineProperty(Dispatcher$2, 'EventPttState', { value: "Ptt.State" }); Object.defineProperty(Dispatcher$2, 'EventPttStateSpeaker', { value: "Ptt.State.Speaker" }); Object.defineProperty(Dispatcher$2, 'EventPttWaiting', { value: "Ptt.Waiting" }); Object.defineProperty(Dispatcher$2, 'EventPttReject', { value: "Ptt.Reject" }); Object.defineProperty(Dispatcher$2, 'EventHistoryVideoInfo', { value: "Video.Role.History.Info" }); Object.defineProperty(Dispatcher$2, 'EventSessionStateChange', { value: "Session.State.Change" }); Object.defineProperty(Dispatcher$2, 'EventSessionMemberChange', { value: "Session.Member.Change" }); Object.defineProperty(Dispatcher$2, 'EventSessionSendToCreater', { value: "Session.SendToCreater.State" }); Object.defineProperty(Dispatcher$2, 'EventSessionSendToAllDTP', { value: "Session.SendToAllDTP.State" }); Object.defineProperty(Dispatcher$2, 'EventSessionMemberToAllDTP', { value: "Session.SendMemberToAllDTP.State" }); Object.defineProperty(Dispatcher$2, 'EventSessionStateChangeFixMeeting', { value: "Session.State.Change.FixMeeting" }); Object.defineProperty(Dispatcher$2, 'EventSessionMemberChangeFixMeeting', { value: "Session.Member.Change.FixMeeting" }); Object.defineProperty(Dispatcher$2, 'EventCallVideoGetVideoEvent', { value: "CallVideo.GetVideo.Event" }); Object.defineProperty(Dispatcher$2, 'EventBusFileOnReceive', { value: "BusFile.OnReceive" }); Object.defineProperty(Dispatcher$2, 'EventCALLPLAYAUDIOCB', { value: "CallPlay.Audio.CB" }); Object.defineProperty(Dispatcher$2, 'EventGisPositionChange', { value: "GIS.Position.Change" }); Object.defineProperty(Dispatcher$2, 'EventFileMsgOnReceive', { value: "FileMsg.OnReceive" }); Object.defineProperty(Dispatcher$2, 'EventMsgOnReceive', { value: "Msg.OnReceive" }); Object.defineProperty(Dispatcher$2, 'EventEmployeeChannelChange', { value: "Employee.Relay.ChannelChange" }); Object.defineProperty(Dispatcher$2, 'EventDBChangeGroupChange', { value: "DB.Group.Change" }); Object.defineProperty(Dispatcher$2, 'EventRegistKickout', { value: "Regist.Kickout.Event" }); Object.defineProperty(Dispatcher$2, 'EventPushCallAudioToOther', { value: "Push.Call.Audio.To.Other" }); // const _ModuleRegistry$u = ice.Ice._ModuleRegistry; const Slice$u = ice.Ice.Slice; Dispatcher.FaxT = class { constructor(fid = "", fname = "", srcnum = "", dstnum = "") { this.fid = fid; this.fname = fname; this.srcnum = srcnum; this.dstnum = dstnum; } _write(ostr) { ostr.writeString(this.fid); ostr.writeString(this.fname); ostr.writeString(this.srcnum); ostr.writeString(this.dstnum); } _read(istr) { this.fid = istr.readString(); this.fname = istr.readString(); this.srcnum = istr.readString(); this.dstnum = istr.readString(); } static get minWireSize() { return 4; } }; Slice$u.defineStruct(Dispatcher.FaxT, true, true); Dispatcher.FaxRT = class { constructor(fid = "", fname = "", fpath = "") { this.fid = fid; this.fname = fname; this.fpath = fpath; } _write(ostr) { ostr.writeString(this.fid); ostr.writeString(this.fname); ostr.writeString(this.fpath); } _read(istr) { this.fid = istr.readString(); this.fname = istr.readString(); this.fpath = istr.readString(); } static get minWireSize() { return 3; } }; Slice$u.defineStruct(Dispatcher.FaxRT, true, true); Dispatcher.FaxEvT = class { constructor(fid = "", code = Dispatcher.FileState.FileStateNone) { this.fid = fid; this.code = code; } _write(ostr) { ostr.writeString(this.fid); Dispatcher.FileState._write(ostr, this.code); } _read(istr) { this.fid = istr.readString(); this.code = Dispatcher.FileState._read(istr); } static get minWireSize() { return 2; } }; Slice$u.defineStruct(Dispatcher.FaxEvT, true, true); Dispatcher.FaxEv2T = class { constructor(fid = "", code = Dispatcher.FaxStateSend.FaxStateSendNone) { this.fid = fid; this.code = code; } _write(ostr) { ostr.writeString(this.fid); Dispatcher.FaxStateSend._write(ostr, this.code); } _read(istr) { this.fid = istr.readString(); this.code = Dispatcher.FaxStateSend._read(istr); } static get minWireSize() { return 2; } }; Slice$u.defineStruct(Dispatcher.FaxEv2T, true, true); Dispatcher.NewFaxEvT = class { constructor(fid = "") { this.fid = fid; } _write(ostr) { ostr.writeString(this.fid); } _read(istr) { this.fid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$u.defineStruct(Dispatcher.NewFaxEvT, true, true); // const _ModuleRegistry$v = ice.Ice._ModuleRegistry; const Slice$v = ice.Ice.Slice; const iceC_Dispatcher_FaxCB_ids = [ "::Dispatcher::FaxCB", "::Ice::Object" ]; Dispatcher.FaxCB = class extends ice.Ice.Object {}; Dispatcher.FaxCBPrx = class extends ice.Ice.ObjectPrx {}; Slice$v.defineOperations(Dispatcher.FaxCB, Dispatcher.FaxCBPrx, iceC_Dispatcher_FaxCB_ids, 0, { "IFCNotifyFaxEvt": [, 2, 2, , , [ [Dispatcher.FaxEv2T] ], , , , ], "IFCNotifyNewFaxEvt": [, 2, 2, , , [ [Dispatcher.NewFaxEvT] ], , , , ] }); // const _ModuleRegistry$w = ice.Ice._ModuleRegistry; const Slice$w = ice.Ice.Slice; const iceC_Dispatcher_FaxOP_ids = [ "::Dispatcher::FaxOP", "::Ice::Object" ]; Dispatcher.FaxOP = class extends ice.Ice.Object {}; Dispatcher.FaxOPPrx = class extends ice.Ice.ObjectPrx {}; Slice$w.defineOperations(Dispatcher.FaxOP, Dispatcher.FaxOPPrx, iceC_Dispatcher_FaxOP_ids, 0, { "IFCReqSendFax": [, , , , [Dispatcher.FaxRT], [ [Dispatcher.Identity], [Dispatcher.FaxT] ], , [ Dispatcher.Error ], , ] }); // const _ModuleRegistry$x = ice.Ice._ModuleRegistry; const Slice$x = ice.Ice.Slice; let Fax = _ModuleRegistry$x.module("Fax"); Fax.FaxDirectType = Slice$x.defineEnum([ ['FaxDirectTypeSend', 0], ['FaxDirectTypeRecv', 1] ]); Fax.Error = class extends ice.Ice.UserException { constructor(fid = "", code = 0, desc = "", _cause = "") { super(_cause); this.fid = fid; this.code = code; this.desc = desc; } static get _parent() { return ice.Ice.UserException; } static get _id() { return "::Fax::Error"; } _mostDerivedType() { return Fax.Error; } _writeMemberImpl(ostr) { ostr.writeString(this.fid); ostr.writeInt(this.code); ostr.writeString(this.desc); } _readMemberImpl(istr) { this.fid = istr.readString(); this.code = istr.readInt(); this.desc = istr.readString(); } }; Fax.FaxOriginateT = class { constructor(fid = "", srcip = "", srcport = 0, srcpath = "", srcuser = "", dstip = "", dstport = 0, dstpath = "", dstuser = "", direct = Fax.FaxDirectType.FaxDirectTypeSend) { this.fid = fid; this.srcip = srcip; this.srcport = srcport; this.srcpath = srcpath; this.srcuser = srcuser; this.dstip = dstip; this.dstport = dstport; this.dstpath = dstpath; this.dstuser = dstuser; this.direct = direct; } _write(ostr) { ostr.writeString(this.fid); ostr.writeString(this.srcip); ostr.writeInt(this.srcport); ostr.writeString(this.srcpath); ostr.writeString(this.srcuser); ostr.writeString(this.dstip); ostr.writeInt(this.dstport); ostr.writeString(this.dstpath); ostr.writeString(this.dstuser); Fax.FaxDirectType._write(ostr, this.direct); } _read(istr) { this.fid = istr.readString(); this.srcip = istr.readString(); this.srcport = istr.readInt(); this.srcpath = istr.readString(); this.srcuser = istr.readString(); this.dstip = istr.readString(); this.dstport = istr.readInt(); this.dstpath = istr.readString(); this.dstuser = istr.readString(); this.direct = Fax.FaxDirectType._read(istr); } static get minWireSize() { return 16; } }; Slice$x.defineStruct(Fax.FaxOriginateT, true, true); Fax.FaxFeedbackT = class { constructor(fid = "", direct = 0, code = 0, msg = "", tiffname = "", tiffpath = "") { this.fid = fid; this.direct = direct; this.code = code; this.msg = msg; this.tiffname = tiffname; this.tiffpath = tiffpath; } _write(ostr) { ostr.writeString(this.fid); ostr.writeInt(this.direct); ostr.writeInt(this.code); ostr.writeString(this.msg); ostr.writeString(this.tiffname); ostr.writeString(this.tiffpath); } _read(istr) { this.fid = istr.readString(); this.direct = istr.readInt(); this.code = istr.readInt(); this.msg = istr.readString(); this.tiffname = istr.readString(); this.tiffpath = istr.readString(); } static get minWireSize() { return 12; } }; Slice$x.defineStruct(Fax.FaxFeedbackT, true, true); const iceC_Fax_FaxServer_ids = [ "::Fax::FaxServer", "::Ice::Object" ]; Fax.FaxServer = class extends ice.Ice.Object {}; Fax.FaxServerPrx = class extends ice.Ice.ObjectPrx {}; Slice$x.defineOperations(Fax.FaxServer, Fax.FaxServerPrx, iceC_Fax_FaxServer_ids, 0, { "faxOriginate": [, , , , [Fax.FaxFeedbackT], [ [Fax.FaxOriginateT] ], , [ Fax.Error ], , ] }); // const _ModuleRegistry$y = ice.Ice._ModuleRegistry; const Slice$y = ice.Ice.Slice; Dispatcher.UploadEvent2T = class { constructor(snum = "", dnum = null, fname = "", fid = "", fpath = "", state = Dispatcher.FileState.FileStateNone, ftype = Dispatcher.FileType.FileTypeNone, sendtime = "") { this.snum = snum; this.dnum = dnum; this.fname = fname; this.fid = fid; this.fpath = fpath; this.state = state; this.ftype = ftype; this.sendtime = sendtime; } _write(ostr) { ostr.writeString(this.snum); ice.Ice.StringSeqHelper.write(ostr, this.dnum); ostr.writeString(this.fname); ostr.writeString(this.fid); ostr.writeString(this.fpath); Dispatcher.FileState._write(ostr, this.state); Dispatcher.FileType._write(ostr, this.ftype); ostr.writeString(this.sendtime); } _read(istr) { this.snum = istr.readString(); this.dnum = ice.Ice.StringSeqHelper.read(istr); this.fname = istr.readString(); this.fid = istr.readString(); this.fpath = istr.readString(); this.state = Dispatcher.FileState._read(istr); this.ftype = Dispatcher.FileType._read(istr); this.sendtime = istr.readString(); } static get minWireSize() { return 8; } }; Slice$y.defineStruct(Dispatcher.UploadEvent2T, true, true); Slice$y.defineSequence(Dispatcher, "UploadEvent2SeqHelper", "Dispatcher.UploadEvent2T", false); // const _ModuleRegistry$z = ice.Ice._ModuleRegistry; const Slice$z = ice.Ice.Slice; const iceC_Dispatcher_FileCB_ids = [ "::Dispatcher::FileCB", "::Ice::Object" ]; Dispatcher.FileCB = class extends ice.Ice.Object {}; Dispatcher.FileCBPrx = class extends ice.Ice.ObjectPrx {}; Slice$z.defineOperations(Dispatcher.FileCB, Dispatcher.FileCBPrx, iceC_Dispatcher_FileCB_ids, 0, { "IFCNotifyUploadEvt": [, 2, 2, , , [ [Dispatcher.UploadEvent2T] ], , , , ], "IFCNotifyDeleteFileEvt": [, 2, 2, , , [ [7] ], , , , ] }); // const _ModuleRegistry$A = ice.Ice._ModuleRegistry; const Slice$A = ice.Ice.Slice; Dispatcher.ApplyUploadET = class { constructor(fid = "", fname = "", ftype = Dispatcher.FileType.FileTypeNone) { this.fid = fid; this.fname = fname; this.ftype = ftype; } _write(ostr) { ostr.writeString(this.fid); ostr.writeString(this.fname); Dispatcher.FileType._write(ostr, this.ftype); } _read(istr) { this.fid = istr.readString(); this.fname = istr.readString(); this.ftype = Dispatcher.FileType._read(istr); } static get minWireSize() { return 3; } }; Slice$A.defineStruct(Dispatcher.ApplyUploadET, true, true); Slice$A.defineSequence(Dispatcher, "ApplyUploadESeqHelper", "Dispatcher.ApplyUploadET", false); Dispatcher.ApplyUploadT = class { constructor(recv = null, file = new Dispatcher.ApplyUploadET()) { this.recv = recv; this.file = file; } _write(ostr) { ice.Ice.StringSeqHelper.write(ostr, this.recv); Dispatcher.ApplyUploadET.write(ostr, this.file); } _read(istr) { this.recv = ice.Ice.StringSeqHelper.read(istr); this.file = Dispatcher.ApplyUploadET.read(istr, this.file); } static get minWireSize() { return 4; } }; Slice$A.defineStruct(Dispatcher.ApplyUploadT, true, true); Dispatcher.ApplyUploadRT = class { constructor(fid = "", fname = "", fpath = "") { this.fid = fid; this.fname = fname; this.fpath = fpath; } _write(ostr) { ostr.writeString(this.fid); ostr.writeString(this.fname); ostr.writeString(this.fpath); } _read(istr) { this.fid = istr.readString(); this.fname = istr.readString(); this.fpath = istr.readString(); } static get minWireSize() { return 3; } }; Slice$A.defineStruct(Dispatcher.ApplyUploadRT, true, true); Slice$A.defineSequence(Dispatcher, "ApplyUploadRSeqHelper", "Dispatcher.ApplyUploadRT", false); Dispatcher.UploadEventT = class { constructor(fid = "", state = Dispatcher.FileState.FileStateNone) { this.fid = fid; this.state = state; } _write(ostr) { ostr.writeString(this.fid); Dispatcher.FileState._write(ostr, this.state); } _read(istr) { this.fid = istr.readString(); this.state = Dispatcher.FileState._read(istr); } static get minWireSize() { return 2; } }; Slice$A.defineStruct(Dispatcher.UploadEventT, true, true); Dispatcher.FlistT = class { constructor(sendid = "", recvid = "", isfinish = "", begtime = "", endtime = "", ftype = Dispatcher.FileType.FileTypeNone) { this.sendid = sendid; this.recvid = recvid; this.isfinish = isfinish; this.begtime = begtime; this.endtime = endtime; this.ftype = ftype; } _write(ostr) { ostr.writeString(this.sendid); ostr.writeString(this.recvid); ostr.writeString(this.isfinish); ostr.writeString(this.begtime); ostr.writeString(this.endtime); Dispatcher.FileType._write(ostr, this.ftype); } _read(istr) { this.sendid = istr.readString(); this.recvid = istr.readString(); this.isfinish = istr.readString(); this.begtime = istr.readString(); this.endtime = istr.readString(); this.ftype = Dispatcher.FileType._read(istr); } static get minWireSize() { return 6; } }; Slice$A.defineStruct(Dispatcher.FlistT, true, true); Slice$A.defineSequence(Dispatcher, "FlistSeqHelper", "Dispatcher.FlistT", false); Dispatcher.FlistRT = class { constructor(fid = "", sendid = "", sendname = "", msgbody = "", sendtime = "", isupload = 0, type = Dispatcher.FileType.FileTypeNone, recvid = "", recvname = "", isfinish = 0, recvtime = "") { this.fid = fid; this.sendid = sendid; this.sendname = sendname; this.msgbody = msgbody; this.sendtime = sendtime; this.isupload = isupload; this.type = type; this.recvid = recvid; this.recvname = recvname; this.isfinish = isfinish; this.recvtime = recvtime; } _write(ostr) { ostr.writeString(this.fid); ostr.writeString(this.sendid); ostr.writeString(this.sendname); ostr.writeString(this.msgbody); ostr.writeString(this.sendtime); ostr.writeInt(this.isupload); Dispatcher.FileType._write(ostr, this.type); ostr.writeString(this.recvid); ostr.writeString(this.recvname); ostr.writeInt(this.isfinish); ostr.writeString(this.recvtime); } _read(istr) { this.fid = istr.readString(); this.sendid = istr.readString(); this.sendname = istr.readString(); this.msgbody = istr.readString(); this.sendtime = istr.readString(); this.isupload = istr.readInt(); this.type = Dispatcher.FileType._read(istr); this.recvid = istr.readString(); this.recvname = istr.readString(); this.isfinish = istr.readInt(); this.recvtime = istr.readString(); } static get minWireSize() { return 17; } }; Slice$A.defineStruct(Dispatcher.FlistRT, true, true); Slice$A.defineSequence(Dispatcher, "FlistRSeqHelper", "Dispatcher.FlistRT", false); Dispatcher.FileReceivedT = class { constructor(fid = "", employeeid = "") { this.fid = fid; this.employeeid = employeeid; } _write(ostr) { ostr.writeString(this.fid); ostr.writeString(this.employeeid); } _read(istr) { this.fid = istr.readString(); this.employeeid = istr.readString(); } static get minWireSize() { return 2; } }; Slice$A.defineStruct(Dispatcher.FileReceivedT, true, true); Dispatcher.FileDeleteT = class { constructor(fid = "") { this.fid = fid; } _write(ostr) { ostr.writeString(this.fid); } _read(istr) { this.fid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$A.defineStruct(Dispatcher.FileDeleteT, true, true); Slice$A.defineSequence(Dispatcher, "FileDeleteTSeqHelper", "Dispatcher.FileDeleteT", false); const iceC_Dispatcher_FileOP_ids = [ "::Dispatcher::FileOP", "::Ice::Object" ]; Dispatcher.FileOP = class extends ice.Ice.Object {}; Dispatcher.FileOPPrx = class extends ice.Ice.ObjectPrx {}; Slice$A.defineOperations(Dispatcher.FileOP, Dispatcher.FileOPPrx, iceC_Dispatcher_FileOP_ids, 0, { "IFCReqapPlayUploadFile": [, , , , [Dispatcher.ApplyUploadRT], [ [Dispatcher.Identity], [Dispatcher.ApplyUploadT] ], , [ Dispatcher.Error ], , ], "IFCNotifyUploadFileEvt": [, 2, 2, , , [ [Dispatcher.Identity], [Dispatcher.UploadEventT] ], , [ Dispatcher.Error ], , ], "IFCReqGetFileList": [, , , , ["Dispatcher.FlistRSeqHelper"], [ [Dispatcher.Identity], ["Dispatcher.FlistSeqHelper"] ], , [ Dispatcher.Error ], , ], "IFCReqFileReceived": [, , , , , [ [Dispatcher.Identity], [Dispatcher.FileReceivedT] ], , [ Dispatcher.Error ], , ], "IFCReqDeleteFile": [, , , , , [ [Dispatcher.Identity], ["Dispatcher.FileDeleteTSeqHelper"] ], , [ Dispatcher.Error ], , ], "IFCReqUploadFileToGroup": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqSetUploadFileState": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ] }); // const _ModuleRegistry$B = ice.Ice._ModuleRegistry; const Slice$B = ice.Ice.Slice; Dispatcher.GisInfoEventT = class { constructor(mEmployeeid = "", mLatitude = 0.0, mLongitude = 0.0, mPositionTime = "", mMessage = "", disid = "", type = 0) { this.mEmployeeid = mEmployeeid; this.mLatitude = mLatitude; this.mLongitude = mLongitude; this.mPositionTime = mPositionTime; this.mMessage = mMessage; this.disid = disid; this.type = type; } _write(ostr) { ostr.writeString(this.mEmployeeid); ostr.writeDouble(this.mLatitude); ostr.writeDouble(this.mLongitude); ostr.writeString(this.mPositionTime); ostr.writeString(this.mMessage); ostr.writeString(this.disid); ostr.writeInt(this.type); } _read(istr) { this.mEmployeeid = istr.readString(); this.mLatitude = istr.readDouble(); this.mLongitude = istr.readDouble(); this.mPositionTime = istr.readString(); this.mMessage = istr.readString(); this.disid = istr.readString(); this.type = istr.readInt(); } static get minWireSize() { return 24; } }; Slice$B.defineStruct(Dispatcher.GisInfoEventT, false, true); Dispatcher.GisInfoEventT1 = class { constructor(mEmployeeid = "", mLatitude = 0.0, mLongitude = 0.0, mPositionTime = "", mMessage = "", disid = "", type = 0, dnsprefix = "") { this.mEmployeeid = mEmployeeid; this.mLatitude = mLatitude; this.mLongitude = mLongitude; this.mPositionTime = mPositionTime; this.mMessage = mMessage; this.disid = disid; this.type = type; this.dnsprefix = dnsprefix; } _write(ostr) { ostr.writeString(this.mEmployeeid); ostr.writeDouble(this.mLatitude); ostr.writeDouble(this.mLongitude); ostr.writeString(this.mPositionTime); ostr.writeString(this.mMessage); ostr.writeString(this.disid); ostr.writeInt(this.type); ostr.writeString(this.dnsprefix); } _read(istr) { this.mEmployeeid = istr.readString(); this.mLatitude = istr.readDouble(); this.mLongitude = istr.readDouble(); this.mPositionTime = istr.readString(); this.mMessage = istr.readString(); this.disid = istr.readString(); this.type = istr.readInt(); this.dnsprefix = istr.readString(); } static get minWireSize() { return 25; } }; Slice$B.defineStruct(Dispatcher.GisInfoEventT1, false, true); const iceC_Dispatcher_GisCB_ids = [ "::Dispatcher::GisCB", "::Ice::Object" ]; Dispatcher.GisCB = class extends ice.Ice.Object {}; Dispatcher.GisCBPrx = class extends ice.Ice.ObjectPrx {}; Slice$B.defineOperations(Dispatcher.GisCB, Dispatcher.GisCBPrx, iceC_Dispatcher_GisCB_ids, 0, { "IFCNotifyGisInfoEvt": [, 2, 2, , , [ [Dispatcher.GisInfoEventT] ], , , , ], "IFCNotifyGisInfoEvt2": [, 2, 2, , , [ [Dispatcher.GisInfoEventT1] ], , , , ], "IFCNotifyGisThirdDataEvt": [, 2, 2, , , [ [7] ], , , , ], "IFCNotifyGisHistoryEvt": [, 2, 2, , , [ [7] ], , , , ] }); // const _ModuleRegistry$C = ice.Ice._ModuleRegistry; const Slice$C = ice.Ice.Slice; Dispatcher.GisInfoByTimeT = class { constructor(employeeid = "", begin = "", end = "", type = 0) { this.employeeid = employeeid; this.begin = begin; this.end = end; this.type = type; } _write(ostr) { ostr.writeString(this.employeeid); ostr.writeString(this.begin); ostr.writeString(this.end); ostr.writeInt(this.type); } _read(istr) { this.employeeid = istr.readString(); this.begin = istr.readString(); this.end = istr.readString(); this.type = istr.readInt(); } static get minWireSize() { return 7; } }; Slice$C.defineStruct(Dispatcher.GisInfoByTimeT, true, true); Dispatcher.GisInfoByEllipseT = class { constructor(sid = "", a = 0.0, b = 0.0, c = 0.0, d = 0.0, type = "") { this.sid = sid; this.a = a; this.b = b; this.c = c; this.d = d; this.type = type; } _write(ostr) { ostr.writeString(this.sid); ostr.writeDouble(this.a); ostr.writeDouble(this.b); ostr.writeDouble(this.c); ostr.writeDouble(this.d); ostr.writeString(this.type); } _read(istr) { this.sid = istr.readString(); this.a = istr.readDouble(); this.b = istr.readDouble(); this.c = istr.readDouble(); this.d = istr.readDouble(); this.type = istr.readString(); } static get minWireSize() { return 34; } }; Slice$C.defineStruct(Dispatcher.GisInfoByEllipseT, false, true); Dispatcher.GisInfoByRectangleT = class { constructor(a = 0.0, b = 0.0, c = 0.0, d = 0.0, type = "") { this.a = a; this.b = b; this.c = c; this.d = d; this.type = type; } _write(ostr) { ostr.writeDouble(this.a); ostr.writeDouble(this.b); ostr.writeDouble(this.c); ostr.writeDouble(this.d); ostr.writeString(this.type); } _read(istr) { this.a = istr.readDouble(); this.b = istr.readDouble(); this.c = istr.readDouble(); this.d = istr.readDouble(); this.type = istr.readString(); } static get minWireSize() { return 33; } }; Slice$C.defineStruct(Dispatcher.GisInfoByRectangleT, false, true); Dispatcher.GetPositionT = class { constructor(employeeid = "") { this.employeeid = employeeid; } _write(ostr) { ostr.writeString(this.employeeid); } _read(istr) { this.employeeid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$C.defineStruct(Dispatcher.GetPositionT, true, true); Dispatcher.GetPositionElem = class { constructor(employeeid = "", name = "", longitude = "", latitude = "", message = "", type = -1, dnsprefix = "", regstate = Dispatcher.RegisterState.RegisterStateLogout, positiontime = "") { this.employeeid = employeeid; this.name = name; this.longitude = longitude; this.latitude = latitude; this.message = message; this.type = type; this.dnsprefix = dnsprefix; this.regstate = regstate; this.positiontime = positiontime; } _write(ostr) { ostr.writeString(this.employeeid); ostr.writeString(this.name); ostr.writeString(this.longitude); ostr.writeString(this.latitude); ostr.writeString(this.message); ostr.writeInt(this.type); ostr.writeString(this.dnsprefix); Dispatcher.RegisterState._write(ostr, this.regstate); ostr.writeString(this.positiontime); } _read(istr) { this.employeeid = istr.readString(); this.name = istr.readString(); this.longitude = istr.readString(); this.latitude = istr.readString(); this.message = istr.readString(); this.type = istr.readInt(); this.dnsprefix = istr.readString(); this.regstate = Dispatcher.RegisterState._read(istr); this.positiontime = istr.readString(); } static get minWireSize() { return 12; } }; Slice$C.defineStruct(Dispatcher.GetPositionElem, true, true); Slice$C.defineSequence(Dispatcher, "GetPositionSeqHelper", "Dispatcher.GetPositionElem", false); Dispatcher.GetPositionRT = class { constructor(pseq = null) { this.pseq = pseq; } _write(ostr) { Dispatcher.GetPositionSeqHelper.write(ostr, this.pseq); } _read(istr) { this.pseq = Dispatcher.GetPositionSeqHelper.read(istr); } static get minWireSize() { return 1; } }; Slice$C.defineStruct(Dispatcher.GetPositionRT, true, true); Dispatcher.GetPositionT1 = class { constructor(employeeid = "") { this.employeeid = employeeid; } _write(ostr) { ostr.writeString(this.employeeid); } _read(istr) { this.employeeid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$C.defineStruct(Dispatcher.GetPositionT1, true, true); Dispatcher.GetPositionElem1 = class { constructor(employeeid = "", name = "", longitude = "", latitude = "", message = "", type = 0, dnsprefix = "", regstate = Dispatcher.RegisterState.RegisterStateLogout) { this.employeeid = employeeid; this.name = name; this.longitude = longitude; this.latitude = latitude; this.message = message; this.type = type; this.dnsprefix = dnsprefix; this.regstate = regstate; } _write(ostr) { ostr.writeString(this.employeeid); ostr.writeString(this.name); ostr.writeString(this.longitude); ostr.writeString(this.latitude); ostr.writeString(this.message); ostr.writeInt(this.type); ostr.writeString(this.dnsprefix); Dispatcher.RegisterState._write(ostr, this.regstate); } _read(istr) { this.employeeid = istr.readString(); this.name = istr.readString(); this.longitude = istr.readString(); this.latitude = istr.readString(); this.message = istr.readString(); this.type = istr.readInt(); this.dnsprefix = istr.readString(); this.regstate = Dispatcher.RegisterState._read(istr); } static get minWireSize() { return 11; } }; Slice$C.defineStruct(Dispatcher.GetPositionElem1, true, true); Slice$C.defineSequence(Dispatcher, "GetPositionSeq1Helper", "Dispatcher.GetPositionElem1", false); Dispatcher.GetPositionRT1 = class { constructor(pseq = null) { this.pseq = pseq; } _write(ostr) { Dispatcher.GetPositionSeq1Helper.write(ostr, this.pseq); } _read(istr) { this.pseq = Dispatcher.GetPositionSeq1Helper.read(istr); } static get minWireSize() { return 1; } }; Slice$C.defineStruct(Dispatcher.GetPositionRT1, true, true); Dispatcher.GisTraceT = class { constructor(dstid = "", space = "", flag = Dispatcher.GisTraceType.GisTraceTypeNone) { this.dstid = dstid; this.space = space; this.flag = flag; } _write(ostr) { ostr.writeString(this.dstid); ostr.writeString(this.space); Dispatcher.GisTraceType._write(ostr, this.flag); } _read(istr) { this.dstid = istr.readString(); this.space = istr.readString(); this.flag = Dispatcher.GisTraceType._read(istr); } static get minWireSize() { return 3; } }; Slice$C.defineStruct(Dispatcher.GisTraceT, true, true); Slice$C.defineSequence(Dispatcher, "GisTraceSeqHelper", "Dispatcher.GisTraceT", false); Dispatcher.GisTraceRT = class { constructor(employeeid = "") { this.employeeid = employeeid; } _write(ostr) { ostr.writeString(this.employeeid); } _read(istr) { this.employeeid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$C.defineStruct(Dispatcher.GisTraceRT, true, true); Slice$C.defineSequence(Dispatcher, "GisTraceRSeqHelper", "Dispatcher.GisTraceRT", false); Dispatcher.GisInfoT = class { constructor(latitude = 0.0, longitude = 0.0, time = "", grmc = "") { this.latitude = latitude; this.longitude = longitude; this.time = time; this.grmc = grmc; } _write(ostr) { ostr.writeDouble(this.latitude); ostr.writeDouble(this.longitude); ostr.writeString(this.time); ostr.writeString(this.grmc); } _read(istr) { this.latitude = istr.readDouble(); this.longitude = istr.readDouble(); this.time = istr.readString(); this.grmc = istr.readString(); } static get minWireSize() { return 18; } }; Slice$C.defineStruct(Dispatcher.GisInfoT, false, true); Dispatcher.GISDETAIL1 = class { constructor(mEmployeeid = "", mLatitude = 0.0, mLongitude = 0.0, mPositionTime = "", mMessage = "", type = 0, dnsprefix = "", regstate = Dispatcher.RegisterState.RegisterStateLogout) { this.mEmployeeid = mEmployeeid; this.mLatitude = mLatitude; this.mLongitude = mLongitude; this.mPositionTime = mPositionTime; this.mMessage = mMessage; this.type = type; this.dnsprefix = dnsprefix; this.regstate = regstate; } _write(ostr) { ostr.writeString(this.mEmployeeid); ostr.writeDouble(this.mLatitude); ostr.writeDouble(this.mLongitude); ostr.writeString(this.mPositionTime); ostr.writeString(this.mMessage); ostr.writeInt(this.type); ostr.writeString(this.dnsprefix); Dispatcher.RegisterState._write(ostr, this.regstate); } _read(istr) { this.mEmployeeid = istr.readString(); this.mLatitude = istr.readDouble(); this.mLongitude = istr.readDouble(); this.mPositionTime = istr.readString(); this.mMessage = istr.readString(); this.type = istr.readInt(); this.dnsprefix = istr.readString(); this.regstate = Dispatcher.RegisterState._read(istr); } static get minWireSize() { return 25; } }; Slice$C.defineStruct(Dispatcher.GISDETAIL1, false, true); Slice$C.defineSequence(Dispatcher, "GISDETAILSeq1Helper", "Dispatcher.GISDETAIL1", false); const iceC_Dispatcher_GisOP_ids = [ "::Dispatcher::GisOP", "::Ice::Object" ]; Dispatcher.GisOP = class extends ice.Ice.Object {}; Dispatcher.GisOPPrx = class extends ice.Ice.ObjectPrx {}; Slice$C.defineOperations(Dispatcher.GisOP, Dispatcher.GisOPPrx, iceC_Dispatcher_GisOP_ids, 0, { "IFCReqGetGisInfoByTime": [, , , , ["DispatcherDB.GISDETAILSeqHelper"], [ [Dispatcher.Identity], [Dispatcher.GisInfoByTimeT] ], , [ Dispatcher.Error ], , ], "IFCReqGetGisInfoByTime2": [, , , , ["Dispatcher.GISDETAILSeq1Helper"], [ [Dispatcher.Identity], [Dispatcher.GisInfoByTimeT] ], , [ Dispatcher.Error ], , ], "IFCReqGetGisInfoByTimeByJson": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetGisInfoByTimeByJson2": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetGisInfoByEllipse": [, , , , ["DispatcherDB.GISDETAILSeqHelper"], [ [Dispatcher.Identity], [Dispatcher.GisInfoByEllipseT] ], , [ Dispatcher.Error ], , ], "IFCReqGetGisInfoByEllipse2": [, , , , ["Dispatcher.GISDETAILSeq1Helper"], [ [Dispatcher.Identity], [Dispatcher.GisInfoByEllipseT] ], , [ Dispatcher.Error ], , ], "IFCReqGetGisInfoByEllipseByJson": [, , , , [7], [ [Dispatcher.Identity], [Dispatcher.GisInfoByEllipseT] ], , [ Dispatcher.Error ], , ], "IFCReqGetGisInfoByRectangle": [, , , , ["DispatcherDB.GISDETAILSeqHelper"], [ [Dispatcher.Identity], [Dispatcher.GisInfoByRectangleT] ], , [ Dispatcher.Error ], , ], "IFCReqGetGisInfoByRectangle2": [, , , , ["Dispatcher.GISDETAILSeq1Helper"], [ [Dispatcher.Identity], [Dispatcher.GisInfoByRectangleT] ], , [ Dispatcher.Error ], , ], "IFCReqGetGisInfoByRectangleByJson": [, , , , [7], [ [Dispatcher.Identity], [Dispatcher.GisInfoByRectangleT] ], , [ Dispatcher.Error ], , ], "IFCReqGetGisInfo": [, , , , [Dispatcher.GetPositionRT], [ [Dispatcher.Identity], [Dispatcher.GetPositionT] ], , [ Dispatcher.Error ], , ], "IFCReqGetGisInfo2": [, , , , [Dispatcher.GetPositionRT1], [ [Dispatcher.Identity], [Dispatcher.GetPositionT1] ], , [ Dispatcher.Error ], , ], "IFCReqGetGisInfoByJson": [, , , , [7], [ [Dispatcher.Identity], [Dispatcher.GetPositionT1] ], , [ Dispatcher.Error ], , ], "IFCReqTraceGisInfo": [, , , , ["Dispatcher.GisTraceRSeqHelper"], [ [Dispatcher.Identity], ["Dispatcher.GisTraceSeqHelper"] ], , [ Dispatcher.Error ], , ], "IFCReqReportGisInfo": [, 2, 2, , , [ [Dispatcher.Identity], [Dispatcher.GisInfoT] ], , , , ], "IFCReqReportGisInfo2": [, 2, 2, , , [ [Dispatcher.Identity], [7] ], , , , ], "IFCReqReportGisInfoByJson": [, 2, 2, , [7], [ [Dispatcher.Identity], [7] ], , , , ] }); // const _ModuleRegistry$D = ice.Ice._ModuleRegistry; const Slice$D = ice.Ice.Slice; // const _ModuleRegistry$E = ice.Ice._ModuleRegistry; const Slice$E = ice.Ice.Slice; const iceC_Dispatcher_McuCB_ids = [ "::Dispatcher::McuCB", "::Ice::Object" ]; Dispatcher.McuCB = class extends ice.Ice.Object {}; Dispatcher.McuCBPrx = class extends ice.Ice.ObjectPrx {}; Slice$E.defineOperations(Dispatcher.McuCB, Dispatcher.McuCBPrx, iceC_Dispatcher_McuCB_ids, 0); // const _ModuleRegistry$F = ice.Ice._ModuleRegistry; const Slice$F = ice.Ice.Slice; Dispatcher.ScreenDisPlay = class { constructor(index = -1, showmember = "", hasstream = true) { this.index = index; this.showmember = showmember; this.hasstream = hasstream; } _write(ostr) { ostr.writeInt(this.index); ostr.writeString(this.showmember); ostr.writeBool(this.hasstream); } _read(istr) { this.index = istr.readInt(); this.showmember = istr.readString(); this.hasstream = istr.readBool(); } static get minWireSize() { return 6; } }; Slice$F.defineStruct(Dispatcher.ScreenDisPlay, true, true); Dispatcher.ScreenInfo = class { constructor(type = "", stream = 1, role = 2) { this.type = type; this.stream = stream; this.role = role; } _write(ostr) { ostr.writeString(this.type); ostr.writeInt(this.stream); ostr.writeInt(this.role); } _read(istr) { this.type = istr.readString(); this.stream = istr.readInt(); this.role = istr.readInt(); } static get minWireSize() { return 9; } }; Slice$F.defineStruct(Dispatcher.ScreenInfo, true, true); Slice$F.defineSequence(Dispatcher, "ScreenDisPlaySeqHelper", "Dispatcher.ScreenDisPlay", false); Dispatcher.SetScreenT = class { constructor(cid = "", screen = new Dispatcher.ScreenInfo(), DisplaySeq = null) { this.cid = cid; this.screen = screen; this.DisplaySeq = DisplaySeq; } _write(ostr) { ostr.writeString(this.cid); Dispatcher.ScreenInfo.write(ostr, this.screen); Dispatcher.ScreenDisPlaySeqHelper.write(ostr, this.DisplaySeq); } _read(istr) { this.cid = istr.readString(); this.screen = Dispatcher.ScreenInfo.read(istr, this.screen); this.DisplaySeq = Dispatcher.ScreenDisPlaySeqHelper.read(istr); } static get minWireSize() { return 11; } }; Slice$F.defineStruct(Dispatcher.SetScreenT, true, true); Dispatcher.SetScreenRT = class { constructor(cid = "", reslut = 0) { this.cid = cid; this.reslut = reslut; } _write(ostr) { ostr.writeString(this.cid); ostr.writeInt(this.reslut); } _read(istr) { this.cid = istr.readString(); this.reslut = istr.readInt(); } static get minWireSize() { return 5; } }; Slice$F.defineStruct(Dispatcher.SetScreenRT, true, true); Dispatcher.SetMemberRoleT = class { constructor(cid = "", member = "", role = 0) { this.cid = cid; this.member = member; this.role = role; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.member); ostr.writeInt(this.role); } _read(istr) { this.cid = istr.readString(); this.member = istr.readString(); this.role = istr.readInt(); } static get minWireSize() { return 6; } }; Slice$F.defineStruct(Dispatcher.SetMemberRoleT, true, true); Dispatcher.SetMemberRoleRT = class { constructor(cid = "", reslut = 0) { this.cid = cid; this.reslut = reslut; } _write(ostr) { ostr.writeString(this.cid); ostr.writeInt(this.reslut); } _read(istr) { this.cid = istr.readString(); this.reslut = istr.readInt(); } static get minWireSize() { return 5; } }; Slice$F.defineStruct(Dispatcher.SetMemberRoleRT, true, true); Dispatcher.MCUDevice = class { constructor(id = 0, ip = "", thetype = 0, defaultbandwidth = 0, thename = "") { this.id = id; this.ip = ip; this.thetype = thetype; this.defaultbandwidth = defaultbandwidth; this.thename = thename; } _write(ostr) { ostr.writeInt(this.id); ostr.writeString(this.ip); ostr.writeInt(this.thetype); ostr.writeInt(this.defaultbandwidth); ostr.writeString(this.thename); } _read(istr) { this.id = istr.readInt(); this.ip = istr.readString(); this.thetype = istr.readInt(); this.defaultbandwidth = istr.readInt(); this.thename = istr.readString(); } static get minWireSize() { return 14; } }; Slice$F.defineStruct(Dispatcher.MCUDevice, true, true); Dispatcher.MCUMettingOP = class { constructor(cid = "", number = "") { this.cid = cid; this.number = number; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.number); } _read(istr) { this.cid = istr.readString(); this.number = istr.readString(); } static get minWireSize() { return 2; } }; Slice$F.defineStruct(Dispatcher.MCUMettingOP, true, true); Slice$F.defineSequence(Dispatcher, "MCUDeviceSeqHelper", "Dispatcher.MCUDevice", false); const iceC_Dispatcher_McuOP_ids = [ "::Dispatcher::McuOP", "::Ice::Object" ]; Dispatcher.McuOP = class extends ice.Ice.Object {}; Dispatcher.McuOPPrx = class extends ice.Ice.ObjectPrx {}; Slice$F.defineOperations(Dispatcher.McuOP, Dispatcher.McuOPPrx, iceC_Dispatcher_McuOP_ids, 0, { "IFCReSetScreen": [, , , , [Dispatcher.SetScreenRT], [ [Dispatcher.Identity], [Dispatcher.SetScreenT] ], , [ Dispatcher.Error ], , ], "IFCReqSetMemberRole": [, , , , [Dispatcher.SetMemberRoleRT], [ [Dispatcher.Identity], [Dispatcher.SetMemberRoleT] ], , [ Dispatcher.Error ], , ], "IFCReqGetMcuDevice": [, , , , ["Dispatcher.MCUDeviceSeqHelper"], [ [Dispatcher.Identity] ], , [ Dispatcher.Error ], , ], "IFCReqMcuConfAddDevice": [, , , , , [ [Dispatcher.Identity], [Dispatcher.MCUMettingOP] ], , [ Dispatcher.Error ], , ], "IFCReqMcuConfDelDevice": [, , , , , [ [Dispatcher.Identity], [Dispatcher.MCUMettingOP] ], , [ Dispatcher.Error ], , ] }); // const _ModuleRegistry$G = ice.Ice._ModuleRegistry; const Slice$G = ice.Ice.Slice; Dispatcher.Message2T = class { constructor(msgid = "", body = "", sendid = "", time = "", receiver = null, attach = null, utype = Dispatcher.UserType.UserTypeDispatch) { this.msgid = msgid; this.body = body; this.sendid = sendid; this.time = time; this.receiver = receiver; this.attach = attach; this.utype = utype; } _write(ostr) { ostr.writeString(this.msgid); ostr.writeString(this.body); ostr.writeString(this.sendid); ostr.writeString(this.time); ice.Ice.StringSeqHelper.write(ostr, this.receiver); Dispatcher.UploadEvent2SeqHelper.write(ostr, this.attach); Dispatcher.UserType._write(ostr, this.utype); } _read(istr) { this.msgid = istr.readString(); this.body = istr.readString(); this.sendid = istr.readString(); this.time = istr.readString(); this.receiver = ice.Ice.StringSeqHelper.read(istr); this.attach = Dispatcher.UploadEvent2SeqHelper.read(istr); this.utype = Dispatcher.UserType._read(istr); } static get minWireSize() { return 7; } }; Slice$G.defineStruct(Dispatcher.Message2T, true, true); Slice$G.defineSequence(Dispatcher, "Message2SeqHelper", "Dispatcher.Message2T", false); // const _ModuleRegistry$H = ice.Ice._ModuleRegistry; const Slice$H = ice.Ice.Slice; const iceC_Dispatcher_MessageCB_ids = [ "::Dispatcher::FileCB", "::Dispatcher::MessageCB", "::Ice::Object" ]; Dispatcher.MessageCB = class extends ice.Ice.Object { static get _iceImplements() { return [ Dispatcher.FileCB ]; } }; Dispatcher.MessageCBPrx = class extends ice.Ice.ObjectPrx { static get _implements() { return [ Dispatcher.FileCBPrx ]; } }; Slice$H.defineOperations(Dispatcher.MessageCB, Dispatcher.MessageCBPrx, iceC_Dispatcher_MessageCB_ids, 1, { "IFCNotifyMsgEvt": [, 2, 2, , , [ [Dispatcher.Message2T] ], , , , ], "IFCNotifyMsgDelEvt": [, 2, 2, , , [ [7] ], , , , ] }); // const _ModuleRegistry$I = ice.Ice._ModuleRegistry; const Slice$I = ice.Ice.Slice; Dispatcher.MessageET = class { constructor(body = "", attach = null) { this.body = body; this.attach = attach; } _write(ostr) { ostr.writeString(this.body); Dispatcher.ApplyUploadESeqHelper.write(ostr, this.attach); } _read(istr) { this.body = istr.readString(); this.attach = Dispatcher.ApplyUploadESeqHelper.read(istr); } static get minWireSize() { return 2; } }; Slice$I.defineStruct(Dispatcher.MessageET, true, true); Dispatcher.MessageT = class { constructor(receiver = null, message = new Dispatcher.MessageET()) { this.receiver = receiver; this.message = message; } _write(ostr) { ice.Ice.StringSeqHelper.write(ostr, this.receiver); Dispatcher.MessageET.write(ostr, this.message); } _read(istr) { this.receiver = ice.Ice.StringSeqHelper.read(istr); this.message = Dispatcher.MessageET.read(istr, this.message); } static get minWireSize() { return 3; } }; Slice$I.defineStruct(Dispatcher.MessageT, true, true); Dispatcher.MessageRT = class { constructor(msgid = "", attach = null) { this.msgid = msgid; this.attach = attach; } _write(ostr) { ostr.writeString(this.msgid); Dispatcher.ApplyUploadRSeqHelper.write(ostr, this.attach); } _read(istr) { this.msgid = istr.readString(); this.attach = Dispatcher.ApplyUploadRSeqHelper.read(istr); } static get minWireSize() { return 2; } }; Slice$I.defineStruct(Dispatcher.MessageRT, true, true); Dispatcher.MessageReceivedT = class { constructor(msgid = "", employeeid = "") { this.msgid = msgid; this.employeeid = employeeid; } _write(ostr) { ostr.writeString(this.msgid); ostr.writeString(this.employeeid); } _read(istr) { this.msgid = istr.readString(); this.employeeid = istr.readString(); } static get minWireSize() { return 2; } }; Slice$I.defineStruct(Dispatcher.MessageReceivedT, true, true); Dispatcher.GetOldMsgFileT = class { constructor(employeeid = "", getnum = 0) { this.employeeid = employeeid; this.getnum = getnum; } _write(ostr) { ostr.writeString(this.employeeid); ostr.writeInt(this.getnum); } _read(istr) { this.employeeid = istr.readString(); this.getnum = istr.readInt(); } static get minWireSize() { return 5; } }; Slice$I.defineStruct(Dispatcher.GetOldMsgFileT, true, true); Dispatcher.GetOldMsgFileRT = class { constructor(fileinfos = null, msginfos = null) { this.fileinfos = fileinfos; this.msginfos = msginfos; } _write(ostr) { Dispatcher.UploadEvent2SeqHelper.write(ostr, this.fileinfos); Dispatcher.Message2SeqHelper.write(ostr, this.msginfos); } _read(istr) { this.fileinfos = Dispatcher.UploadEvent2SeqHelper.read(istr); this.msginfos = Dispatcher.Message2SeqHelper.read(istr); } static get minWireSize() { return 2; } }; Slice$I.defineStruct(Dispatcher.GetOldMsgFileRT, true, true); const iceC_Dispatcher_MessageOP_ids = [ "::Dispatcher::FileOP", "::Dispatcher::MessageOP", "::Ice::Object" ]; Dispatcher.MessageOP = class extends ice.Ice.Object { static get _iceImplements() { return [ Dispatcher.FileOP ]; } }; Dispatcher.MessageOPPrx = class extends ice.Ice.ObjectPrx { static get _implements() { return [ Dispatcher.FileOPPrx ]; } }; Slice$I.defineOperations(Dispatcher.MessageOP, Dispatcher.MessageOPPrx, iceC_Dispatcher_MessageOP_ids, 1, { "IFCReqMsg": [, , , , [Dispatcher.MessageRT], [ [Dispatcher.Identity], [Dispatcher.MessageT] ], , [ Dispatcher.Error ], , ], "IFCReqMsgReceived": [, , , , , [ [Dispatcher.Identity], [Dispatcher.MessageReceivedT] ], , [ Dispatcher.Error ], , ], "IFCReqGetOldMsgFile": [, , , , [Dispatcher.GetOldMsgFileRT], [ [Dispatcher.Identity], [Dispatcher.GetOldMsgFileT] ], , [ Dispatcher.Error ], , ], "IFCReqDelMsg": [, , , , , [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetGroupMsgByUserid": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqAddGroupMsg": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqUpdateGroupMsg": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqDeleteGroupMsg": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqSendMsg": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetOldMsg": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetSmsGis": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetSmsGisRepeat": [, , , , [7], [ [Dispatcher.Identity], [7], [7] ], , [ Dispatcher.Error ], , ] }); // const _ModuleRegistry$J = ice.Ice._ModuleRegistry; const Slice$J = ice.Ice.Slice; Dispatcher.PrePlanT = class { constructor(dummy = "") { this.dummy = dummy; } _write(ostr) { ostr.writeString(this.dummy); } _read(istr) { this.dummy = istr.readString(); } static get minWireSize() { return 1; } }; Slice$J.defineStruct(Dispatcher.PrePlanT, true, true); Dispatcher.PrePlanRT = class { constructor(planId = 0, planName = "", planAddr = "", planMeans = "", planNumber = "", planType = 0, dis = "") { this.planId = planId; this.planName = planName; this.planAddr = planAddr; this.planMeans = planMeans; this.planNumber = planNumber; this.planType = planType; this.dis = dis; } _write(ostr) { ostr.writeInt(this.planId); ostr.writeString(this.planName); ostr.writeString(this.planAddr); ostr.writeString(this.planMeans); ostr.writeString(this.planNumber); ostr.writeInt(this.planType); ostr.writeString(this.dis); } _read(istr) { this.planId = istr.readInt(); this.planName = istr.readString(); this.planAddr = istr.readString(); this.planMeans = istr.readString(); this.planNumber = istr.readString(); this.planType = istr.readInt(); this.dis = istr.readString(); } static get minWireSize() { return 13; } }; Slice$J.defineStruct(Dispatcher.PrePlanRT, true, true); Slice$J.defineSequence(Dispatcher, "PrePlanRSeqHelper", "Dispatcher.PrePlanRT", false); Dispatcher.PrePlanStartT = class { constructor(planId = 0, passwd = "", caller = "") { this.planId = planId; this.passwd = passwd; this.caller = caller; } _write(ostr) { ostr.writeInt(this.planId); ostr.writeString(this.passwd); ostr.writeString(this.caller); } _read(istr) { this.planId = istr.readInt(); this.passwd = istr.readString(); this.caller = istr.readString(); } static get minWireSize() { return 6; } }; Slice$J.defineStruct(Dispatcher.PrePlanStartT, true, true); Dispatcher.PrePlanStartRT = class { constructor(dummy = "") { this.dummy = dummy; } _write(ostr) { ostr.writeString(this.dummy); } _read(istr) { this.dummy = istr.readString(); } static get minWireSize() { return 1; } }; Slice$J.defineStruct(Dispatcher.PrePlanStartRT, true, true); Dispatcher.PrePlanEvT = class { constructor(planId = 0, state = Dispatcher.PrePlanState.PrePlanStateNone) { this.planId = planId; this.state = state; } _write(ostr) { ostr.writeInt(this.planId); Dispatcher.PrePlanState._write(ostr, this.state); } _read(istr) { this.planId = istr.readInt(); this.state = Dispatcher.PrePlanState._read(istr); } static get minWireSize() { return 5; } }; Slice$J.defineStruct(Dispatcher.PrePlanEvT, true, true); Dispatcher.PrePlanStopT = class { constructor(planId = 0, passwd = "") { this.planId = planId; this.passwd = passwd; } _write(ostr) { ostr.writeInt(this.planId); ostr.writeString(this.passwd); } _read(istr) { this.planId = istr.readInt(); this.passwd = istr.readString(); } static get minWireSize() { return 5; } }; Slice$J.defineStruct(Dispatcher.PrePlanStopT, true, true); Dispatcher.PrePlanStopRT = class { constructor(dummy = "") { this.dummy = dummy; } _write(ostr) { ostr.writeString(this.dummy); } _read(istr) { this.dummy = istr.readString(); } static get minWireSize() { return 1; } }; Slice$J.defineStruct(Dispatcher.PrePlanStopRT, true, true); // const _ModuleRegistry$K = ice.Ice._ModuleRegistry; const Slice$K = ice.Ice.Slice; const iceC_Dispatcher_PrePlanCB_ids = [ "::Dispatcher::PrePlanCB", "::Ice::Object" ]; Dispatcher.PrePlanCB = class extends ice.Ice.Object {}; Dispatcher.PrePlanCBPrx = class extends ice.Ice.ObjectPrx {}; Slice$K.defineOperations(Dispatcher.PrePlanCB, Dispatcher.PrePlanCBPrx, iceC_Dispatcher_PrePlanCB_ids, 0, { "onPrePlanEv": [, 2, 2, , , [ [Dispatcher.PrePlanEvT] ], , , , ] }); // const _ModuleRegistry$L = ice.Ice._ModuleRegistry; const Slice$L = ice.Ice.Slice; const iceC_Dispatcher_PrePlanOP_ids = [ "::Dispatcher::FileOP", "::Dispatcher::MessageOP", "::Dispatcher::PrePlanOP", "::Ice::Object" ]; Dispatcher.PrePlanOP = class extends ice.Ice.Object { static get _iceImplements() { return [ Dispatcher.MessageOP ]; } }; Dispatcher.PrePlanOPPrx = class extends ice.Ice.ObjectPrx { static get _implements() { return [ Dispatcher.MessageOPPrx ]; } }; Slice$L.defineOperations(Dispatcher.PrePlanOP, Dispatcher.PrePlanOPPrx, iceC_Dispatcher_PrePlanOP_ids, 2, { "IFCReqSelectPreplan": [, , , , ["Dispatcher.PrePlanRSeqHelper"], [ [Dispatcher.Identity], [Dispatcher.PrePlanT] ], , [ Dispatcher.Error ], , ], "IFCReqSelectPreplan2": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqStartPreplan": [, , , , [Dispatcher.PrePlanStartRT], [ [Dispatcher.Identity], [Dispatcher.PrePlanStartT] ], , [ Dispatcher.Error ], , ], "IFCReqStopPreplan": [, , , , [Dispatcher.PrePlanStopRT], [ [Dispatcher.Identity], [Dispatcher.PrePlanStopT] ], , [ Dispatcher.Error ], , ] }); // const _ModuleRegistry$M = ice.Ice._ModuleRegistry; const Slice$M = ice.Ice.Slice; Dispatcher.PttIndCallInfoElem = class { constructor(group = "", speaker = "", callid = "") { this.group = group; this.speaker = speaker; this.callid = callid; } _write(ostr) { ostr.writeString(this.group); ostr.writeString(this.speaker); ostr.writeString(this.callid); } _read(istr) { this.group = istr.readString(); this.speaker = istr.readString(); this.callid = istr.readString(); } static get minWireSize() { return 3; } }; Slice$M.defineStruct(Dispatcher.PttIndCallInfoElem, true, true); Slice$M.defineSequence(Dispatcher, "PttIndCallInfoSeqHelper", "Dispatcher.PttIndCallInfoElem", false); Dispatcher.G3MessageT = class { constructor(sid = "", employeeid = "", callinfo = null, ip = "", port = 0) { this.sid = sid; this.employeeid = employeeid; this.callinfo = callinfo; this.ip = ip; this.port = port; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.employeeid); Dispatcher.PttIndCallInfoSeqHelper.write(ostr, this.callinfo); ostr.writeString(this.ip); ostr.writeInt(this.port); } _read(istr) { this.sid = istr.readString(); this.employeeid = istr.readString(); this.callinfo = Dispatcher.PttIndCallInfoSeqHelper.read(istr); this.ip = istr.readString(); this.port = istr.readInt(); } static get minWireSize() { return 8; } }; Slice$M.defineStruct(Dispatcher.G3MessageT, true, true); Dispatcher.PttIndGroupInfoElem = class { constructor(groupname = "", groupnum = "", grouplevel = 0, ipstatespace = 0, ipheartbeatspace = 0, ip = "", port = 0, thetype = Dispatcher.GroupType.GroupTypeNone) { this.groupname = groupname; this.groupnum = groupnum; this.grouplevel = grouplevel; this.ipstatespace = ipstatespace; this.ipheartbeatspace = ipheartbeatspace; this.ip = ip; this.port = port; this.thetype = thetype; } _write(ostr) { ostr.writeString(this.groupname); ostr.writeString(this.groupnum); ostr.writeInt(this.grouplevel); ostr.writeInt(this.ipstatespace); ostr.writeInt(this.ipheartbeatspace); ostr.writeString(this.ip); ostr.writeInt(this.port); Dispatcher.GroupType._write(ostr, this.thetype); } _read(istr) { this.groupname = istr.readString(); this.groupnum = istr.readString(); this.grouplevel = istr.readInt(); this.ipstatespace = istr.readInt(); this.ipheartbeatspace = istr.readInt(); this.ip = istr.readString(); this.port = istr.readInt(); this.thetype = Dispatcher.GroupType._read(istr); } static get minWireSize() { return 20; } }; Slice$M.defineStruct(Dispatcher.PttIndGroupInfoElem, true, true); Slice$M.defineSequence(Dispatcher, "PttIndGroupInfoSeqHelper", "Dispatcher.PttIndGroupInfoElem", false); Dispatcher.PttIndGroupInfoT = class { constructor(seq = null, employeeid = "", ip = "", port = 0, type = "") { this.seq = seq; this.employeeid = employeeid; this.ip = ip; this.port = port; this.type = type; } _write(ostr) { Dispatcher.PttIndGroupInfoSeqHelper.write(ostr, this.seq); ostr.writeString(this.employeeid); ostr.writeString(this.ip); ostr.writeInt(this.port); ostr.writeString(this.type); } _read(istr) { this.seq = Dispatcher.PttIndGroupInfoSeqHelper.read(istr); this.employeeid = istr.readString(); this.ip = istr.readString(); this.port = istr.readInt(); this.type = istr.readString(); } static get minWireSize() { return 8; } }; Slice$M.defineStruct(Dispatcher.PttIndGroupInfoT, true, true); Dispatcher.PttReqRightRT = class { constructor(employeeid = "", result = "", reason = "") { this.employeeid = employeeid; this.result = result; this.reason = reason; } _write(ostr) { ostr.writeString(this.employeeid); ostr.writeString(this.result); ostr.writeString(this.reason); } _read(istr) { this.employeeid = istr.readString(); this.result = istr.readString(); this.reason = istr.readString(); } static get minWireSize() { return 3; } }; Slice$M.defineStruct(Dispatcher.PttReqRightRT, true, true); // const _ModuleRegistry$N = ice.Ice._ModuleRegistry; const Slice$N = ice.Ice.Slice; const iceC_Dispatcher_PttCB_ids = [ "::Dispatcher::PttCB", "::Ice::Object" ]; Dispatcher.PttCB = class extends ice.Ice.Object {}; Dispatcher.PttCBPrx = class extends ice.Ice.ObjectPrx {}; Slice$N.defineOperations(Dispatcher.PttCB, Dispatcher.PttCBPrx, iceC_Dispatcher_PttCB_ids, 0, { "IFCNotifyPhoneMsgEvt": [, 2, 2, , , [ [Dispatcher.G3MessageT] ], , , , ], "IFCNotifyGroupInfoEvt": [, 2, 2, , , [ [Dispatcher.PttIndGroupInfoT] ], , , , ], "IFCNotifyReqRightResultEvt": [, 2, 2, , , [ [Dispatcher.PttReqRightRT] ], , , , ] }); // const _ModuleRegistry$O = ice.Ice._ModuleRegistry; const Slice$O = ice.Ice.Slice; Dispatcher.PttReqRightT = class { constructor(groupnum = "", caller = "", messageinfo = "") { this.groupnum = groupnum; this.caller = caller; this.messageinfo = messageinfo; } _write(ostr) { ostr.writeString(this.groupnum); ostr.writeString(this.caller); ostr.writeString(this.messageinfo); } _read(istr) { this.groupnum = istr.readString(); this.caller = istr.readString(); this.messageinfo = istr.readString(); } static get minWireSize() { return 3; } }; Slice$O.defineStruct(Dispatcher.PttReqRightT, true, true); Dispatcher.PttReqGroupInfoT = class { constructor(employeeid = "", type = "") { this.employeeid = employeeid; this.type = type; } _write(ostr) { ostr.writeString(this.employeeid); ostr.writeString(this.type); } _read(istr) { this.employeeid = istr.readString(); this.type = istr.readString(); } static get minWireSize() { return 2; } }; Slice$O.defineStruct(Dispatcher.PttReqGroupInfoT, true, true); Dispatcher.PttReqMemberInfoT = class { constructor(employeeid = "", groupnum = "") { this.employeeid = employeeid; this.groupnum = groupnum; } _write(ostr) { ostr.writeString(this.employeeid); ostr.writeString(this.groupnum); } _read(istr) { this.employeeid = istr.readString(); this.groupnum = istr.readString(); } static get minWireSize() { return 2; } }; Slice$O.defineStruct(Dispatcher.PttReqMemberInfoT, true, true); Dispatcher.PttReqMemberInfoRElem = class { constructor(num = "", name = "", state = Dispatcher.CallState.CallStateNone) { this.num = num; this.name = name; this.state = state; } _write(ostr) { ostr.writeString(this.num); ostr.writeString(this.name); Dispatcher.CallState._write(ostr, this.state); } _read(istr) { this.num = istr.readString(); this.name = istr.readString(); this.state = Dispatcher.CallState._read(istr); } static get minWireSize() { return 3; } }; Slice$O.defineStruct(Dispatcher.PttReqMemberInfoRElem, true, true); Slice$O.defineSequence(Dispatcher, "PttReqMemberInfoRSeqHelper", "Dispatcher.PttReqMemberInfoRElem", false); Dispatcher.PttReqMemberInfoRT = class { constructor(groupnum = "", employeeid = "", memberinfo = null) { this.groupnum = groupnum; this.employeeid = employeeid; this.memberinfo = memberinfo; } _write(ostr) { ostr.writeString(this.groupnum); ostr.writeString(this.employeeid); Dispatcher.PttReqMemberInfoRSeqHelper.write(ostr, this.memberinfo); } _read(istr) { this.groupnum = istr.readString(); this.employeeid = istr.readString(); this.memberinfo = Dispatcher.PttReqMemberInfoRSeqHelper.read(istr); } static get minWireSize() { return 3; } }; Slice$O.defineStruct(Dispatcher.PttReqMemberInfoRT, true, true); Dispatcher.PttReqMemberInfoT1 = class { constructor(sid = "", groupnum = "", employeeid = "") { this.sid = sid; this.groupnum = groupnum; this.employeeid = employeeid; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.groupnum); ostr.writeString(this.employeeid); } _read(istr) { this.sid = istr.readString(); this.groupnum = istr.readString(); this.employeeid = istr.readString(); } static get minWireSize() { return 3; } }; Slice$O.defineStruct(Dispatcher.PttReqMemberInfoT1, true, true); Dispatcher.PttReqMemberInfoRElem1 = class { constructor(employeeid = "", name = "", type = 8, level = 10, state = Dispatcher.CallState.CallStateNone, stateDecorate = "") { this.employeeid = employeeid; this.name = name; this.type = type; this.level = level; this.state = state; this.stateDecorate = stateDecorate; } _write(ostr) { ostr.writeString(this.employeeid); ostr.writeString(this.name); ostr.writeInt(this.type); ostr.writeInt(this.level); Dispatcher.CallState._write(ostr, this.state); ostr.writeString(this.stateDecorate); } _read(istr) { this.employeeid = istr.readString(); this.name = istr.readString(); this.type = istr.readInt(); this.level = istr.readInt(); this.state = Dispatcher.CallState._read(istr); this.stateDecorate = istr.readString(); } static get minWireSize() { return 12; } }; Slice$O.defineStruct(Dispatcher.PttReqMemberInfoRElem1, true, true); Slice$O.defineSequence(Dispatcher, "PttReqMemberInfoRSeq1Helper", "Dispatcher.PttReqMemberInfoRElem1", false); Dispatcher.PttReqMemberInfoRT1 = class { constructor(groupnum = "", employeeid = "", memberinfo = null) { this.groupnum = groupnum; this.employeeid = employeeid; this.memberinfo = memberinfo; } _write(ostr) { ostr.writeString(this.groupnum); ostr.writeString(this.employeeid); Dispatcher.PttReqMemberInfoRSeq1Helper.write(ostr, this.memberinfo); } _read(istr) { this.groupnum = istr.readString(); this.employeeid = istr.readString(); this.memberinfo = Dispatcher.PttReqMemberInfoRSeq1Helper.read(istr); } static get minWireSize() { return 3; } }; Slice$O.defineStruct(Dispatcher.PttReqMemberInfoRT1, true, true); Dispatcher.PttTimeOutT = class { constructor(cid = "", MaxQueue = "", IdelTimeout = "", SpeakTimeout = "", RefreshStateSpace = "") { this.cid = cid; this.MaxQueue = MaxQueue; this.IdelTimeout = IdelTimeout; this.SpeakTimeout = SpeakTimeout; this.RefreshStateSpace = RefreshStateSpace; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.MaxQueue); ostr.writeString(this.IdelTimeout); ostr.writeString(this.SpeakTimeout); ostr.writeString(this.RefreshStateSpace); } _read(istr) { this.cid = istr.readString(); this.MaxQueue = istr.readString(); this.IdelTimeout = istr.readString(); this.SpeakTimeout = istr.readString(); this.RefreshStateSpace = istr.readString(); } static get minWireSize() { return 5; } }; Slice$O.defineStruct(Dispatcher.PttTimeOutT, true, true); const iceC_Dispatcher_PttOP_ids = [ "::Dispatcher::PttOP", "::Ice::Object" ]; Dispatcher.PttOP = class extends ice.Ice.Object {}; Dispatcher.PttOPPrx = class extends ice.Ice.ObjectPrx {}; Slice$O.defineOperations(Dispatcher.PttOP, Dispatcher.PttOPPrx, iceC_Dispatcher_PttOP_ids, 0, { "IFCReqGetMemberInfo": [, , , , [Dispatcher.PttReqMemberInfoRT], [ [Dispatcher.Identity], [Dispatcher.PttReqMemberInfoT] ], , [ Dispatcher.Error ], , ], "IFCReqGetMemberInfo2": [, , , , [Dispatcher.PttReqMemberInfoRT1], [ [Dispatcher.Identity], [Dispatcher.PttReqMemberInfoT1] ], , [ Dispatcher.Error ], , ], "IFCReqApplyRight": [, , , , [Dispatcher.CommonRequestT], [ [Dispatcher.Identity], [Dispatcher.PttReqRightT] ], , [ Dispatcher.Error ], , ], "IFCReqSetIntercomTimeoutInfo": [, , , , [3], [ [Dispatcher.Identity], [Dispatcher.PttTimeOutT] ], , [ Dispatcher.Error ], , ], "IFCReqGetIntercomTimeoutInfo": [, , , , [Dispatcher.PttTimeOutT], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetGroupInfo": [, 2, 2, , , [ [Dispatcher.Identity], [Dispatcher.PttReqGroupInfoT] ], , , , ] }); const iceC_Dispatcher_PttSB_ids = [ "::Dispatcher::PttSB", "::Ice::Object" ]; Dispatcher.PttSB = class extends ice.Ice.Object {}; Dispatcher.PttSBPrx = class extends ice.Ice.ObjectPrx {}; Slice$O.defineOperations(Dispatcher.PttSB, Dispatcher.PttSBPrx, iceC_Dispatcher_PttSB_ids, 0); // const _ModuleRegistry$P = ice.Ice._ModuleRegistry; const Slice$P = ice.Ice.Slice; let Dispatcher$3 = _ModuleRegistry$P.module("Dispatcher"); Dispatcher$3.ContentInfo = class { constructor(strContent = "") { this.strContent = strContent; } _write(ostr) { ostr.writeString(this.strContent); } _read(istr) { this.strContent = istr.readString(); } static get minWireSize() { return 1; } }; Slice$P.defineStruct(Dispatcher$3.ContentInfo, true, true); Slice$P.defineSequence(Dispatcher$3, "SubContentSeqHelper", "Dispatcher.ContentInfo", false); Dispatcher$3.SubInfo = class { constructor(subHeader = "", subContents = null) { this.subHeader = subHeader; this.subContents = subContents; } _write(ostr) { ostr.writeString(this.subHeader); Dispatcher$3.SubContentSeqHelper.write(ostr, this.subContents); } _read(istr) { this.subHeader = istr.readString(); this.subContents = Dispatcher$3.SubContentSeqHelper.read(istr); } static get minWireSize() { return 2; } }; Slice$P.defineStruct(Dispatcher$3.SubInfo, true, true); Slice$P.defineSequence(Dispatcher$3, "SubInfoSeqHelper", "Dispatcher.SubInfo", false); Dispatcher$3.SubInfos = class { constructor(Infos = null) { this.Infos = Infos; } _write(ostr) { Dispatcher$3.SubInfoSeqHelper.write(ostr, this.Infos); } _read(istr) { this.Infos = Dispatcher$3.SubInfoSeqHelper.read(istr); } static get minWireSize() { return 1; } }; Slice$P.defineStruct(Dispatcher$3.SubInfos, true, true); Dispatcher$3.PubInfo = class { constructor(subHeader = "", subMsg = "") { this.subHeader = subHeader; this.subMsg = subMsg; } _write(ostr) { ostr.writeString(this.subHeader); ostr.writeString(this.subMsg); } _read(istr) { this.subHeader = istr.readString(); this.subMsg = istr.readString(); } static get minWireSize() { return 2; } }; Slice$P.defineStruct(Dispatcher$3.PubInfo, true, true); Dispatcher$3.FixReceiveInfo = class { constructor(subHeader = "", subMsg = "", receive = "") { this.subHeader = subHeader; this.subMsg = subMsg; this.receive = receive; } _write(ostr) { ostr.writeString(this.subHeader); ostr.writeString(this.subMsg); ostr.writeString(this.receive); } _read(istr) { this.subHeader = istr.readString(); this.subMsg = istr.readString(); this.receive = istr.readString(); } static get minWireSize() { return 3; } }; Slice$P.defineStruct(Dispatcher$3.FixReceiveInfo, true, true); Dispatcher$3.OnReceiveHeartBeat = class { constructor(number = "", issub = false) { this.number = number; this.issub = issub; } _write(ostr) { ostr.writeString(this.number); ostr.writeBool(this.issub); } _read(istr) { this.number = istr.readString(); this.issub = istr.readBool(); } static get minWireSize() { return 2; } }; Slice$P.defineStruct(Dispatcher$3.OnReceiveHeartBeat, true, true); // const _ModuleRegistry$Q = ice.Ice._ModuleRegistry; const Slice$Q = ice.Ice.Slice; const iceC_Dispatcher_PublishCB_ids = [ "::Dispatcher::PublishCB", "::Ice::Object" ]; Dispatcher.PublishCB = class extends ice.Ice.Object {}; Dispatcher.PublishCBPrx = class extends ice.Ice.ObjectPrx {}; Slice$Q.defineOperations(Dispatcher.PublishCB, Dispatcher.PublishCBPrx, iceC_Dispatcher_PublishCB_ids, 0, { "IFCNotifyPublishMsgEvt": [, 2, 2, , , [ [Dispatcher.PubInfo] ], , , , ], "IFCNotifyFixMsgEvt": [, 2, 2, , , [ [Dispatcher.FixReceiveInfo] ], , , , ], "IFCNotifyPublishHBEvt": [, 2, 2, , , [ [Dispatcher.OnReceiveHeartBeat] ], , , , ] }); // const _ModuleRegistry$R = ice.Ice._ModuleRegistry; const Slice$R = ice.Ice.Slice; const iceC_Dispatcher_PublishOP_ids = [ "::Dispatcher::PublishOP", "::Ice::Object" ]; Dispatcher.PublishOP = class extends ice.Ice.Object {}; Dispatcher.PublishOPPrx = class extends ice.Ice.ObjectPrx {}; Slice$R.defineOperations(Dispatcher.PublishOP, Dispatcher.PublishOPPrx, iceC_Dispatcher_PublishOP_ids, 0, { "IFCReqPublishMsg": [, , , , , [ [Dispatcher.Identity], [Dispatcher.SubInfos] ], , , , ], "IFCReqUnpublishMsg": [, , , , , [ [Dispatcher.Identity] ], , , , ], "IFCReqPublishHB": [, , , , [1], [ [Dispatcher.Identity], [3] ], , [ Dispatcher.Error ], , ] }); // const _ModuleRegistry$S = ice.Ice._ModuleRegistry; const Slice$S = ice.Ice.Slice; Dispatcher.StationLineT = class { constructor(stationid = -1, Employeeid = "") { this.stationid = stationid; this.Employeeid = Employeeid; } _write(ostr) { ostr.writeInt(this.stationid); ostr.writeString(this.Employeeid); } _read(istr) { this.stationid = istr.readInt(); this.Employeeid = istr.readString(); } static get minWireSize() { return 5; } }; Slice$S.defineStruct(Dispatcher.StationLineT, true, true); Dispatcher.StationLineRT = class { constructor(LineID = 0, LineName = "", StationID = 0, Description = "") { this.LineID = LineID; this.LineName = LineName; this.StationID = StationID; this.Description = Description; } _write(ostr) { ostr.writeInt(this.LineID); ostr.writeString(this.LineName); ostr.writeInt(this.StationID); ostr.writeString(this.Description); } _read(istr) { this.LineID = istr.readInt(); this.LineName = istr.readString(); this.StationID = istr.readInt(); this.Description = istr.readString(); } static get minWireSize() { return 10; } }; Slice$S.defineStruct(Dispatcher.StationLineRT, true, true); Slice$S.defineSequence(Dispatcher, "StationLineRTSeqHelper", "Dispatcher.StationLineRT", false); Dispatcher.StationT = class { constructor(Employeeid = "") { this.Employeeid = Employeeid; } _write(ostr) { ostr.writeString(this.Employeeid); } _read(istr) { this.Employeeid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$S.defineStruct(Dispatcher.StationT, true, true); Dispatcher.StationRT = class { constructor(StationID = 0, StationName = "", StationDes = "") { this.StationID = StationID; this.StationName = StationName; this.StationDes = StationDes; } _write(ostr) { ostr.writeInt(this.StationID); ostr.writeString(this.StationName); ostr.writeString(this.StationDes); } _read(istr) { this.StationID = istr.readInt(); this.StationName = istr.readString(); this.StationDes = istr.readString(); } static get minWireSize() { return 6; } }; Slice$S.defineStruct(Dispatcher.StationRT, true, true); Slice$S.defineSequence(Dispatcher, "StationRTSeqHelper", "Dispatcher.StationRT", false); const iceC_Dispatcher_RailWayOP_ids = [ "::Dispatcher::RailWayOP", "::Ice::Object" ]; Dispatcher.RailWayOP = class extends ice.Ice.Object {}; Dispatcher.RailWayOPPrx = class extends ice.Ice.ObjectPrx {}; Slice$S.defineOperations(Dispatcher.RailWayOP, Dispatcher.RailWayOPPrx, iceC_Dispatcher_RailWayOP_ids, 0, { "IFCReqGetStationLine": [, , , , ["Dispatcher.StationLineRTSeqHelper"], [ [Dispatcher.Identity], [Dispatcher.StationLineT] ], , [ Dispatcher.Error ], , ], "IFCReqstopGetStation": [, , , , [Dispatcher.StationRT], [ [Dispatcher.Identity], [Dispatcher.StationT] ], , [ Dispatcher.Error ], , ], "IFCReqGetAllStations": [, , , , ["Dispatcher.StationRTSeqHelper"], [ [Dispatcher.Identity] ], , [ Dispatcher.Error ], , ] }); // const _ModuleRegistry$T = ice.Ice._ModuleRegistry; const Slice$T = ice.Ice.Slice; Dispatcher.ForceLogoutT = class { constructor(code = Dispatcher.ECode.ECodeNone) { this.code = code; } _write(ostr) { Dispatcher.ECode._write(ostr, this.code); } _read(istr) { this.code = Dispatcher.ECode._read(istr); } static get minWireSize() { return 1; } }; Slice$T.defineStruct(Dispatcher.ForceLogoutT, true, true); const iceC_Dispatcher_RegisterCB_ids = [ "::Dispatcher::RegisterCB", "::Ice::Object" ]; Dispatcher.RegisterCB = class extends ice.Ice.Object {}; Dispatcher.RegisterCBPrx = class extends ice.Ice.ObjectPrx {}; Slice$T.defineOperations(Dispatcher.RegisterCB, Dispatcher.RegisterCBPrx, iceC_Dispatcher_RegisterCB_ids, 0, { "IFCNotifyForceLogout": [, 2, 2, , , [ [Dispatcher.ForceLogoutT] ], , , , ] }); const iceC_Dispatcher_RegisterCBSub_ids = [ "::Dispatcher::RegisterCBSub", "::Ice::Object" ]; Dispatcher.RegisterCBSub = class extends ice.Ice.Object {}; Dispatcher.RegisterCBSubPrx = class extends ice.Ice.ObjectPrx {}; Slice$T.defineOperations(Dispatcher.RegisterCBSub, Dispatcher.RegisterCBSubPrx, iceC_Dispatcher_RegisterCBSub_ids, 0); // const _ModuleRegistry$U = ice.Ice._ModuleRegistry; const Slice$U = ice.Ice.Slice; Dispatcher.LoginT = class { constructor(pass = "", ip = "", interval = 0, type = Dispatcher.UserType.UserTypeNone) { this.pass = pass; this.ip = ip; this.interval = interval; this.type = type; } _write(ostr) { ostr.writeString(this.pass); ostr.writeString(this.ip); ostr.writeInt(this.interval); Dispatcher.UserType._write(ostr, this.type); } _read(istr) { this.pass = istr.readString(); this.ip = istr.readString(); this.interval = istr.readInt(); this.type = Dispatcher.UserType._read(istr); } static get minWireSize() { return 7; } }; Slice$U.defineStruct(Dispatcher.LoginT, true, true); Dispatcher.LoginRT = class { constructor(firstlogin = false, sptpsw = "", dnsprefix = "") { this.firstlogin = firstlogin; this.sptpsw = sptpsw; this.dnsprefix = dnsprefix; } _write(ostr) { ostr.writeBool(this.firstlogin); ostr.writeString(this.sptpsw); ostr.writeString(this.dnsprefix); } _read(istr) { this.firstlogin = istr.readBool(); this.sptpsw = istr.readString(); this.dnsprefix = istr.readString(); } static get minWireSize() { return 3; } }; Slice$U.defineStruct(Dispatcher.LoginRT, true, true); Dispatcher.LogoutT = class { constructor(dummy = "") { this.dummy = dummy; } _write(ostr) { ostr.writeString(this.dummy); } _read(istr) { this.dummy = istr.readString(); } static get minWireSize() { return 1; } }; Slice$U.defineStruct(Dispatcher.LogoutT, true, true); Dispatcher.LogoutRT = class { constructor(dummy = "") { this.dummy = dummy; } _write(ostr) { ostr.writeString(this.dummy); } _read(istr) { this.dummy = istr.readString(); } static get minWireSize() { return 1; } }; Slice$U.defineStruct(Dispatcher.LogoutRT, true, true); Dispatcher.ReloginT = class { constructor(state = 0, ip = "") { this.state = state; this.ip = ip; } _write(ostr) { ostr.writeInt(this.state); ostr.writeString(this.ip); } _read(istr) { this.state = istr.readInt(); this.ip = istr.readString(); } static get minWireSize() { return 5; } }; Slice$U.defineStruct(Dispatcher.ReloginT, true, true); Dispatcher.HeartbeatRT = class { constructor(dummy = 0) { this.dummy = dummy; } _write(ostr) { ostr.writeInt(this.dummy); } _read(istr) { this.dummy = istr.readInt(); } static get minWireSize() { return 4; } }; Slice$U.defineStruct(Dispatcher.HeartbeatRT, true, false); Dispatcher.ChangePassWordT = class { constructor(Employeeid = "", oldPassWord = "", newPassWord = "") { this.Employeeid = Employeeid; this.oldPassWord = oldPassWord; this.newPassWord = newPassWord; } _write(ostr) { ostr.writeString(this.Employeeid); ostr.writeString(this.oldPassWord); ostr.writeString(this.newPassWord); } _read(istr) { this.Employeeid = istr.readString(); this.oldPassWord = istr.readString(); this.newPassWord = istr.readString(); } static get minWireSize() { return 3; } }; Slice$U.defineStruct(Dispatcher.ChangePassWordT, true, true); Dispatcher.ChangePassWordRT = class { constructor(Employeeid = "", issuccess = false) { this.Employeeid = Employeeid; this.issuccess = issuccess; } _write(ostr) { ostr.writeString(this.Employeeid); ostr.writeBool(this.issuccess); } _read(istr) { this.Employeeid = istr.readString(); this.issuccess = istr.readBool(); } static get minWireSize() { return 2; } }; Slice$U.defineStruct(Dispatcher.ChangePassWordRT, true, true); Dispatcher.ForceKickOutT = class { constructor(Employeeid = "", LoginUUID = "") { this.Employeeid = Employeeid; this.LoginUUID = LoginUUID; } _write(ostr) { ostr.writeString(this.Employeeid); ostr.writeString(this.LoginUUID); } _read(istr) { this.Employeeid = istr.readString(); this.LoginUUID = istr.readString(); } static get minWireSize() { return 2; } }; Slice$U.defineStruct(Dispatcher.ForceKickOutT, true, true); const iceC_Dispatcher_RegisterOP_ids = [ "::Dispatcher::RegisterOP", "::Ice::Object" ]; Dispatcher.RegisterOP = class extends ice.Ice.Object {}; Dispatcher.RegisterOPPrx = class extends ice.Ice.ObjectPrx {}; Slice$U.defineOperations(Dispatcher.RegisterOP, Dispatcher.RegisterOPPrx, iceC_Dispatcher_RegisterOP_ids, 0, { "IFCReqLogin": [, , , , [Dispatcher.LoginRT], [ [Dispatcher.Identity], [Dispatcher.LoginT] ], , [ Dispatcher.Error ], , ], "IFCReqLoginForce": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqLogout": [, , , , [Dispatcher.LogoutRT], [ [Dispatcher.Identity], [Dispatcher.LogoutT] ], , [ Dispatcher.Error ], , ], "IFCReqRelogin": [, 2, 2, , , [ [Dispatcher.Identity], [Dispatcher.ReloginT] ], , , , ], "IFCReqSendHB": [, , , , [Dispatcher.HeartbeatRT], [ [Dispatcher.Identity], [3] ], , [ Dispatcher.Error ], , ], "IFCReqSendHB2": [, , , , [7], [ [Dispatcher.Identity], [3] ], , [ Dispatcher.Error ], , ], "IFCReqChangePasswd": [, , , , [Dispatcher.ChangePassWordRT], [ [Dispatcher.Identity], [Dispatcher.ChangePassWordT] ], , [ Dispatcher.Error ], , ], "IFCReqForceLogout": [, , , , [1], [ [Dispatcher.Identity], [Dispatcher.ForceKickOutT] ], , [ Dispatcher.Error ], , ], "IFCReqAllUserRegState": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqLoginState": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ] }); const iceC_Dispatcher_RegisterSB_ids = [ "::Dispatcher::RegisterSB", "::Ice::Object" ]; Dispatcher.RegisterSB = class extends ice.Ice.Object {}; Dispatcher.RegisterSBPrx = class extends ice.Ice.ObjectPrx {}; Slice$U.defineOperations(Dispatcher.RegisterSB, Dispatcher.RegisterSBPrx, iceC_Dispatcher_RegisterSB_ids, 0); // const _ModuleRegistry$V = ice.Ice._ModuleRegistry; const Slice$V = ice.Ice.Slice; Dispatcher.Agent = class { constructor(employeeid = "", state = Dispatcher.RegisterState.RegisterStateNone, othernumber = "", othername = "", ip = "", DNSprefix = "") { this.employeeid = employeeid; this.state = state; this.othernumber = othernumber; this.othername = othername; this.ip = ip; this.DNSprefix = DNSprefix; } _write(ostr) { ostr.writeString(this.employeeid); Dispatcher.RegisterState._write(ostr, this.state); ostr.writeString(this.othernumber); ostr.writeString(this.othername); ostr.writeString(this.ip); ostr.writeString(this.DNSprefix); } _read(istr) { this.employeeid = istr.readString(); this.state = Dispatcher.RegisterState._read(istr); this.othernumber = istr.readString(); this.othername = istr.readString(); this.ip = istr.readString(); this.DNSprefix = istr.readString(); } static get minWireSize() { return 6; } }; Slice$V.defineStruct(Dispatcher.Agent, true, true); Slice$V.defineSequence(Dispatcher, "AgentSeqHelper", "Dispatcher.Agent", false); const iceC_Dispatcher_StateCB_ids = [ "::Dispatcher::StateCB", "::Ice::Object" ]; Dispatcher.StateCB = class extends ice.Ice.Object {}; Dispatcher.StateCBPrx = class extends ice.Ice.ObjectPrx {}; Slice$V.defineOperations(Dispatcher.StateCB, Dispatcher.StateCBPrx, iceC_Dispatcher_StateCB_ids, 0, { "IFCNotifyUserStateEvt": [, 2, 2, , , [ ["Dispatcher.AgentSeqHelper"] ], , , , ] }); // const _ModuleRegistry$W = ice.Ice._ModuleRegistry; const Slice$W = ice.Ice.Slice; Dispatcher.VideoBugT = class { constructor(cid = "", ip = "", port = "", srcid = "", dstid = "", state = Dispatcher.VBugStateType.VBugStateTypeNone) { this.cid = cid; this.ip = ip; this.port = port; this.srcid = srcid; this.dstid = dstid; this.state = state; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.ip); ostr.writeString(this.port); ostr.writeString(this.srcid); ostr.writeString(this.dstid); Dispatcher.VBugStateType._write(ostr, this.state); } _read(istr) { this.cid = istr.readString(); this.ip = istr.readString(); this.port = istr.readString(); this.srcid = istr.readString(); this.dstid = istr.readString(); this.state = Dispatcher.VBugStateType._read(istr); } static get minWireSize() { return 6; } }; Slice$W.defineStruct(Dispatcher.VideoBugT, true, true); Dispatcher.VideoBugT1 = class { constructor(cid = "", ip = "", port = "", srcid = "", dstid = "", audiocodec = "", videocodec = "", state = Dispatcher.VBugStateType.VBugStateTypeNone) { this.cid = cid; this.ip = ip; this.port = port; this.srcid = srcid; this.dstid = dstid; this.audiocodec = audiocodec; this.videocodec = videocodec; this.state = state; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.ip); ostr.writeString(this.port); ostr.writeString(this.srcid); ostr.writeString(this.dstid); ostr.writeString(this.audiocodec); ostr.writeString(this.videocodec); Dispatcher.VBugStateType._write(ostr, this.state); } _read(istr) { this.cid = istr.readString(); this.ip = istr.readString(); this.port = istr.readString(); this.srcid = istr.readString(); this.dstid = istr.readString(); this.audiocodec = istr.readString(); this.videocodec = istr.readString(); this.state = Dispatcher.VBugStateType._read(istr); } static get minWireSize() { return 8; } }; Slice$W.defineStruct(Dispatcher.VideoBugT1, true, true); Dispatcher.PlayVideoEvT = class { constructor(cid = "", uuid = "", type = Dispatcher.PlayVideoType.PlayVideoTypeNone) { this.cid = cid; this.uuid = uuid; this.type = type; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.uuid); Dispatcher.PlayVideoType._write(ostr, this.type); } _read(istr) { this.cid = istr.readString(); this.uuid = istr.readString(); this.type = Dispatcher.PlayVideoType._read(istr); } static get minWireSize() { return 3; } }; Slice$W.defineStruct(Dispatcher.PlayVideoEvT, true, true); const iceC_Dispatcher_VideoCB_ids = [ "::Dispatcher::VideoCB", "::Ice::Object" ]; Dispatcher.VideoCB = class extends ice.Ice.Object {}; Dispatcher.VideoCBPrx = class extends ice.Ice.ObjectPrx {}; Slice$W.defineOperations(Dispatcher.VideoCB, Dispatcher.VideoCBPrx, iceC_Dispatcher_VideoCB_ids, 0, { "IFCNotifyVideoBugEvt": [, 2, 2, , , [ [Dispatcher.VideoBugT] ], , , , ], "IFCNotifyVideoBugEvt2": [, 2, 2, , , [ [Dispatcher.VideoBugT1] ], , , , ], "IFCNotifyPlayVideoEvt": [, 2, 2, , , [ [Dispatcher.PlayVideoEvT] ], , , , ] }); // const _ModuleRegistry$X = ice.Ice._ModuleRegistry; const Slice$X = ice.Ice.Slice; Dispatcher.VideoBugStartT = class { constructor(dstid = "", ip = "", port = "", codec = "", srcid = "") { this.dstid = dstid; this.ip = ip; this.port = port; this.codec = codec; this.srcid = srcid; } _write(ostr) { ostr.writeString(this.dstid); ostr.writeString(this.ip); ostr.writeString(this.port); ostr.writeString(this.codec); ostr.writeString(this.srcid); } _read(istr) { this.dstid = istr.readString(); this.ip = istr.readString(); this.port = istr.readString(); this.codec = istr.readString(); this.srcid = istr.readString(); } static get minWireSize() { return 5; } }; Slice$X.defineStruct(Dispatcher.VideoBugStartT, true, true); Dispatcher.VideoBugStartRT = class { constructor(cid = "", srcid = "") { this.cid = cid; this.srcid = srcid; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.srcid); } _read(istr) { this.cid = istr.readString(); this.srcid = istr.readString(); } static get minWireSize() { return 2; } }; Slice$X.defineStruct(Dispatcher.VideoBugStartRT, true, true); Dispatcher.VideoBugEndT = class { constructor(cid = "", srcid = "") { this.cid = cid; this.srcid = srcid; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.srcid); } _read(istr) { this.cid = istr.readString(); this.srcid = istr.readString(); } static get minWireSize() { return 2; } }; Slice$X.defineStruct(Dispatcher.VideoBugEndT, true, true); Dispatcher.VideoBugEndRT = class { constructor(srcid = "") { this.srcid = srcid; } _write(ostr) { ostr.writeString(this.srcid); } _read(istr) { this.srcid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$X.defineStruct(Dispatcher.VideoBugEndRT, true, true); Dispatcher.PlayVideoT = class { constructor(cid = "", fid = "", state = Dispatcher.PlayVideoType.PlayVideoTypeNone) { this.cid = cid; this.fid = fid; this.state = state; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.fid); Dispatcher.PlayVideoType._write(ostr, this.state); } _read(istr) { this.cid = istr.readString(); this.fid = istr.readString(); this.state = Dispatcher.PlayVideoType._read(istr); } static get minWireSize() { return 3; } }; Slice$X.defineStruct(Dispatcher.PlayVideoT, true, true); Dispatcher.PlayVideoRT = class { constructor(code = 0) { this.code = code; } _write(ostr) { ostr.writeInt(this.code); } _read(istr) { this.code = istr.readInt(); } static get minWireSize() { return 4; } }; Slice$X.defineStruct(Dispatcher.PlayVideoRT, true, false); Dispatcher.VideoInfoT = class { constructor(dummy = "") { this.dummy = dummy; } _write(ostr) { ostr.writeString(this.dummy); } _read(istr) { this.dummy = istr.readString(); } static get minWireSize() { return 1; } }; Slice$X.defineStruct(Dispatcher.VideoInfoT, true, true); Dispatcher.VideoChannelInfo = class { constructor(ID = 0, ChannelNum = 0, bindEmployeeID = "", ChannelName = "") { this.ID = ID; this.ChannelNum = ChannelNum; this.bindEmployeeID = bindEmployeeID; this.ChannelName = ChannelName; } _write(ostr) { ostr.writeInt(this.ID); ostr.writeInt(this.ChannelNum); ostr.writeString(this.bindEmployeeID); ostr.writeString(this.ChannelName); } _read(istr) { this.ID = istr.readInt(); this.ChannelNum = istr.readInt(); this.bindEmployeeID = istr.readString(); this.ChannelName = istr.readString(); } static get minWireSize() { return 10; } }; Slice$X.defineStruct(Dispatcher.VideoChannelInfo, true, true); Slice$X.defineSequence(Dispatcher, "VideoChannelsHelper", "Dispatcher.VideoChannelInfo", false); Dispatcher.VideoInfoElem = class { constructor(id = 0, videoIP = "", videoport = "", user = "", password = "", showname = "", type = Dispatcher.emVideoDeviceType.VDTNONE, channels = null) { this.id = id; this.videoIP = videoIP; this.videoport = videoport; this.user = user; this.password = password; this.showname = showname; this.type = type; this.channels = channels; } _write(ostr) { ostr.writeInt(this.id); ostr.writeString(this.videoIP); ostr.writeString(this.videoport); ostr.writeString(this.user); ostr.writeString(this.password); ostr.writeString(this.showname); Dispatcher.emVideoDeviceType._write(ostr, this.type); Dispatcher.VideoChannelsHelper.write(ostr, this.channels); } _read(istr) { this.id = istr.readInt(); this.videoIP = istr.readString(); this.videoport = istr.readString(); this.user = istr.readString(); this.password = istr.readString(); this.showname = istr.readString(); this.type = Dispatcher.emVideoDeviceType._read(istr); this.channels = Dispatcher.VideoChannelsHelper.read(istr); } static get minWireSize() { return 11; } }; Slice$X.defineStruct(Dispatcher.VideoInfoElem, true, true); Slice$X.defineSequence(Dispatcher, "VideoInfoSeqHelper", "Dispatcher.VideoInfoElem", false); Dispatcher.VideoInfoRT = class { constructor(vseq = null) { this.vseq = vseq; } _write(ostr) { Dispatcher.VideoInfoSeqHelper.write(ostr, this.vseq); } _read(istr) { this.vseq = Dispatcher.VideoInfoSeqHelper.read(istr); } static get minWireSize() { return 1; } }; Slice$X.defineStruct(Dispatcher.VideoInfoRT, true, true); Dispatcher.VideoChannelInfo1 = class { constructor(ID = 0, ChannelNum = 0, bindEmployeeID = "", ChannelName = "") { this.ID = ID; this.ChannelNum = ChannelNum; this.bindEmployeeID = bindEmployeeID; this.ChannelName = ChannelName; } _write(ostr) { ostr.writeInt(this.ID); ostr.writeInt(this.ChannelNum); ostr.writeString(this.bindEmployeeID); ostr.writeString(this.ChannelName); } _read(istr) { this.ID = istr.readInt(); this.ChannelNum = istr.readInt(); this.bindEmployeeID = istr.readString(); this.ChannelName = istr.readString(); } static get minWireSize() { return 10; } }; Slice$X.defineStruct(Dispatcher.VideoChannelInfo1, true, true); Slice$X.defineSequence(Dispatcher, "VideoChannels1Helper", "Dispatcher.VideoChannelInfo1", false); Dispatcher.VideoInfoElem1 = class { constructor(id = 0, videoIP = "", videoport = "", user = "", password = "", showname = "", type = 0, channels = null) { this.id = id; this.videoIP = videoIP; this.videoport = videoport; this.user = user; this.password = password; this.showname = showname; this.type = type; this.channels = channels; } _write(ostr) { ostr.writeInt(this.id); ostr.writeString(this.videoIP); ostr.writeString(this.videoport); ostr.writeString(this.user); ostr.writeString(this.password); ostr.writeString(this.showname); ostr.writeInt(this.type); Dispatcher.VideoChannels1Helper.write(ostr, this.channels); } _read(istr) { this.id = istr.readInt(); this.videoIP = istr.readString(); this.videoport = istr.readString(); this.user = istr.readString(); this.password = istr.readString(); this.showname = istr.readString(); this.type = istr.readInt(); this.channels = Dispatcher.VideoChannels1Helper.read(istr); } static get minWireSize() { return 14; } }; Slice$X.defineStruct(Dispatcher.VideoInfoElem1, true, true); Slice$X.defineSequence(Dispatcher, "VideoInfoSeq1Helper", "Dispatcher.VideoInfoElem1", false); Dispatcher.VideoInfoRT1 = class { constructor(vseq = null) { this.vseq = vseq; } _write(ostr) { Dispatcher.VideoInfoSeq1Helper.write(ostr, this.vseq); } _read(istr) { this.vseq = Dispatcher.VideoInfoSeq1Helper.read(istr); } static get minWireSize() { return 1; } }; Slice$X.defineStruct(Dispatcher.VideoInfoRT1, true, true); Dispatcher.VideoControlType = Slice$X.defineEnum([ ['VideoControlTypeX', 0], ['VideoControlTypeY', 1], ['VideoControlTypeZoom', 2], ['VideoControlTypeLR', 3], ['VideoControlTypeFocus', 4], ['VideoControlTypeZoomADD', 20], ['VideoControlTypeZoomDEL', 21] ]); Dispatcher.CameraNumberControl = class { constructor(number = "", ctype = Dispatcher.VideoControlType.VideoControlTypeX, IsStart = true, TimeOut = 0, step = 0.0) { this.number = number; this.ctype = ctype; this.IsStart = IsStart; this.TimeOut = TimeOut; this.step = step; } _write(ostr) { ostr.writeString(this.number); Dispatcher.VideoControlType._write(ostr, this.ctype); ostr.writeBool(this.IsStart); ostr.writeInt(this.TimeOut); ostr.writeFloat(this.step); } _read(istr) { this.number = istr.readString(); this.ctype = Dispatcher.VideoControlType._read(istr); this.IsStart = istr.readBool(); this.TimeOut = istr.readInt(); this.step = istr.readFloat(); } static get minWireSize() { return 11; } }; Slice$X.defineStruct(Dispatcher.CameraNumberControl, false, true); Dispatcher.CameraIPControl = class { constructor(strip = "", strport = "", struser = "", strpwd = "", channel = -1, ctype = Dispatcher.VideoControlType.VideoControlTypeX, IsStart = true, TimeOut = 0, step = 0.0) { this.strip = strip; this.strport = strport; this.struser = struser; this.strpwd = strpwd; this.channel = channel; this.ctype = ctype; this.IsStart = IsStart; this.TimeOut = TimeOut; this.step = step; } _write(ostr) { ostr.writeString(this.strip); ostr.writeString(this.strport); ostr.writeString(this.struser); ostr.writeString(this.strpwd); ostr.writeInt(this.channel); Dispatcher.VideoControlType._write(ostr, this.ctype); ostr.writeBool(this.IsStart); ostr.writeInt(this.TimeOut); ostr.writeFloat(this.step); } _read(istr) { this.strip = istr.readString(); this.strport = istr.readString(); this.struser = istr.readString(); this.strpwd = istr.readString(); this.channel = istr.readInt(); this.ctype = Dispatcher.VideoControlType._read(istr); this.IsStart = istr.readBool(); this.TimeOut = istr.readInt(); this.step = istr.readFloat(); } static get minWireSize() { return 18; } }; Slice$X.defineStruct(Dispatcher.CameraIPControl, false, true); Dispatcher.HistoryVideoT = class { constructor(srcnumber = "", caramnumber = "", timestart = "", timeend = "") { this.srcnumber = srcnumber; this.caramnumber = caramnumber; this.timestart = timestart; this.timeend = timeend; } _write(ostr) { ostr.writeString(this.srcnumber); ostr.writeString(this.caramnumber); ostr.writeString(this.timestart); ostr.writeString(this.timeend); } _read(istr) { this.srcnumber = istr.readString(); this.caramnumber = istr.readString(); this.timestart = istr.readString(); this.timeend = istr.readString(); } static get minWireSize() { return 4; } }; Slice$X.defineStruct(Dispatcher.HistoryVideoT, true, true); Dispatcher.HistoryVideoOperateT = class { constructor(cid = "", caramnumber = "", second = 0) { this.cid = cid; this.caramnumber = caramnumber; this.second = second; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.caramnumber); ostr.writeInt(this.second); } _read(istr) { this.cid = istr.readString(); this.caramnumber = istr.readString(); this.second = istr.readInt(); } static get minWireSize() { return 6; } }; Slice$X.defineStruct(Dispatcher.HistoryVideoOperateT, true, true); Dispatcher.HistoryVSpeedT = class { constructor(cid = "", caramnumber = "", speed = 1) { this.cid = cid; this.caramnumber = caramnumber; this.speed = speed; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.caramnumber); ostr.writeFloat(this.speed); } _read(istr) { this.cid = istr.readString(); this.caramnumber = istr.readString(); this.speed = istr.readFloat(); } static get minWireSize() { return 6; } }; Slice$X.defineStruct(Dispatcher.HistoryVSpeedT, false, true); Dispatcher.PlayHistoryVideoRT = class { constructor(cid = "", caramnumber = "", msg = "") { this.cid = cid; this.caramnumber = caramnumber; this.msg = msg; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.caramnumber); ostr.writeString(this.msg); } _read(istr) { this.cid = istr.readString(); this.caramnumber = istr.readString(); this.msg = istr.readString(); } static get minWireSize() { return 3; } }; Slice$X.defineStruct(Dispatcher.PlayHistoryVideoRT, true, true); Dispatcher.SipPhoneVideoBugT = class { constructor(called = "", caller = "", codec = "") { this.called = called; this.caller = caller; this.codec = codec; } _write(ostr) { ostr.writeString(this.called); ostr.writeString(this.caller); ostr.writeString(this.codec); } _read(istr) { this.called = istr.readString(); this.caller = istr.readString(); this.codec = istr.readString(); } static get minWireSize() { return 3; } }; Slice$X.defineStruct(Dispatcher.SipPhoneVideoBugT, true, true); Dispatcher.SipPhoneVideoBugRT = class { constructor(cid = "", empid = "", sessnum = "") { this.cid = cid; this.empid = empid; this.sessnum = sessnum; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.empid); ostr.writeString(this.sessnum); } _read(istr) { this.cid = istr.readString(); this.empid = istr.readString(); this.sessnum = istr.readString(); } static get minWireSize() { return 3; } }; Slice$X.defineStruct(Dispatcher.SipPhoneVideoBugRT, true, true); const iceC_Dispatcher_VideoOP_ids = [ "::Dispatcher::VideoOP", "::Ice::Object" ]; Dispatcher.VideoOP = class extends ice.Ice.Object {}; Dispatcher.VideoOPPrx = class extends ice.Ice.ObjectPrx {}; Slice$X.defineOperations(Dispatcher.VideoOP, Dispatcher.VideoOPPrx, iceC_Dispatcher_VideoOP_ids, 0, { "IFCReqStartVideoBug": [, , , , [Dispatcher.VideoBugStartRT], [ [Dispatcher.Identity], [Dispatcher.VideoBugStartT] ], , [ Dispatcher.Error ], , ], "IFCReqStopVideoBug": [, , , , [Dispatcher.VideoBugEndRT], [ [Dispatcher.Identity], [Dispatcher.VideoBugEndT] ], , [ Dispatcher.Error ], , ], "IFCReqPlayVideo": [, , , , [Dispatcher.PlayVideoRT], [ [Dispatcher.Identity], [Dispatcher.PlayVideoT] ], , [ Dispatcher.Error ], , ], "IFCReqGetVideoInfo": [, , , , [Dispatcher.VideoInfoRT], [ [Dispatcher.Identity], [Dispatcher.VideoInfoT] ], , [ Dispatcher.Error ], , ], "IFCReqGetVideoInfo2": [, , , , [Dispatcher.VideoInfoRT1], [ [Dispatcher.Identity], [Dispatcher.VideoInfoT] ], , [ Dispatcher.Error ], , ], "IFCReqCameraControlByNumber": [, , , , , [ [Dispatcher.Identity], [Dispatcher.CameraNumberControl] ], , [ Dispatcher.Error ], , ], "IFCReqCameraControlByIP": [, , , , , [ [Dispatcher.Identity], [Dispatcher.CameraIPControl] ], , [ Dispatcher.Error ], , ], "IFCReqGetHistoryVideo": [, , , , , [ [Dispatcher.Identity], [Dispatcher.HistoryVideoT] ], , [ Dispatcher.Error ], , ], "IFCReqPlayHistoryVideo": [, , , , [Dispatcher.PlayHistoryVideoRT], [ [Dispatcher.Identity], [Dispatcher.HistoryVideoT] ], , [ Dispatcher.Error ], , ], "IFCReqHistoryVideoPlay": [, , , , , [ [Dispatcher.Identity], [Dispatcher.HistoryVideoOperateT] ], , [ Dispatcher.Error ], , ], "IFCReqHistoryVideoPause": [, , , , , [ [Dispatcher.Identity], [Dispatcher.HistoryVideoOperateT] ], , [ Dispatcher.Error ], , ], "IFCReqHistoryVideoSpeed": [, , , , , [ [Dispatcher.Identity], [Dispatcher.HistoryVSpeedT] ], , [ Dispatcher.Error ], , ], "IFCReqPhoneVideoBug": [, , , , [Dispatcher.SipPhoneVideoBugRT], [ [Dispatcher.Identity], [Dispatcher.SipPhoneVideoBugT] ], , [ Dispatcher.Error ], , ] }); // const _ModuleRegistry$Y = ice.Ice._ModuleRegistry; const Slice$Y = ice.Ice.Slice; Dispatcher.MdsStateAgentMonitorSessionType = class { constructor(sid = "", employeeid = "") { this.sid = sid; this.employeeid = employeeid; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.employeeid); } _read(istr) { this.sid = istr.readString(); this.employeeid = istr.readString(); } static get minWireSize() { return 2; } }; Slice$Y.defineStruct(Dispatcher.MdsStateAgentMonitorSessionType, true, true); Dispatcher.MdsStateAgentMonitorSessionElem = class { constructor(cid = "", caller = "", called = "", type = 0, time = "", level = 0, state = "") { this.cid = cid; this.caller = caller; this.called = called; this.type = type; this.time = time; this.level = level; this.state = state; } _write(ostr) { ostr.writeString(this.cid); ostr.writeString(this.caller); ostr.writeString(this.called); ostr.writeInt(this.type); ostr.writeString(this.time); ostr.writeInt(this.level); ostr.writeString(this.state); } _read(istr) { this.cid = istr.readString(); this.caller = istr.readString(); this.called = istr.readString(); this.type = istr.readInt(); this.time = istr.readString(); this.level = istr.readInt(); this.state = istr.readString(); } static get minWireSize() { return 13; } }; Slice$Y.defineStruct(Dispatcher.MdsStateAgentMonitorSessionElem, true, true); Slice$Y.defineSequence(Dispatcher, "MdsStateAgentMonitorSessionSeqHelper", "Dispatcher.MdsStateAgentMonitorSessionElem", false); Dispatcher.MdsStateAgentMonitorSessionRType = class { constructor(sid = "", sseq = null) { this.sid = sid; this.sseq = sseq; } _write(ostr) { ostr.writeString(this.sid); Dispatcher.MdsStateAgentMonitorSessionSeqHelper.write(ostr, this.sseq); } _read(istr) { this.sid = istr.readString(); this.sseq = Dispatcher.MdsStateAgentMonitorSessionSeqHelper.read(istr); } static get minWireSize() { return 2; } }; Slice$Y.defineStruct(Dispatcher.MdsStateAgentMonitorSessionRType, true, true); Dispatcher.MdsStateAgentMonitorDeviceType = class { constructor(sid = "", employeeid = "", employeename = "", type = 0) { this.sid = sid; this.employeeid = employeeid; this.employeename = employeename; this.type = type; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.employeeid); ostr.writeString(this.employeename); ostr.writeInt(this.type); } _read(istr) { this.sid = istr.readString(); this.employeeid = istr.readString(); this.employeename = istr.readString(); this.type = istr.readInt(); } static get minWireSize() { return 7; } }; Slice$Y.defineStruct(Dispatcher.MdsStateAgentMonitorDeviceType, true, true); Dispatcher.MdsStateAgentMonitorDeviceElem = class { constructor(employeename = "", employeeid = "", type = 0) { this.employeename = employeename; this.employeeid = employeeid; this.type = type; } _write(ostr) { ostr.writeString(this.employeename); ostr.writeString(this.employeeid); ostr.writeInt(this.type); } _read(istr) { this.employeename = istr.readString(); this.employeeid = istr.readString(); this.type = istr.readInt(); } static get minWireSize() { return 6; } }; Slice$Y.defineStruct(Dispatcher.MdsStateAgentMonitorDeviceElem, true, true); Slice$Y.defineSequence(Dispatcher, "MdsStateAgentMonitorDeviceSeqHelper", "Dispatcher.MdsStateAgentMonitorDeviceElem", false); Dispatcher.MdsStateAgentMonitorDeviceRType = class { constructor(sid = "", dseq = null) { this.sid = sid; this.dseq = dseq; } _write(ostr) { ostr.writeString(this.sid); Dispatcher.MdsStateAgentMonitorDeviceSeqHelper.write(ostr, this.dseq); } _read(istr) { this.sid = istr.readString(); this.dseq = Dispatcher.MdsStateAgentMonitorDeviceSeqHelper.read(istr); } static get minWireSize() { return 2; } }; Slice$Y.defineStruct(Dispatcher.MdsStateAgentMonitorDeviceRType, true, true); Dispatcher.MdsSessionAgentSetNightServiceType = class { constructor(sid = "", employeeid = "", nightnumber = "", starttime = "", endtime = "") { this.sid = sid; this.employeeid = employeeid; this.nightnumber = nightnumber; this.starttime = starttime; this.endtime = endtime; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.employeeid); ostr.writeString(this.nightnumber); ostr.writeString(this.starttime); ostr.writeString(this.endtime); } _read(istr) { this.sid = istr.readString(); this.employeeid = istr.readString(); this.nightnumber = istr.readString(); this.starttime = istr.readString(); this.endtime = istr.readString(); } static get minWireSize() { return 5; } }; Slice$Y.defineStruct(Dispatcher.MdsSessionAgentSetNightServiceType, true, true); Dispatcher.MdsSessionAgentSetNightServiceRsType = class { constructor(sid = "") { this.sid = sid; } _write(ostr) { ostr.writeString(this.sid); } _read(istr) { this.sid = istr.readString(); } static get minWireSize() { return 1; } }; Slice$Y.defineStruct(Dispatcher.MdsSessionAgentSetNightServiceRsType, true, true); Dispatcher.MdsSessionAgentSetNightServiceReType = class { constructor(sid = "", errid = 0, dis = "") { this.sid = sid; this.errid = errid; this.dis = dis; } _write(ostr) { ostr.writeString(this.sid); ostr.writeInt(this.errid); ostr.writeString(this.dis); } _read(istr) { this.sid = istr.readString(); this.errid = istr.readInt(); this.dis = istr.readString(); } static get minWireSize() { return 6; } }; Slice$Y.defineStruct(Dispatcher.MdsSessionAgentSetNightServiceReType, true, true); Dispatcher.MdsDataAgentGetConfigType = class { constructor(sid = "", employeeid = "") { this.sid = sid; this.employeeid = employeeid; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.employeeid); } _read(istr) { this.sid = istr.readString(); this.employeeid = istr.readString(); } static get minWireSize() { return 2; } }; Slice$Y.defineStruct(Dispatcher.MdsDataAgentGetConfigType, true, true); Dispatcher.MdsDataAgentGetConfigRType = class { constructor(sid = "", databasetype = "", databasename = "", databaseuser = "", databasepwd = "", databaseip = "", databaseport = "") { this.sid = sid; this.databasetype = databasetype; this.databasename = databasename; this.databaseuser = databaseuser; this.databasepwd = databasepwd; this.databaseip = databaseip; this.databaseport = databaseport; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.databasetype); ostr.writeString(this.databasename); ostr.writeString(this.databaseuser); ostr.writeString(this.databasepwd); ostr.writeString(this.databaseip); ostr.writeString(this.databaseport); } _read(istr) { this.sid = istr.readString(); this.databasetype = istr.readString(); this.databasename = istr.readString(); this.databaseuser = istr.readString(); this.databasepwd = istr.readString(); this.databaseip = istr.readString(); this.databaseport = istr.readString(); } static get minWireSize() { return 7; } }; Slice$Y.defineStruct(Dispatcher.MdsDataAgentGetConfigRType, true, true); Dispatcher.MdsDataAgentDatachangeType = class { constructor(a = 0) { this.a = a; } _write(ostr) { ostr.writeInt(this.a); } _read(istr) { this.a = istr.readInt(); } static get minWireSize() { return 4; } }; Slice$Y.defineStruct(Dispatcher.MdsDataAgentDatachangeType, true, false); Dispatcher.MdsDataAgentGetDataType = class { constructor(sid = "", tablename = "") { this.sid = sid; this.tablename = tablename; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.tablename); } _read(istr) { this.sid = istr.readString(); this.tablename = istr.readString(); } static get minWireSize() { return 2; } }; Slice$Y.defineStruct(Dispatcher.MdsDataAgentGetDataType, true, true); Dispatcher.MdsDataAgentGetTerminalVideoIpType = class { constructor(sid = "", employeeid = "") { this.sid = sid; this.employeeid = employeeid; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.employeeid); } _read(istr) { this.sid = istr.readString(); this.employeeid = istr.readString(); } static get minWireSize() { return 2; } }; Slice$Y.defineStruct(Dispatcher.MdsDataAgentGetTerminalVideoIpType, true, true); Dispatcher.MdsDataAgentGetTerminalVideoIpRType = class { constructor(sid = "", employeeid = "", videoip = "") { this.sid = sid; this.employeeid = employeeid; this.videoip = videoip; } _write(ostr) { ostr.writeString(this.sid); ostr.writeString(this.employeeid); ostr.writeString(this.videoip); } _read(istr) { this.sid = istr.readString(); this.employeeid = istr.readString(); this.videoip = istr.readString(); } static get minWireSize() { return 3; } }; Slice$Y.defineStruct(Dispatcher.MdsDataAgentGetTerminalVideoIpRType, true, true); Dispatcher.BindTerminalT = class { constructor(number = "", type = 0) { this.number = number; this.type = type; } _write(ostr) { ostr.writeString(this.number); ostr.writeInt(this.type); } _read(istr) { this.number = istr.readString(); this.type = istr.readInt(); } static get minWireSize() { return 5; } }; Slice$Y.defineStruct(Dispatcher.BindTerminalT, true, true); Slice$Y.defineSequence(Dispatcher, "BindTerminalSeqHelper", "Dispatcher.BindTerminalT", false); Dispatcher.BindTerminalRT = class { constructor(ret = "") { this.ret = ret; } _write(ostr) { ostr.writeString(this.ret); } _read(istr) { this.ret = istr.readString(); } static get minWireSize() { return 1; } }; Slice$Y.defineStruct(Dispatcher.BindTerminalRT, true, true); Dispatcher.AllStateT = class { constructor(type = "", group = "", employeeid = "") { this.type = type; this.group = group; this.employeeid = employeeid; } _write(ostr) { ostr.writeString(this.type); ostr.writeString(this.group); ostr.writeString(this.employeeid); } _read(istr) { this.type = istr.readString(); this.group = istr.readString(); this.employeeid = istr.readString(); } static get minWireSize() { return 3; } }; Slice$Y.defineStruct(Dispatcher.AllStateT, true, true); Dispatcher.AllStateRT = class { constructor(employeeid = "", rstate = Dispatcher.RegisterState.RegisterStateNone, cstate = Dispatcher.CallState.CallStateNone, othernumber = "", othername = "") { this.employeeid = employeeid; this.rstate = rstate; this.cstate = cstate; this.othernumber = othernumber; this.othername = othername; } _write(ostr) { ostr.writeString(this.employeeid); Dispatcher.RegisterState._write(ostr, this.rstate); Dispatcher.CallState._write(ostr, this.cstate); ostr.writeString(this.othernumber); ostr.writeString(this.othername); } _read(istr) { this.employeeid = istr.readString(); this.rstate = Dispatcher.RegisterState._read(istr); this.cstate = Dispatcher.CallState._read(istr); this.othernumber = istr.readString(); this.othername = istr.readString(); } static get minWireSize() { return 5; } }; Slice$Y.defineStruct(Dispatcher.AllStateRT, true, true); Slice$Y.defineSequence(Dispatcher, "AllStateRSeqHelper", "Dispatcher.AllStateRT", false); Dispatcher.SetNightServiceT = class { constructor(nightnumber = "", starttime = "", endtime = "") { this.nightnumber = nightnumber; this.starttime = starttime; this.endtime = endtime; } _write(ostr) { ostr.writeString(this.nightnumber); ostr.writeString(this.starttime); ostr.writeString(this.endtime); } _read(istr) { this.nightnumber = istr.readString(); this.starttime = istr.readString(); this.endtime = istr.readString(); } static get minWireSize() { return 3; } }; Slice$Y.defineStruct(Dispatcher.SetNightServiceT, true, true); Dispatcher.SetNightServiceRT = class { constructor(dummy = "") { this.dummy = dummy; } _write(ostr) { ostr.writeString(this.dummy); } _read(istr) { this.dummy = istr.readString(); } static get minWireSize() { return 1; } }; Slice$Y.defineStruct(Dispatcher.SetNightServiceRT, true, true); Dispatcher.GetNightServiceRT = class { constructor(nightnumber = "", starttime = "", endtime = "") { this.nightnumber = nightnumber; this.starttime = starttime; this.endtime = endtime; } _write(ostr) { ostr.writeString(this.nightnumber); ostr.writeString(this.starttime); ostr.writeString(this.endtime); } _read(istr) { this.nightnumber = istr.readString(); this.starttime = istr.readString(); this.endtime = istr.readString(); } static get minWireSize() { return 3; } }; Slice$Y.defineStruct(Dispatcher.GetNightServiceRT, true, true); Dispatcher.GetNightServiceT = class { constructor(number = "") { this.number = number; } _write(ostr) { ostr.writeString(this.number); } _read(istr) { this.number = istr.readString(); } static get minWireSize() { return 1; } }; Slice$Y.defineStruct(Dispatcher.GetNightServiceT, true, true); Dispatcher.TerminalDetailT = class { constructor(number = "") { this.number = number; } _write(ostr) { ostr.writeString(this.number); } _read(istr) { this.number = istr.readString(); } static get minWireSize() { return 1; } }; Slice$Y.defineStruct(Dispatcher.TerminalDetailT, true, true); Dispatcher.TerminalDetailRT = class { constructor(id = 0, employeeId = "", password = "", employeeLevel = 0, departId = 0, roleId = 0, name = "", addTime = "", modifyTime = "", theState = 0, theType = 0, remark = "", latitude = 0.0, longitude = 0.0, isRecord = 0, monName = "", monPasswd = "", monIp = "", monPort = 0, monFlag = "", isVideo = 0) { this.id = id; this.employeeId = employeeId; this.password = password; this.employeeLevel = employeeLevel; this.departId = departId; this.roleId = roleId; this.name = name; this.addTime = addTime; this.modifyTime = modifyTime; this.theState = theState; this.theType = theType; this.remark = remark; this.latitude = latitude; this.longitude = longitude; this.isRecord = isRecord; this.monName = monName; this.monPasswd = monPasswd; this.monIp = monIp; this.monPort = monPort; this.monFlag = monFlag; this.isVideo = isVideo; } _write(ostr) { ostr.writeInt(this.id); ostr.writeString(this.employeeId); ostr.writeString(this.password); ostr.writeInt(this.employeeLevel); ostr.writeInt(this.departId); ostr.writeInt(this.roleId); ostr.writeString(this.name); ostr.writeString(this.addTime); ostr.writeString(this.modifyTime); ostr.writeInt(this.theState); ostr.writeInt(this.theType); ostr.writeString(this.remark); ostr.writeDouble(this.latitude); ostr.writeDouble(this.longitude); ostr.writeInt(this.isRecord); ostr.writeString(this.monName); ostr.writeString(this.monPasswd); ostr.writeString(this.monIp); ostr.writeInt(this.monPort); ostr.writeString(this.monFlag); ostr.writeInt(this.isVideo); } _read(istr) { this.id = istr.readInt(); this.employeeId = istr.readString(); this.password = istr.readString(); this.employeeLevel = istr.readInt(); this.departId = istr.readInt(); this.roleId = istr.readInt(); this.name = istr.readString(); this.addTime = istr.readString(); this.modifyTime = istr.readString(); this.theState = istr.readInt(); this.theType = istr.readInt(); this.remark = istr.readString(); this.latitude = istr.readDouble(); this.longitude = istr.readDouble(); this.isRecord = istr.readInt(); this.monName = istr.readString(); this.monPasswd = istr.readString(); this.monIp = istr.readString(); this.monPort = istr.readInt(); this.monFlag = istr.readString(); this.isVideo = istr.readInt(); } static get minWireSize() { return 62; } }; Slice$Y.defineStruct(Dispatcher.TerminalDetailRT, false, true); Dispatcher.GetSessionEventT = class { constructor(dummy = "") { this.dummy = dummy; } _write(ostr) { ostr.writeString(this.dummy); } _read(istr) { this.dummy = istr.readString(); } static get minWireSize() { return 1; } }; Slice$Y.defineStruct(Dispatcher.GetSessionEventT, true, true); const iceC_Dispatcher_IFCSrv_ids = [ "::Dispatcher::BusinessOP", "::Dispatcher::CallingOP", "::Dispatcher::CallingVOP", "::Dispatcher::CommSrv", "::Dispatcher::ConfigureOP", "::Dispatcher::DecoderOP", "::Dispatcher::FaxOP", "::Dispatcher::FileOP", "::Dispatcher::GisOP", "::Dispatcher::IFCSrv", "::Dispatcher::McuOP", "::Dispatcher::MessageOP", "::Dispatcher::PrePlanOP", "::Dispatcher::PttOP", "::Dispatcher::PublishOP", "::Dispatcher::RailWayOP", "::Dispatcher::RegisterOP", "::Dispatcher::VideoOP", "::Ice::Object" ]; Dispatcher.IFCSrv = class extends ice.Ice.Object { static get _iceImplements() { return [ Dispatcher.CommSrv, Dispatcher.RegisterOP, Dispatcher.CallingOP, Dispatcher.ConfigureOP, Dispatcher.VideoOP, Dispatcher.GisOP, Dispatcher.PttOP, Dispatcher.MessageOP, Dispatcher.CallingVOP, Dispatcher.PrePlanOP, Dispatcher.FaxOP, Dispatcher.DecoderOP, Dispatcher.McuOP, Dispatcher.PublishOP, Dispatcher.BusinessOP, Dispatcher.RailWayOP ]; } }; Dispatcher.IFCSrvPrx = class extends ice.Ice.ObjectPrx { static get _implements() { return [ Dispatcher.CommSrvPrx, Dispatcher.RegisterOPPrx, Dispatcher.CallingOPPrx, Dispatcher.ConfigureOPPrx, Dispatcher.VideoOPPrx, Dispatcher.GisOPPrx, Dispatcher.PttOPPrx, Dispatcher.MessageOPPrx, Dispatcher.CallingVOPPrx, Dispatcher.PrePlanOPPrx, Dispatcher.FaxOPPrx, Dispatcher.DecoderOPPrx, Dispatcher.McuOPPrx, Dispatcher.PublishOPPrx, Dispatcher.BusinessOPPrx, Dispatcher.RailWayOPPrx ]; } }; Slice$Y.defineOperations(Dispatcher.IFCSrv, Dispatcher.IFCSrvPrx, iceC_Dispatcher_IFCSrv_ids, 9, { "IFCReqBindNumber": [, , , , [Dispatcher.BindTerminalRT], [ [Dispatcher.Identity], ["Dispatcher.BindTerminalSeqHelper"] ], , [ Dispatcher.Error ], , ], "IFCReqGetAllState": [, , , , ["Dispatcher.AllStateRSeqHelper"], [ [Dispatcher.Identity], [Dispatcher.AllStateT] ], , [ Dispatcher.Error ], , ], "IFCReqSetNightService": [, , , , [Dispatcher.SetNightServiceRT], [ [Dispatcher.Identity], [Dispatcher.SetNightServiceT] ], , [ Dispatcher.Error ], , ], "IFCReqSetNightServiceByJson": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetNightService": [, , , , [Dispatcher.GetNightServiceRT], [ [Dispatcher.Identity], [Dispatcher.GetNightServiceT] ], , [ Dispatcher.Error ], , ], "IFCReqGetUserDetail": [, , , , [Dispatcher.TerminalDetailRT], [ [Dispatcher.Identity], [Dispatcher.TerminalDetailT] ], , [ Dispatcher.Error ], , ], "IFCReqGetUserDetailByJson": [, , , , [7], [ [Dispatcher.Identity], [7] ], , [ Dispatcher.Error ], , ], "IFCReqGetSessionEvt": [, 2, 2, , , [ [Dispatcher.Identity], [Dispatcher.GetSessionEventT] ], , , , ], "IFCReqGetUserConfig": [, 2, 2, , , [ [7], [Dispatcher.MdsDataAgentGetConfigType] ], , , , ], "IFCReqDataChange": [, 2, 2, , , [ [7], [Dispatcher.MdsDataAgentDatachangeType] ], , , , ], "IFCReqMonitorSession": [, 2, 2, , , [ [7], [Dispatcher.MdsStateAgentMonitorSessionType] ], , , , ], "IFCReqMonitorDevice": [, 2, 2, , , [ [7], [Dispatcher.MdsStateAgentMonitorDeviceType] ], , , , ], "IFCReqAgentGetUserVideoIP": [, 2, 2, , , [ [7], [Dispatcher.MdsDataAgentGetTerminalVideoIpType] ], , , , ] }); const iceC_Dispatcher_MDCCli_ids = [ "::Dispatcher::CallingCB", "::Dispatcher::CallingVCB", "::Dispatcher::CommCli", "::Dispatcher::ConfigureCB", "::Dispatcher::DecoderCB", "::Dispatcher::FaxCB", "::Dispatcher::FileCB", "::Dispatcher::GisCB", "::Dispatcher::MDCCli", "::Dispatcher::McuCB", "::Dispatcher::MessageCB", "::Dispatcher::PrePlanCB", "::Dispatcher::PttCB", "::Dispatcher::PublishCB", "::Dispatcher::RegisterCB", "::Dispatcher::StateCB", "::Dispatcher::VideoCB", "::Ice::Object" ]; Dispatcher.MDCCli = class extends ice.Ice.Object { static get _iceImplements() { return [ Dispatcher.CommCli, Dispatcher.RegisterCB, Dispatcher.CallingCB, Dispatcher.ConfigureCB, Dispatcher.VideoCB, Dispatcher.GisCB, Dispatcher.PttCB, Dispatcher.MessageCB, Dispatcher.CallingVCB, Dispatcher.PrePlanCB, Dispatcher.FaxCB, Dispatcher.StateCB, Dispatcher.DecoderCB, Dispatcher.McuCB, Dispatcher.PublishCB ]; } }; Dispatcher.MDCCliPrx = class extends ice.Ice.ObjectPrx { static get _implements() { return [ Dispatcher.CommCliPrx, Dispatcher.RegisterCBPrx, Dispatcher.CallingCBPrx, Dispatcher.ConfigureCBPrx, Dispatcher.VideoCBPrx, Dispatcher.GisCBPrx, Dispatcher.PttCBPrx, Dispatcher.MessageCBPrx, Dispatcher.CallingVCBPrx, Dispatcher.PrePlanCBPrx, Dispatcher.FaxCBPrx, Dispatcher.StateCBPrx, Dispatcher.DecoderCBPrx, Dispatcher.McuCBPrx, Dispatcher.PublishCBPrx ]; } }; Slice$Y.defineOperations(Dispatcher.MDCCli, Dispatcher.MDCCliPrx, iceC_Dispatcher_MDCCli_ids, 8); // const _ModuleRegistry$Z = ice.Ice._ModuleRegistry; const Slice$Z = ice.Ice.Slice; const iceC_Dispatcher_MobileOP_ids = [ "::Dispatcher::CallingOP", "::Dispatcher::CallingVOP", "::Dispatcher::ConfigureOP", "::Dispatcher::FileOP", "::Dispatcher::GisOP", "::Dispatcher::MessageOP", "::Dispatcher::MobileOP", "::Dispatcher::PttOP", "::Dispatcher::RegisterOP", "::Dispatcher::VideoOP", "::Ice::Object" ]; Dispatcher.MobileOP = class extends ice.Ice.Object { static get _iceImplements() { return [ Dispatcher.RegisterOP, Dispatcher.PttOP, Dispatcher.VideoOP, Dispatcher.CallingOP, Dispatcher.MessageOP, Dispatcher.GisOP, Dispatcher.CallingVOP, Dispatcher.ConfigureOP ]; } }; Dispatcher.MobileOPPrx = class extends ice.Ice.ObjectPrx { static get _implements() { return [ Dispatcher.RegisterOPPrx, Dispatcher.PttOPPrx, Dispatcher.VideoOPPrx, Dispatcher.CallingOPPrx, Dispatcher.MessageOPPrx, Dispatcher.GisOPPrx, Dispatcher.CallingVOPPrx, Dispatcher.ConfigureOPPrx ]; } }; Slice$Z.defineOperations(Dispatcher.MobileOP, Dispatcher.MobileOPPrx, iceC_Dispatcher_MobileOP_ids, 6); /** * 分组类型 */ var GroupType; (function(GroupType) { /** * 非对讲组 */ GroupType[GroupType["Normal"] = 0] = "Normal"; /** * 对讲组 */ GroupType[GroupType["PTT"] = 1] = "PTT"; })(GroupType || (GroupType = {})); class Logger { constructor() { this.enable = true; } static getInstance() { if (Logger.sInstance == null) { Logger.sInstance = new Logger(); } return Logger.sInstance; } log(msg) { if (this.enable) { msg = this.getNowFormatDate() + " : " + msg; console.log(msg); } } warn(msg) { if (this.enable) { msg = this.getNowFormatDate() + " : " + msg; console.warn(msg); } } error(msg) { if (this.enable) { msg = this.getNowFormatDate() + " : " + msg; console.error(msg); } } getNowFormatDate() { var date = new Date(); var seperator1 = "/"; //设置成自己想要的日期格式 年/月/日 var seperator2 = ":"; //设置成自己想要的时间格式 时:分:秒 var month = date.getMonth() + 1; //月 var strDate = date.getDate(); //日 // if (month >= 1 && month <= 9) { // month = "0" + month; // } // if (strDate >= 0 && strDate <= 9) { // strDate = "0" + strDate; // } var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate + " " + date.getHours() + seperator2 + date.getMinutes() + seperator2 + date.getSeconds(); return currentdate; } } Logger.sInstance = null; class LoginInfo { constructor() { this.handleMode = exports.HandleMode.Normal; // audioDeviceId: string ="default"; // videoDeviceId: string ="default"; this.audioInputDeviceConfig = { id: "" }; this.videoInputDeviceConfig = { id: "", width: 0, height: 0, frameRate: 100 }; } static getInstance() { if (LoginInfo.s_instance == null) { LoginInfo.s_instance = new LoginInfo(); } return LoginInfo.s_instance; } get currentNumber() { switch (this.handleMode) { case exports.HandleMode.Left: return this.leftPhone; case exports.HandleMode.Right: return this.rightPhone; default: break; } return this.number; } } var RecoderServerType; (function(RecoderServerType) { RecoderServerType[RecoderServerType["Local"] = 0] = "Local"; RecoderServerType[RecoderServerType["RecoderServer"] = 1] = "RecoderServer"; })(RecoderServerType || (RecoderServerType = {})); /** * 用户类型 */ var UserType; (function(UserType) { /** * 0 其他 */ UserType[UserType["Other"] = 0] = "Other"; /** * 1 调度台 */ UserType[UserType["Dispatcher"] = 1] = "Dispatcher"; /** * 2 3G终端 */ UserType[UserType["APP"] = 2] = "APP"; /** * 3 SIP电话 */ UserType[UserType["SIP"] = 3] = "SIP"; /** * 4 监控用户 */ UserType[UserType["Monitor"] = 4] = "Monitor"; /** * 5 外线手机 */ UserType[UserType["OutlineMonitorPhone"] = 5] = "OutlineMonitorPhone"; /** * 6 外线座机 */ UserType[UserType["OutlineTelePhone"] = 6] = "OutlineTelePhone"; /** * 7 天通终端 */ UserType[UserType["TianTong"] = 7] = "TianTong"; /** * 8 323终端 */ UserType[UserType["Device323"] = 8] = "Device323"; /** * 9 韦德终端 */ UserType[UserType["Wade"] = 9] = "Wade"; /** * 10 基站组 */ UserType[UserType["StationGroup"] = 10] = "StationGroup"; /** * 11 中继台 */ UserType[UserType["RelayGateway"] = 11] = "RelayGateway"; /** * 12 定位车辆 */ UserType[UserType["OutlineCar"] = 12] = "OutlineCar"; /** * 13 自组网 */ UserType[UserType["MeshDevice"] = 13] = "MeshDevice"; // /** // * SSU用户 // */ // Phone, // /** // * 外线用户 // */ // OutLine, // /** // * 监控设备 // */ // MonitorDevice, // /** // * 对讲终端 // */ // handHeld, // OutlineTelePhone = 111, // OutlineCar = 18, // MeshDevice = 21, // OutlineMonitorPhone = 110, // TianTong = 20, // Wade = 17, // MCUReg = 15, // StationGroup = 10, // RelayGateway = 14, // /** // * 视频会议终端 // */ // VideoMeetingDevice = 9, // /** // * 基站成员 // */ // StationUser = 11, // /** // * 窄带对讲 // */ // NarrowIntercom = 16, // /** // * 外线调度台 // */ // OutlineDispatch = 100, // /** // * (handHeld) 外线 // */ // OutlineHandHeld = 101, // /** // * SIP电话(外线) // */ // OutlineCommonUser = 102, // /** // * MonitorUser(外线) // */ // OutlineMonitorUser = 104, // /** // * Ssu(外线) // */ // OutlineSsu = 105, // /** // * 监控设备(外线) // */ // OutlineMonitorDevice = 107, // /** // * 3G终端(外线) // */ // Outline3ghandheld = 106, })(UserType || (UserType = {})); /** * 呼叫方法 */ var CallDirection; (function(CallDirection) { /** * 0 呼出 */ CallDirection[CallDirection["Out"] = 0] = "Out"; /** * 1 呼入 */ CallDirection[CallDirection["In"] = 1] = "In"; })(CallDirection || (CallDirection = {})); /** * 用户呼叫状态 */ var UserCallState; (function(UserCallState) { /** * 0 无 */ UserCallState[UserCallState["None"] = 0] = "None"; /** * 1 初始 */ UserCallState[UserCallState["Init"] = 1] = "Init"; /** * 2 空闲 */ UserCallState[UserCallState["Normal"] = 2] = "Normal"; /** * 3 呼出 */ UserCallState[UserCallState["Callout"] = 3] = "Callout"; /** * 4 呼入 */ UserCallState[UserCallState["Incoming"] = 4] = "Incoming"; /** * 5 回铃 */ UserCallState[UserCallState["Ringing"] = 5] = "Ringing"; /** * 6 通话 */ UserCallState[UserCallState["Connect"] = 6] = "Connect"; /** * 7 保持 */ UserCallState[UserCallState["Hold"] = 7] = "Hold"; /**8 忙 */ UserCallState[UserCallState["Busy"] = 8] = "Busy"; /** * 9 摘机 */ UserCallState[UserCallState["Offhook"] = 9] = "Offhook"; /**10 离会 */ UserCallState[UserCallState["Release"] = 10] = "Release"; /**11 听讲 */ UserCallState[UserCallState["Unspeak"] = 11] = "Unspeak"; /**12 讲话 */ UserCallState[UserCallState["Speak"] = 12] = "Speak"; /**13排队 */ UserCallState[UserCallState["Queue"] = 13] = "Queue"; /**14取消保持 */ UserCallState[UserCallState["Unhold"] = 14] = "Unhold"; /**15暂离 */ UserCallState[UserCallState["Zombie"] = 15] = "Zombie"; })(UserCallState || (UserCallState = {})); // export enum CallState{ // Initial = "Initial", // Establishing = "Establishing", // Established = "Established", // Terminating = "Terminating", // Terminated = "Terminated" // } /** * 呼叫类型 */ var CallType; (function(CallType) { /** * 0 无 */ CallType[CallType["None"] = 0] = "None"; /** * 1 单呼 */ CallType[CallType["Single"] = 1] = "Single"; /** * 2 组呼 */ CallType[CallType["Group"] = 2] = "Group"; /** * 3 通播 */ CallType[CallType["Report"] = 3] = "Report"; /** * 4 广播 */ CallType[CallType["Broadcast"] = 4] = "Broadcast"; /** * 5 普通会议 */ CallType[CallType["Conference"] = 5] = "Conference"; /** * 6 强插 */ CallType[CallType["Interpose"] = 6] = "Interpose"; /** * 7 强拆 */ CallType[CallType["Forceremove"] = 7] = "Forceremove"; /** * 8 监听 */ CallType[CallType["Monitor"] = 8] = "Monitor"; /** * 9 转接 */ CallType[CallType["Switch"] = 9] = "Switch"; /** * 10 紧急呼叫 */ CallType[CallType["Urgent"] = 10] = "Urgent"; /** * 11对讲 */ CallType[CallType["Intercom"] = 11] = "Intercom"; /** * 12临时对讲 */ CallType[CallType["Tempintercom"] = 12] = "Tempintercom"; /** * 13 3G监控 */ CallType[CallType["VideoBug"] = 13] = "VideoBug"; /** * 14 MCU会议 */ CallType[CallType["MCUMetting"] = 14] = "MCUMetting"; /** * 15 紧急呼叫 */ CallType[CallType["SOS"] = 15] = "SOS"; /** * 16 转发视频 */ CallType[CallType["TransferVideo"] = 16] = "TransferVideo"; /** * 17 转发视频到mcu */ CallType[CallType["TransferVideoToMCU"] = 17] = "TransferVideoToMCU"; })(CallType || (CallType = {})); class UserInternal { /** * */ constructor() { const callState = { number: "0", otherNumber: "0", otherName: "0", callType: CallType.None, state: UserCallState.None, otherMark: "", otherLatitude: 0, otherLongitude: 0, direction: CallDirection.Out, sessionId: "" }; this.state = { registState: exports.RegistState.Unregisted, callState: callState }; } } var IceEventName; (function(IceEventName) { IceEventName[IceEventName["regStateChange"] = 0] = "regStateChange"; IceEventName[IceEventName["CallStateChange"] = 1] = "CallStateChange"; IceEventName[IceEventName["SessionStateChange"] = 2] = "SessionStateChange"; IceEventName[IceEventName["ServerDisconnect"] = 3] = "ServerDisconnect"; IceEventName[IceEventName["ServerConnectd"] = 4] = "ServerConnectd"; IceEventName[IceEventName["SessionMemberChange"] = 5] = "SessionMemberChange"; IceEventName[IceEventName["PttStateSpeaker"] = 6] = "PttStateSpeaker"; IceEventName[IceEventName["GisInfo"] = 7] = "GisInfo"; IceEventName[IceEventName["MsgReceived"] = 8] = "MsgReceived"; IceEventName[IceEventName["FileMsgReceived"] = 9] = "FileMsgReceived"; IceEventName[IceEventName["SessionSendToCreaterState"] = 10] = "SessionSendToCreaterState"; IceEventName[IceEventName["PttWaiting"] = 11] = "PttWaiting"; IceEventName[IceEventName["PttReject"] = 12] = "PttReject"; IceEventName[IceEventName["registKickout"] = 13] = "registKickout"; IceEventName[IceEventName["pushAudioToRTSP"] = 14] = "pushAudioToRTSP"; })(IceEventName || (IceEventName = {})); var e_Status; (function(e_Status) { e_Status[e_Status["nUnavailable"] = 0] = "nUnavailable"; e_Status[e_Status["nDisconnect"] = 1] = "nDisconnect"; e_Status[e_Status["nConnected"] = 2] = "nConnected"; e_Status[e_Status["nPublished"] = 3] = "nPublished"; })(e_Status || (e_Status = {})); class iceClientCallback extends Dispatcher.MDCCli { constructor() { super(...arguments); this._logger = Logger.getInstance(); this._lasthbTime = 0; } IFCNotifyForceLogout2(in0, current) { throw new Error("Method not implemented."); } IFCNotifyGisThirdDataEvt(info, current) { // throw new Error("Method not implemented."); } IFCNotifyGisHistoryEvt(info, current) { // throw new Error("Method not implemented."); } onPrePlanEv(_in, current) { throw new Error("Method not implemented."); } IFCNotifyForceLogout(in0, current) { throw new Error("Method not implemented."); } IFCNotifySessionStateEvt(in0, current) { throw new Error("Method not implemented."); } IFCNotifySessionStateEvt2(in0, current) { throw new Error("Method not implemented."); } IFCNotifyConfMemberStateEvt(in0, current) { throw new Error("Method not implemented."); } IFCNotifyCallStateEvt(in0, current) { throw new Error("Method not implemented."); } IFCNotifyAudioPlayStateEvt(in0, current) { // throw new Error("Method not implemented."); } IFCNotifyVideoBugEvt(in0, current) { // throw new Error("Method not implemented."); } IFCNotifyVideoBugEvt2(in0, current) { // throw new Error("Method not implemented."); } IFCNotifyPlayVideoEvt(in0, current) { throw new Error("Method not implemented."); } IFCNotifyGisInfoEvt(in0, current) { throw new Error("Method not implemented."); } IFCNotifyGisInfoEvt2(in0, current) { throw new Error("Method not implemented."); } IFCNotifyPhoneMsgEvt(in0, current) { throw new Error("Method not implemented."); } IFCNotifyGroupInfoEvt(in0, current) { throw new Error("Method not implemented."); } IFCNotifyReqRightResultEvt(in0, current) { throw new Error("Method not implemented."); } IFCNotifyUploadEvt(in0, current) { throw new Error("Method not implemented."); } IFCNotifyDeleteFileEvt(fid, current) { throw new Error("Method not implemented."); } IFCNotifyMsgEvt(in0, current) { this._eventEmitter.emit(IceEventName.MsgReceived.toString(), JSON.stringify(in0)); } IFCNotifyMsgDelEvt(msgid, current) { throw new Error("Method not implemented."); } IFCNotifySendVideoEvt(_in, current) { throw new Error("Method not implemented."); } IFCNotifyGetVideoEvt(_in, current) { throw new Error("Method not implemented."); } IFCNotifyFaxEvt(_in, current) { throw new Error("Method not implemented."); } IFCNotifyNewFaxEvt(_in, current) { throw new Error("Method not implemented."); } IFCNotifyUserStateEvt(aseq, current) { throw new Error("Method not implemented."); } IFCNotifyPublishMsgEvt(info, current) { // var msg1 = "IFCNotifyPublishMsgEvt header: " + info.subHeader + ", msg: " + info.subMsg; // this._logger.log(msg1); let msg = JSON.parse(info.subMsg); switch (info.subHeader) { case "Employee.State.Reg": let regState = exports.RegistState.Unregisted; switch (msg[0].state) { case "1": regState = exports.RegistState.Registed; break; case "2": regState = exports.RegistState.Unregisted; break; default: break; } this._eventEmitter.emit(IceEventName.regStateChange.toString(), msg[0].employeeid, regState); break; case "Employee.State.Call": let callType = iceAPI.convertIceCallType(msg[0].calltype); let callState = iceAPI.convertIceCallState(msg[0].state); let direciton = CallDirection.Out; if (msg[0].direct == "2") { direciton = CallDirection.In; } const callStateDetail = { number: msg[0].employeeid, otherNumber: msg[0].othernumber, otherName: msg[0].othername, callType: callType, state: callState, otherLatitude: msg[0].other_lat, otherLongitude: msg[0].other_lon, otherMark: msg[0].other_mark, direction: direciton, sessionId: msg[0].cid }; this._eventEmitter.emit(IceEventName.CallStateChange.toString(), msg[0].employeeid, callStateDetail); break; default: break; } // this._delegate.onSessionMember(msg); } IFCNotifyFixMsgEvt(info, current) { // var msg = "IFCNotifyFixMsgEvt header: " + info.subHeader + ", msg: " + info.subMsg; // this._logger.log(msg); switch (info.subHeader) { case "Session.State.Change": var msg = "IFCNotifyFixMsgEvt header: " + info.subHeader + ", msg: " + info.subMsg; this._logger.log(msg); this._eventEmitter.emit(IceEventName.SessionStateChange.toString(), info.subMsg); break; case "Session.Member.Change": this._eventEmitter.emit(IceEventName.SessionMemberChange.toString(), info.subMsg); break; case "Ptt.Waiting": this._eventEmitter.emit(IceEventName.PttWaiting.toString(), info.subMsg); break; case "Ptt.Reject": this._eventEmitter.emit(IceEventName.PttReject.toString(), info.subMsg); break; case "Ptt.State.Speaker": this._eventEmitter.emit(IceEventName.PttStateSpeaker.toString(), info.subMsg); break; case "GIS.Position.Change": this._eventEmitter.emit(IceEventName.GisInfo.toString(), info.subMsg); break; case "FileMsg.OnReceive": this._eventEmitter.emit(IceEventName.FileMsgReceived.toString(), info.subMsg); break; case "Session.SendToCreater.State": this._eventEmitter.emit(IceEventName.SessionSendToCreaterState.toString(), info.subMsg); break; case "Regist.Kickout.Event": this._eventEmitter.emit(IceEventName.registKickout.toString(), info.subMsg); break; case "Push.Call.Audio.To.Other": this._eventEmitter.emit(IceEventName.pushAudioToRTSP.toString(), info.subMsg); break; default: break; } // this._delegate.onSessionState(msg); } IFCNotifyPublishHBEvt(info, current) { this._lasthbTime = Date.now(); // this._logger.log("onReceiveHB " + this._lasthbTime); } get lasthbTime() { if (this._lasthbTime == 0) { this._lasthbTime = Date.now(); } return this._lasthbTime; } } class iceAPI extends EventEmitter { constructor() { super(); this._dispatcherPrx = null; this._caller = "1000"; this._iceStatus = e_Status.nUnavailable; this._isCheckIceNetworck = false; this._hbCount = 0; // _leftPhone: string; // _rightPhone: string; this._logger = Logger.getInstance(); this._sendHBTime = 0; this.started = false; } static getInstance() { if (iceAPI.instance == null) { iceAPI.instance = new iceAPI(); } return iceAPI.instance; } static convertIceCallState(icestate) { let callState = UserCallState.None; switch (icestate) { case "1": callState = UserCallState.Init; break; case "2": callState = UserCallState.Normal; break; case "3": callState = UserCallState.Callout; break; case "4": callState = UserCallState.Incoming; break; case "5": callState = UserCallState.Ringing; break; case "6": callState = UserCallState.Connect; break; case "7": callState = UserCallState.Hold; break; case "8": callState = UserCallState.Busy; break; case "9": callState = UserCallState.Offhook; break; case "10": callState = UserCallState.Release; break; case "11": callState = UserCallState.Unspeak; break; case "12": callState = UserCallState.Speak; break; case "13": callState = UserCallState.Queue; break; case "14": callState = UserCallState.Unhold; break; case "15": callState = UserCallState.Zombie; break; default: break; } return callState; } static convertIceCallState1(icestate) { let callState = CallState.None; switch (icestate) { case "1": callState = CallState.Init; break; case "2": callState = CallState.Normal; break; case "3": callState = CallState.Callout; break; case "4": callState = CallState.Incoming; break; case "5": callState = CallState.Ringing; break; case "6": callState = CallState.Connect; break; case "7": callState = CallState.Hold; break; case "10": callState = CallState.Release; break; case "13": callState = CallState.Hold; break; case "14": callState = CallState.Unhold; break; default: break; } return callState; } static convertIceCallType(iceCallType) { var callType = CallType.None; switch (iceCallType) { case "1": callType = CallType.Single; break; case "2": callType = CallType.Group; break; case "3": callType = CallType.Report; break; case "4": callType = CallType.Broadcast; break; case "5": callType = CallType.Conference; break; case "6": callType = CallType.Interpose; break; case "7": callType = CallType.Interpose; break; case "8": callType = CallType.Monitor; break; case "9": callType = CallType.Intercom; break; case "10": callType = CallType.Switch; break; case "11": callType = CallType.Urgent; break; case "12": callType = CallType.Single; break; case "13": callType = CallType.Tempintercom; break; case "14": callType = CallType.VideoBug; break; case "15": callType = CallType.MCUMetting; break; case "16": callType = CallType.SOS; break; case "17": callType = CallType.TransferVideo; break; case "18": callType = CallType.TransferVideoToMCU; break; default: break; } return callType; } iceInit() { const properties = ice.Ice.createProperties(); properties.setProperty("Ice.ACM.Close", "0"); const id = new ice.Ice.InitializationData(); id.properties = properties; this._iceCommunicator = ice.Ice.initialize(id); this._iceStatus = e_Status.nDisconnect; } async connect() { // const hostname = document.location.hostname || "127.0.0.1"; // this._proxy = this._iceCommunicator.stringToProxy("IFCSrv" + // ":wss -r /b -h " + this._serverIP + " -p " + this._serverPort); // this._serverIP = "localhost"; // this._serverPort = 9443; this._proxy = this._iceCommunicator.stringToProxy("IFCSrv" + ":wss -r /" + this._resourceUrl + " -h " + this._serverIP + " -p " + this._serverPort); this._caller = this._username; this._proxy.ice_timeout(10000); // // Set or clear the timeout. // // const timeout:number = Number($("#timeout").val()); const timeout = 10000; this._proxy = this._proxy.ice_invocationTimeout(timeout); // this._proxy.ice_getCommunicator().shutdown() // // Set the mode and protocol // // const mode = $("#mode").val(); // if(mode == "twoway") // { this._proxy = this._proxy.ice_twoway(); // } // else if(mode == "twoway-secure") // { // proxy = proxy.ice_twoway().ice_secure(true); // } // else if(mode == "oneway") // { // proxy = proxy.ice_oneway(); // } // else if(mode == "oneway-secure") // { // proxy = proxy.ice_oneway().ice_secure(true); // } // else if(mode == "oneway-batch") // { // proxy = proxy.ice_batchOneway(); // } // else if(mode == "oneway-batch-secure") // { // proxy = proxy.ice_batchOneway().ice_secure(true); // } this._dispatcherPrx = Dispatcher.IFCSrvPrx.uncheckedCast(this._proxy); const myadapter = await this._iceCommunicator.createObjectAdapter(""); const identity1 = new ice.Ice.Identity(this._caller, "MDCCli"); this._myid = new Dispatcher.Identity(this._caller); // myReceiver: Ice.IceClient; this._myReceiver = new iceClientCallback(); this._myReceiver._delegate = this._delegate; this._myReceiver._eventEmitter = this; myadapter.add(this._myReceiver, identity1); try { this._connection = await this._dispatcherPrx.ice_getConnection(); this._connection.setAdapter(myadapter); } catch (error) { this._logger.error("connect error: " + error); return; } this._iceStatus = e_Status.nConnected; } sendHeartBeat() { // this._hbCount++; // if (this._hbCount < 3) { // return; // } // this._hbCount = 0; if (this._dispatcherPrx != null && this._iceStatus == e_Status.nPublished) { // this._logger.log("sendhb"); this._dispatcherPrx.IFCReqPublishHB(this._myid, 120); this._sendHBTime = Date.now(); // return; // this._dispatcherPrx.IFCReqSendHB2(this._myid, 30).then( (result: string)=>{ // // this._logger.log("IFCReqSendHB2: " + result); // if (LoginInfo.getInstance().recordServer == null) { // LoginInfo.getInstance().recordServer = new RecordServerInfo(); // } // let recoderServerType = JSON.parse(result).trtype; // if (recoderServerType == "0") { // LoginInfo.getInstance().recordServer.type = RecoderServerType.Local; // LoginInfo.getInstance().recordServer.port = 8901; // LoginInfo.getInstance().recordServer.ip = this._serverIP; // }else{ // LoginInfo.getInstance().recordServer.type = RecoderServerType.RecoderServer; // LoginInfo.getInstance().recordServer.port = 8902; // let ip = JSON.parse(result).trexternalip; // if (ip == null || ip == "") { // ip = JSON.parse(result).trinternalip; // } // LoginInfo.getInstance().recordServer.ip = ip; // } // } ).catch((reason: any) => { // this._logger.warn("IFCReqSendHB2 fail: " + reason); // }) // this._dispatcherPrx.IFCReqSendHB(this._myid, 30).then( (result: Dispatcher.HeartbeatRT)=>{ // this._logger.log("IFCReqSendHB: "); // // let recoderServerType = JSON.parse(result).trtype; // // if (recoderServerType == "0") { // // LoginInfo.getInstance().recoderServerType = RecoderServerType.Local; // // }else{ // // LoginInfo.getInstance().recoderServerType = RecoderServerType.RecoderServer; // // } // } ).catch((reason: any) => { // this._logger.warn("IFCReqSendHB2 fail: "); // }) // this._dispatcherPrx.IFCReqPublishHB(this._myid, 30).then((result: boolean) => { // this._logger.log("IFCReqPublishHB:" + JSON.stringify(result)); // this._myReceiver._lasthbTime = Date.now(); // }).catch((result) => { // this._logger.log("IFCReqPublishHB fail" + JSON.stringify(result)); // }); } } publishInfo() { const subinfos = new Dispatcher.SubInfos(); subinfos.Infos = new Array(); const subinfo = new Dispatcher.SubInfo(); subinfo.subHeader = Dispatcher.EventPttStateSpeaker; subinfos.Infos.push(subinfo); const subinfoEmployeeState = new Dispatcher.SubInfo(); subinfoEmployeeState.subHeader = Dispatcher.EventEmployeeStateReg; subinfos.Infos.push(subinfoEmployeeState); const subinfoEmployeeCall = new Dispatcher.SubInfo(); subinfoEmployeeCall.subHeader = Dispatcher.EventEmployeeStateCall; subinfos.Infos.push(subinfoEmployeeCall); this._dispatcherPrx.IFCReqPublishMsg(this._myid, subinfos); this._iceStatus = e_Status.nPublished; this.emit(IceEventName.ServerConnectd.toString()); } checkIceNetwork() { // if (!iceAPI.getInstance()._isCheckIceNetworck) { // return; // } // iceAPI.getInstance()._logger.log("checkIceNetwork " + iceAPI.getInstance()._iceStatus); if (iceAPI.getInstance()._isCheckIceNetworck) { if (iceAPI.getInstance()._myReceiver != null && iceAPI.getInstance()._sendHBTime > 0) { let notReceiveHeartbeatTime = Date.now() - iceAPI.getInstance()._myReceiver.lasthbTime; let sendHBTimeSpan = Date.now() - iceAPI.getInstance()._sendHBTime; if (notReceiveHeartbeatTime > 30000 && notReceiveHeartbeatTime > sendHBTimeSpan) { iceAPI.getInstance()._logger.warn("hbTimeout!!! lasthbTime:" + iceAPI.getInstance()._myReceiver.lasthbTime + ", timeout: " + notReceiveHeartbeatTime + ", sendHBTimeSpan: " + sendHBTimeSpan); iceAPI.getInstance()._iceStatus = e_Status.nDisconnect; iceAPI.getInstance().emit(IceEventName.ServerDisconnect.toString()); } } if (iceAPI.getInstance()._iceStatus == e_Status.nUnavailable) { // iceAPI.getInstance()._logger.log("checkIceNetwork nUnavailable"); iceAPI.getInstance().iceInit(); // iceAPI.getInstance()._logger.log("checkIceNetwork nUnavailable1"); } if (iceAPI.getInstance()._iceStatus == e_Status.nDisconnect) { // iceAPI.getInstance()._logger.log("checkIceNetwork nDisconnect"); iceAPI.getInstance().connect(); // iceAPI.getInstance()._logger.log("checkIceNetwork nDisconnect1"); } if (iceAPI.getInstance()._iceStatus == e_Status.nConnected) { // iceAPI.getInstance()._logger.log("checkIceNetwork nConnected"); if (DispatcherClient.getInstance().registState == exports.RegistState.Registed) { iceAPI.getInstance().publishInfo(); } // iceAPI.getInstance()._logger.log("checkIceNetwork nConnected1"); } // iceAPI.getInstance()._logger.log("checkIceNetwork sendHeartBeat"); iceAPI.getInstance().sendHeartBeat(); // iceAPI.getInstance()._logger.log("checkIceNetwork sendHeartBeat1"); } // iceAPI.hellow(); // iceAPI.getInstance()._logger.log("checkIceNetwork repeat0"); if (iceAPI.getInstance()._isCheckIceNetworck) { // iceAPI.getInstance()._logger.log("checkIceNetwork repeat1"); setTimeout(iceAPI.getInstance().checkIceNetwork, 5000); // iceAPI.getInstance()._logger.log("checkIceNetwork repeat2"); // setInterval(iceAPI.getInstance().checkIceNetwork, 1000); } } regist(serverip, serverport, username, delegateHandler, resourceUrl = "") { // if (this.started) { // return; // } // this.started = true; this._serverIP = serverip; this._serverPort = serverport; this._username = username; this._isCheckIceNetworck = true; this._delegate = delegateHandler; this._resourceUrl = resourceUrl; // setIntkerval(iceAPI.getInstance().checkIceNetwork, 5000); this.checkIceNetwork(); } unRegist() { this._isCheckIceNetworck = false; try { if (this._iceStatus == e_Status.nPublished) { this._dispatcherPrx.IFCReqUnpublishMsg(this._myid); this._iceStatus = e_Status.nConnected; } if (this._dispatcherPrx != null) { this._dispatcherPrx = null; } } catch (ex) { this._logger.log(ex); } this._iceStatus = e_Status.nUnavailable; } async getGroupTree() { const info1 = new Dispatcher.TreeT(); info1.groupnum = ""; info1.userId = this._caller; const result = await this._dispatcherPrx.IFCReqGetOrganization(this._myid, info1); try { var str = JSON.stringify(result.roots); this._logger.log(str); } catch (error) {} return ""; // const result = await this._dispatcherPrx.IFCReqGetOrganizationByJson(this._myid, info1); // return result; // result.roots.length; // this._logger.log(); // // $("#output").val( result.roots[0].groupname); // result.roots.forEach(element => { // this._logger.log( " groupname = " + element.groupname); // }); // $("#output").val(result.roots.length); } getRootGroups() { const info1 = new Dispatcher.TreeT(); info1.groupnum = ""; info1.userId = this._caller; return this._dispatcherPrx.IFCReqGetOrganization(this._myid, info1).then((tree) => { var groups = new Array(); tree.roots.forEach(element => { var subGroup = this.convertICEGroup(element); groups.push(subGroup); }); return Promise.resolve(groups); }); } getGroupWithUsersById(groupId) { const info1 = new Dispatcher.TreeT(); info1.type = -1; info1.groupnum = groupId; info1.userId = this._caller; return this._dispatcherPrx.IFCReqGetOrganization(this._myid, info1).then((tree) => { this._logger.log(JSON.stringify(tree)); if (tree.roots.length > 0) { let group = this.convertICEGroup(tree.roots.pop()); return Promise.resolve(group); } }); } getLocalVideos() { let para = new Dispatcher.TreeT(); para.type = 7; //监控设备 para.userId = this._caller; return this._dispatcherPrx.IFCReqGetLocalUserByType(this._myid, para).then((tree) => { this._logger.warn("getlocalVideo: " + JSON.stringify(tree)); let monitors = new Array(); tree.roots.forEach(element => { let groupMonitors = this.getMonitorsByGroup(element); groupMonitors.forEach(monitor => { let exist = false; monitors.forEach(exsitMonitor => { if (exsitMonitor.number == monitor.number) { exist = true; } }); if (!exist) { monitors.push(monitor); } }); }); return Promise.resolve(monitors); }); } get28281Groups() { let para = new Dispatcher.GetFXDeviceT(); para.getdetail = false; return this._dispatcherPrx.IFCReqGet28181Devices(this._myid, para).then((monitors) => { var groups = new Array(); this._logger.log(JSON.stringify(monitors)); monitors.forEach(monitorElement => { var subGroups = Array(); monitorElement.Orgs.forEach(org => { var subGroup = this.convertICE28281Group(org); subGroups.push(subGroup); }); const group = { id: monitorElement.id, name: monitorElement.name, subGroups }; groups.push(group); this._logger.log(monitorElement.name); }); return Promise.resolve(groups); }); } getMonitors28281ByGroupId(deviceId, groupId) { var para = new Dispatcher.GetFXDeviceDetailT(); para.fxDeviceid = deviceId; para.orgid = groupId; return this._dispatcherPrx.IFCReqGet28181DeviceDetail(this._myid, para).then((devices) => { let monitors = Array(); devices.forEach(deviceElement => { deviceElement.Orgs.forEach(orgElement => { orgElement.Numbers.forEach(monitorElement => { const monitor = { number: monitorElement.num, name: monitorElement.name }; monitors.push(monitor); }); }); }); this._logger.log(JSON.stringify(devices)); return Promise.resolve(monitors); }); } getMonitorsByGroup(group) { let monitors = new Array(); group.user.forEach(element => { let monitor = { number: element.userid, name: element.username }; monitors.push(monitor); }); group.group.forEach(iceGroup => { let groupMonitors = this.getMonitorsByGroup(iceGroup); groupMonitors.forEach(groupMonitor => { monitors.push(groupMonitor); }); }); return monitors; } convertICEGroup(iceGroup) { var subGroups = new Array(); iceGroup.group.forEach(subGroupElement => { const subGroup = this.convertICEGroup(subGroupElement); subGroups.push(subGroup); }); var subUsers = new Array(); iceGroup.user.forEach(subUserElement => { let subUser = new UserInternal(); subUser.id = subUserElement.userid; subUser.name = subUserElement.username; subUser.number = subUserElement.userid; let userType = iceAPI.getUserTypeByIceCode(subUserElement.type); subUser.type = userType; let regState = exports.RegistState.Unregisted; switch (subUserElement.rstate) { case Dispatcher.RegisterState.RegisterStateLogin: regState = exports.RegistState.Registed; break; case Dispatcher.RegisterState.RegisterStateLogout: regState = exports.RegistState.Unregisted; break; default: break; } let alwaysOnline = iceAPI.isAlwaysOnlineByICeUserType(subUserElement.type); if (alwaysOnline) { regState = exports.RegistState.Registed; } subUser.state.registState = regState; subUser.state.callState.otherNumber = subUserElement.othernumber; subUser.state.callState.otherName = subUserElement.othername; subUser.state.callState.number = subUserElement.username; subUser.state.callState.state = iceAPI.convertIceCallState(subUserElement.cstate.value.toString()); // subUser.state = userState; // const subUser: User = { // id: subUserElement.userid, name: subUserElement.username, // number: subUserElement.othernumber, registState: subUserElement.rstate.value // }; subUsers.push(subUser); this._logger.log(subUser.number); }); let groupType = GroupType.Normal; if (iceGroup.type == Dispatcher.GroupType.GroupTypeIntercomgroup) { groupType = GroupType.PTT; } const group = { id: iceGroup.id.toString(), name: iceGroup.groupname, groupNumber: iceGroup.groupnum, level: iceGroup.level, type: groupType, subGroups: subGroups, subUser: subUsers }; this._logger.log(group.name); return group; } static getUserTypeByIceCode(iceUserType) { let userType = UserType.Other; // userType = subUserElement.type; switch (iceUserType) { case 0: userType = UserType.Dispatcher; break; case 1: // userType = UserType.handHeld; break; case 2: userType = UserType.SIP; break; case 3: // userType = UserType.OutLine; break; case 7: userType = UserType.Monitor; break; case 5: // userType = UserType.Phone; break; case 6: userType = UserType.APP; break; case 8: // userType = UserType.None; break; case 110: userType = UserType.OutlineMonitorPhone; break; case 111: userType = UserType.OutlineTelePhone; break; case 20: userType = UserType.TianTong; break; case 9: userType = UserType.Device323; break; case 17: userType = UserType.Wade; break; case 10: userType = UserType.StationGroup; break; case 14: userType = UserType.RelayGateway; break; case 18: userType = UserType.OutlineCar; break; case 21: userType = UserType.MeshDevice; break; default: break; } return userType; } static isAlwaysOnlineByICeUserType(iceUserType) { let alwaysOnline = false; if (iceUserType >= 100) { alwaysOnline = true; } let userType = iceAPI.getUserTypeByIceCode(iceUserType); switch (userType) { // case UserType.MonitorDevice: // case UserType.VideoMeetingDevice: // case UserType.OutLine: // case UserType.Outline3ghandheld: // case UserType.OutlineCommonUser: // case UserType.OutlineDispatch: // case UserType.OutlineHandHeld: // case UserType.OutlineMonitorDevice: case UserType.OutlineMonitorPhone: // case UserType.OutlineMonitorUser: case UserType.OutlineTelePhone: // case UserType.NarrowIntercom: case UserType.Wade: case UserType.StationGroup: // case UserType.StationUser: case UserType.Device323: case UserType.RelayGateway: case UserType.Monitor: alwaysOnline = true; break; } return alwaysOnline; } convertICE28281Group(iceGroup) { var subGroups = new Array(); iceGroup.Orgs.forEach(subGroupElement => { const subGroup = this.convertICE28281Group(subGroupElement); subGroups.push(subGroup); }); var subUsers = new Array(); const group = { id: iceGroup.id.toString(), name: iceGroup.name, subGroups: subGroups }; return group; } makecall(calleeStr, isVideo, callType = 0) { return this.makecall1(LoginInfo.getInstance().currentNumber, calleeStr, isVideo, callType); } makecallByLeftPhone(calleeStr, isVideo) { return this.makecall1(LoginInfo.getInstance().leftPhone, calleeStr, isVideo); } makecallByRightPhone(calleeStr, isVideo) { return this.makecall1(LoginInfo.getInstance().rightPhone, calleeStr, isVideo); } makecall1(caller, calleeStr, isVideo, callType = 0) { // try { return navigator.mediaDevices.enumerateDevices().then((devices) => { let videoDeviceName = ""; devices.forEach(element => { if (element.kind == "videoinput") { videoDeviceName = element.label; } }); const info = new Dispatcher.CreateConfT(); info.caller = caller; const callee = new Dispatcher.CalleeT(calleeStr); const callees = new Array(); info.member = callees; info.member.push(callee); info.ctype = Dispatcher.CallType.CallTypeSingle2; if (isVideo) { info.isVideo = Dispatcher.MediaType.MediaTypeVideo; } else { info.isVideo = Dispatcher.MediaType.MediaTypeAudio; } return this._dispatcherPrx.IFCReqCreateConf(this._myid, info).then((result) => { this._logger.log("IFCReqCreateConf: " + JSON.stringify(result)); return Promise.resolve(result.cid); }).catch((reason) => { return Promise.reject(reason); }); } // catch (ex) { // // $("#output").val(ex.toString()); // this._logger.log(ex); // } // finally { // // setState(State.Idle); // } ); } // createConference(calleds: Array, isVideo: boolean) { // } createConference(calleds, isVideo, caller = this._caller) { const info = new Dispatcher.CreateConfT(); info.caller = caller; const callees = new Array(); calleds.forEach(element => { const callee = new Dispatcher.CalleeT(element); callees.push(callee); }); info.member = callees; info.ctype = Dispatcher.CallType.CallTypeTemporary; if (isVideo) { info.isVideo = Dispatcher.MediaType.MediaTypeVideo; } else { info.isVideo = Dispatcher.MediaType.MediaTypeAudio; } info.sessname = "MT" + Date.parse(new Date().toString()); info.sessnum = this._caller + Date.parse(new Date().toString()); return this._dispatcherPrx.IFCReqCreateConf(this._myid, info); } startTempIntercom(calleds, caller = this._caller) { const info = new Dispatcher.CreateConfT(); info.caller = caller; const callees = new Array(); calleds.forEach(element => { const callee = new Dispatcher.CalleeT(element); callees.push(callee); }); info.member = callees; info.ctype = Dispatcher.CallType.CallTypeTmpintercom; info.isVideo = Dispatcher.MediaType.MediaTypeAudio; info.sessname = "tmpIntercom" + Date.parse(new Date().toString()); info.sessnum = this._caller + Date.parse(new Date().toString()); return this._dispatcherPrx.IFCReqCreateConf(this._myid, info); } startBroadcast(calleds, caller = this._caller) { const info = new Dispatcher.CreateConfT(); info.caller = caller; const callees = new Array(); calleds.forEach(element => { const callee = new Dispatcher.CalleeT(element); callees.push(callee); }); info.member = callees; info.ctype = Dispatcher.CallType.CallTypeBroadcast; // info.isVideo = Dispatcher.MediaType.MediaTypeAudio; info.sessname = "broadcast" + Date.parse(new Date().toString()); info.sessnum = this._caller + Date.parse(new Date().toString()); return this._dispatcherPrx.IFCReqCreateConf(this._myid, info); } applySpeak(groupNumber, caller = this._caller) { const info = new Dispatcher.PttReqRightT(); info.caller = caller; info.groupnum = groupNumber; info.messageinfo = "req:ptt_request_speak_right"; return this._dispatcherPrx.IFCReqApplyRight(this._myid, info); } releaseSpeak(groupnum) { const info = new Dispatcher.PttReqRightT(); info.caller = this._caller; info.groupnum = groupnum; info.messageinfo = "req:ptt_cancle_speak_right"; return this._dispatcherPrx.IFCReqApplyRight(this._myid, info); } conferenceAddMember(cid, member) { try { const info = new Dispatcher.AddMemberT(); info.cid = cid; info.number = member; info.astype = Dispatcher.AnswerType.AnswerTypeMan; return this._dispatcherPrx.IFCReqAddMember(this._myid, info); } catch (ex) { // $("#output").val(ex.toString()); this._logger.log(ex); } finally { // setState(State.Idle); } } async conferenceDeleteMember(cid, member) { try { const info = new Dispatcher.DelMemberT(); info.cid = cid; info.number = member; await this._dispatcherPrx.IFCReqDelMember(this._myid, info); } catch (ex) { // $("#output").val(ex.toString()); this._logger.log(ex); } finally { // setState(State.Idle); } } endConference(cid) { const info = new Dispatcher.ForceEndConfeT(); info.cid = cid; return this._dispatcherPrx.IFCReqEndConf(this._myid, info); } conferenceGetVideo(cid, member) { try { // const info: Dispatcher.ForceEndConfeT = new Dispatcher.ForceEndConfeT(); // info.cid = cid; let jsonStr = '{"sid":"bob","cid":"' + cid + '","recv_id":"' + this._caller + '","ip":"","port":"","source_id":"' + member + '","codec":"","stream":"","framerate":"","agentid":"' + this._caller + '"}'; return this._dispatcherPrx.IFCReqWebrtcGetVideo(this._myid, jsonStr); } catch (ex) { // $("#output").val(ex.toString()); this._logger.log(ex.toString()); } finally { // setState(State.Idle); } } conferenceGetVideoMCU(cid, member) { try { // const info: Dispatcher.ForceEndConfeT = new Dispatcher.ForceEndConfeT(); // info.cid = cid; let jsonStr = '{"sid":"bob","cid":"' + cid + '","recv_id":"' + this._caller + '","ip":"","port":"","source_id":"' + member + '","codec":"","stream":"","framerate":"","agentid":"' + this._caller + '","single_video":"1"}'; return this._dispatcherPrx.IFCReqWebrtcGetVideo(this._myid, jsonStr); } catch (ex) { // $("#output").val(ex.toString()); this._logger.log(ex.toString()); } finally { // setState(State.Idle); } } conferencePushMember(cid, member) { const info = new Dispatcher.PushVideoT(); info.cid = cid; info.employeeid = member; info.IsPush = Dispatcher.PushVideoType.PushVideoTypePush; // Dispatcher::Callback_CallingVOP_IFCReqPushVideoPtr d = Dispatcher::newCallback_CallingVOP_IFCReqPushVideo(cb, &IceCallBack::opPushVideo, &IceCallBack::ice_exception); return this._dispatcherPrx.IFCReqPushVideo(this._myid, info); } startAttended(number) { // let info = new Dispatcher.SetNightServiceT(); // info.nightnumber = number; // info.starttime = ""; // info.endtime = ""; let para = { nightnumber: number, starttime: "", endtime: "" }; return this._dispatcherPrx.IFCReqSetNightServiceByJson(this._myid, JSON.stringify(para)); } getUnattendedState() { // let info = new Dispatcher.GetNightServiceT(); // return this._dispatcherPrx.IFCReqSetNightServiceByJson(this._myid, JSON.stringify(para) ); let para = { number: LoginInfo.getInstance().number }; return this._dispatcherPrx.IFCReqGetUserDetailByJson(this._myid, JSON.stringify(para)).then((result) => { let obj = JSON.parse(result); // let key = "nightnumber"; // let nightNumber = result.substring(result.indexOf(key)+ key.length, result.length) // this._logger.warn(nightNumber) let nightNumber = obj.nightnumber; return Promise.resolve(nightNumber); }).catch((reason) => { if (reason == null) { reason = { error: "unkown" }; } return Promise.reject(reason); }); } bindPhoneHandle(leftPhoneNumber, rightPhoneNumber) { // this._leftPhone = leftPhoneNumber; // this._rightPhone = rightPhoneNumber; let infos = new Array(); let info = new Dispatcher.BindTerminalT(); info.number = this._caller; infos.push(info); let infoleft = new Dispatcher.BindTerminalT(); infoleft.number = leftPhoneNumber; infos.push(infoleft); let infoRight = new Dispatcher.BindTerminalT(); infoRight.number = rightPhoneNumber; infos.push(infoRight); return this._dispatcherPrx.IFCReqBindNumber(this._myid, infos); } switch (cid, number, otherNumber) { let info = new Dispatcher.CallCommonT(); info.cid = cid; info.caller = number; info.called = otherNumber; return this._dispatcherPrx.IFCReqCallTransfer(this._myid, info); } SubsituteCall(dstNumber, cid) { let info = new Dispatcher.CallCommonT(); info.cid = cid; info.caller = this._caller; info.called = dstNumber; return this._dispatcherPrx.IFCReqCallPickup(this._myid, info); } transferVideo(cid, caller, calleds) { let info = new Dispatcher.TransferVideoT(); info.srccid = cid; info.srcnumber = caller; let calledsObj = new Array(); calleds.forEach(element => { let calledObj = new Dispatcher.OrderCalledT(); calledObj.called = element; let detail = new Dispatcher.OrderDetailT(); detail.number = element; detail.index = 1; detail.ringtime = 30; calledObj.details = new Array(); calledObj.details.push(detail); calledsObj.push(calledObj); }); info.calleds = calledsObj; return this._dispatcherPrx.IFCReqTransferVideo(this._myid, info); } getUserDetail() { let para = new Dispatcher.TerminalDetailT(this._caller); return this._dispatcherPrx.IFCReqGetUserDetail(this._myid, para); } getUserDetailByNumber(number) { let para = new Dispatcher.TerminalDetailT(number); return this._dispatcherPrx.IFCReqGetUserDetail(this._myid, para); } getUserDetailByNumber1(number) { // let para = new Dispatcher.TerminalDetailT(number); let para = { number: number }; return this._dispatcherPrx.IFCReqGetUserDetailByJson(this._myid, JSON.stringify(para)); } getConfMembers(cid) { let info = new Dispatcher.AllCallMemberT(); info.cid = cid; return this._dispatcherPrx.IFCReqGetAllMember1(this._myid, info); } forceInterposeCall(cid, dstNumber) { let info = new Dispatcher.CallCommonT(); info.called = dstNumber; info.caller = LoginInfo.getInstance().currentNumber; info.cid = cid; return this._dispatcherPrx.IFCReqForceInsert(this._myid, info); } forceRemoveOther(cid, dstNumber) { let info = new Dispatcher.CallCommonT(); info.called = dstNumber; info.caller = LoginInfo.getInstance().currentNumber; info.cid = cid; return this._dispatcherPrx.IFCReqForceDemolition(this._myid, info); } forceRemoveCall(cid, dstNumber) { let info = new Dispatcher.CallCommonT(); info.called = dstNumber; info.caller = this._caller; info.cid = cid; return this._dispatcherPrx.IFCReqForceBreak(this._myid, info); } MonitorCall(cid, dstNumber) { let info = new Dispatcher.CallCommonT(); info.called = dstNumber; // info.called = "3007"; info.caller = this._caller; info.cid = cid; return this._dispatcherPrx.IFCReqMonitor(this._myid, info); } GetUserSessions(number) { let info = new Dispatcher.GetAllSession1T(); info.employeeid = number; info.cType = Dispatcher.CallType.CallTypeNone; return this._dispatcherPrx.IFCReqGetAllSessions2(this._myid, info); } allowSpeak(cid, number, allow) { let info = new Dispatcher.SpeakerT(); info.employeeid = number; info.cid = cid; let type = Dispatcher.SpeakType.SpeakTypeUnmute; if (allow) { type = Dispatcher.SpeakType.SpeakTypeUnmute; } else { type = Dispatcher.SpeakType.SpeakTypeMute; } info.speakertypea = type; return this._dispatcherPrx.IFCReqForbiddenTalk(this._myid, info); } allowListen(cid, number, allow) { let info = new Dispatcher.HearT(); info.number = number; info.cid = cid; let type = Dispatcher.HearType.HearTypeUnmute; if (allow) { type = Dispatcher.HearType.HearTypeUnmute; } else { type = Dispatcher.HearType.HearTypeMute; } info.hear = type; return this._dispatcherPrx.IFCReqForbiddenHear(this._myid, info); } muteLocalMic(sessionId, number, mute) { const info = new Dispatcher.MuteLocalTrackT(); info.cid = sessionId; info.number = number; info.mute = mute; return this._dispatcherPrx.IFCReqMuteLocalMic(this._myid, info); } muteLocalCamera(sessionId, number, mute) { const info = new Dispatcher.MuteLocalTrackT(); info.cid = sessionId; info.number = number; info.mute = mute; return this._dispatcherPrx.IFCReqMuteLocalCamera(this._myid, info); } hold(cid) { // let info = new Dispatcher.HoldT(); // info.cid = cid; // if (hold) { // info.htype = Dispatcher.HoldType.HoldTypeHold; // } else { // info.htype = Dispatcher.HoldType.HoldTypeUnhold; // } // return this._dispatcherPrx.IFCReqHold(this._myid, info); let info = new Dispatcher.PushCallToQueueT(); info.cid = cid; // if (hold) { // info.htype = Dispatcher.HoldType.HoldTypeHold; // } else { // info.htype = Dispatcher.HoldType.HoldTypeUnhold; // } return this._dispatcherPrx.IFCReqPushCallToQueue(this._myid, info); } unHold(cid) { // let info = new Dispatcher.HoldT(); // info.cid = cid; // if (hold) { // info.htype = Dispatcher.HoldType.HoldTypeHold; // } else { // info.htype = Dispatcher.HoldType.HoldTypeUnhold; // } // return this._dispatcherPrx.IFCReqHold(this._myid, info); let info = new Dispatcher.PullQueueCallT(); info.cid = cid; info.caller = this._caller; // if (hold) { // info.htype = Dispatcher.HoldType.HoldTypeHold; // } else { // info.htype = Dispatcher.HoldType.HoldTypeUnhold; // } return this._dispatcherPrx.IFCReqPullCallFromQueue(this._myid, info); } PTZMoveY(number, step, isStart, timeout) { return this.PTZMove(number, Dispatcher.VideoControlType.VideoControlTypeY, step, isStart, timeout); } PTZMoveX(number, step, isStart, timeout) { return this.PTZMove(number, Dispatcher.VideoControlType.VideoControlTypeX, step, isStart, timeout); } PTZZoom(number, step, isStart, timeout) { return this.PTZMove(number, Dispatcher.VideoControlType.VideoControlTypeZoom, step, isStart, timeout); } PTZMoveLR(number, step, isStart, timeout) { return this.PTZMove(number, Dispatcher.VideoControlType.VideoControlTypeLR, step, isStart, timeout); } PTZFocus(number, step, isStart, timeout) { return this.PTZMove(number, Dispatcher.VideoControlType.VideoControlTypeFocus, step, isStart, timeout); } PTZMove(number, type, step, isStart, timeout) { let info = new Dispatcher.CameraNumberControl(); info.number = number; info.TimeOut = timeout; info.IsStart = isStart; info.step = step; info.ctype = type; return this._dispatcherPrx.IFCReqCameraControlByNumber(this._myid, info); } SipPhoneVideoBug(number, isPreCamera, isAutoAnswer) { let info = new Dispatcher.SipPhoneVideoBugT(); info.called = number; info.caller = this._caller; let codec = "*7*"; if (isPreCamera) { codec += "1"; } else { codec += "2"; } codec += "0"; if (isAutoAnswer) { codec += "1"; } else { codec += "2"; } info.codec = codec; return this._dispatcherPrx.IFCReqPhoneVideoBug(this._myid, info); } getDecoderDevices() { return this._dispatcherPrx.IFCReqGetDecoderDevice(this._myid); } getDecoderDeviceConfig(decoderId) { let info = new Dispatcher.GetDisplayCfg(); info.Decoderid = decoderId; return this._dispatcherPrx.IFCReqGetDisplayConfig2(this._myid, info); } getDecoderChannelState(decoderId, channel) { let info = new Dispatcher.opChannelStatus(); info.Decoderid = decoderId; info.Channel = channel; return this._dispatcherPrx.IFCReqGetChannelDecodeState(this._myid, info); } /** * * @param decoderId * @param windows "[{ \"WindowNO\": \"16777217\", \"LayerIndex\": \"67108865\", \"Enable\": \"1\", \"WinMode\": \"" + winMode + "\", \"OperateMode\": \"1\", \"x\": \"1920\", \"y\": \"1920\", \"w\": \"1920\", \"h\": \"1920\" }]"; */ setDecoderWindows(decoderId, windows) { return this._dispatcherPrx.IFCReqSetWindows(this._myid, decoderId, windows); } startDecoderWall(decoderId, channel, cid, number) { let info = new Dispatcher.opDecoderInfo(); info.Decoderid = decoderId; info.Channel = channel; info.disNumber = number; info.cid = cid; return this._dispatcherPrx.IFCReqStartDecode(this._myid, info); } stopDecoderWall(decoderId, channel) { let info = new Dispatcher.opDecoderByVideoInfo(); info.Decoderid = decoderId; info.Channel = channel; info.VideoChannel = ""; info.VideoIP = ""; info.VideoPort = "1"; info.VideoPwd = ""; info.VideoType = Dispatcher.emVideoDeviceType.VDTDHIPC; info.VideoUser = ""; return this._dispatcherPrx.IFCReqStopDecodeByVideoInfo(this._myid, info); } uploadGISInfo(latitude, longitude, grmc) { let info = new Dispatcher.GisInfoT(); info.latitude = latitude; info.longitude = longitude; info.grmc = grmc; info.time = ""; return this._dispatcherPrx.IFCReqReportGisInfo(this._myid, info); } setGisTrace(numbers) { const infos = new Array(); numbers.forEach(element => { const info = new Dispatcher.GisTraceT(); info.dstid = element; info.space = ""; info.flag = Dispatcher.GisTraceType.GisTraceTypeSub; infos.push(info); }); return this._dispatcherPrx.IFCReqTraceGisInfo(this._myid, infos); } cancelGisTrace(numbers) { const infos = new Array(); numbers.forEach(element => { const info = new Dispatcher.GisTraceT(); info.dstid = element; info.space = ""; info.flag = Dispatcher.GisTraceType.GisTraceTypeUnsub; infos.push(info); }); return this._dispatcherPrx.IFCReqTraceGisInfo(this._myid, infos); } getGisHistory(number, beginTime, endTime) { const info = new Dispatcher.GisInfoByTimeT(); info.employeeid = number; info.begin = beginTime; info.end = endTime; info.type = 0; return this._dispatcherPrx.IFCReqGetGisInfoByTime2(this._myid, info); } getGisHistoryPage(number, beginTime, endTime, pagesize, pageindex) { let info = { employeeid: number, begin: beginTime, end: endTime, type: 0, pagesize: pagesize, pageindex: pageindex }; return this._dispatcherPrx.IFCReqGetGisInfoByTimeByJson2(this._myid, JSON.stringify(info)); } getGisInfoByRectangle(longmin, longmax, latmin, latmax, types) { const info = new Dispatcher.GisInfoByRectangleT(); info.a = longmin; info.b = longmax; info.c = latmin; info.d = latmax; info.type = types; return this._dispatcherPrx.IFCReqGetGisInfoByRectangle2(this._myid, info); } getGisInfoByEllipse(longmin, longmax, latmin, latmax, types) { const info = new Dispatcher.GisInfoByEllipseT(); info.a = longmin; info.b = longmax; info.c = latmin; info.d = latmax; info.type = types; return this._dispatcherPrx.IFCReqGetGisInfoByEllipse2(this._myid, info); } getGisPosition(numbers) { const info = new Dispatcher.GetPositionT1(); info.employeeid = numbers; return this._dispatcherPrx.IFCReqGetGisInfoByJson(this._myid, info).then((str) => { let obj = JSON.parse(str); let alwaysOnline = iceAPI.isAlwaysOnlineByICeUserType(obj[0].type); if (alwaysOnline) { obj[0].regstate = 1; } return Promise.resolve(JSON.stringify(obj)); }).catch((reason) => { return Promise.reject(reason); }); } SendMsg(msg, receives) { try { const info = new Dispatcher.MessageT(); info.message.body = msg; info.receiver = new Array(); receives.forEach(element => { info.receiver.push(element); }); return this._dispatcherPrx.IFCReqMsg(this._myid, info); } catch (ex) { // DisConnect(); this._logger.log("IceConn error:" + ex); return Promise.reject(ex); } } getOfflineMsg(getNumber) { const info = new Dispatcher.GetOldMsgFileT(); info.getnum = getNumber; info.employeeid = this._caller; return this._dispatcherPrx.IFCReqGetOldMsgFile(this._myid, info); } SetFileRecieved(fileId, number) { const info = new Dispatcher.FileReceivedT(); info.fid = fileId; info.employeeid = number; return this._dispatcherPrx.IFCReqFileReceived(this._myid, info); } SetMessageRecevied(msgId, number) { const info = new Dispatcher.MessageReceivedT(); info.msgid = msgId; info.employeeid = number; return this._dispatcherPrx.IFCReqMsgReceived(this._myid, info); } SetUploadFileResult(fileId, uploadState) { const info = new Dispatcher.UploadEventT(); info.fid = fileId; info.state = Dispatcher.FileState.valueOf(uploadState); return this._dispatcherPrx.IFCNotifyUploadFileEvt(this._myid, info); } ApplyUploadFile(fileName, receivers, fileType) { const info = new Dispatcher.ApplyUploadT(); info.file.fname = fileName; info.file.ftype = Dispatcher.FileType.valueOf(fileType); info.recv = receivers; return this._dispatcherPrx.IFCReqapPlayUploadFile(this._myid, info); } getPlanInfo() { return this._dispatcherPrx.IFCReqSelectPreplan2(this._myid, ""); } startPlan(planId) { const info = new Dispatcher.PrePlanStartT(); info.planId = planId; info.caller = LoginInfo.getInstance().number; return this._dispatcherPrx.IFCReqStartPreplan(this._myid, info); } createShecduleConf(calleds, isVideo, startTime, name) { let mediaType = 1; if (isVideo) { mediaType = 2; } let membersStr = ""; calleds.forEach(element => { if (membersStr != "") { membersStr += ","; } membersStr += element; }); let para = { meeting_name: name, cid: "", media_type: mediaType, start_time: this.dateFormat(startTime, "yyyy-MM-dd hh:mm:ss"), call_type: 5, dnsprefix: "", members: membersStr }; let jsonPara = JSON.stringify(para); this._logger.warn("schedule members: " + jsonPara); return this._dispatcherPrx.IFCReqCreateScheduleConf(this._myid, jsonPara); } fixScheduleConf(cid, calleds, isVideo, startTime, name) { let mediaType = 1; if (isVideo) { mediaType = 2; } let membersStr = ""; calleds.forEach(element => { if (membersStr != "") { membersStr += ","; } membersStr += element; }); let para = { meeting_name: name, cid: cid, media_type: mediaType, start_time: this.dateFormat(startTime, "yyyy-MM-dd hh:mm:ss"), call_type: 5, dnsprefix: "", members: membersStr }; let jsonPara = JSON.stringify(para); this._logger.warn("schedule members: " + jsonPara); return this._dispatcherPrx.IFCReqFixScheduleConf(this._myid, jsonPara); } getScheduleConf() { let info = { employeeID: LoginInfo.getInstance().number }; return this._dispatcherPrx.IFCReqGetScheduleConf(this._myid, JSON.stringify(info)); } deleteScheduleConf(sessionId) { let info = { cid: sessionId }; return this._dispatcherPrx.IFCReqDeleteScheduleConf(this._myid, JSON.stringify(info)); } /** * 对日期进行格式化, 和C#大致一致 默认yyyy-MM-dd HH:mm:ss * 可不带参数 一个日期参数 或一个格式化参数 * @param date 要格式化的日期 * @param format 进行格式化的模式字符串 * 支持的模式字母有: * y:年, * M:年中的月份(1-12), * d:月份中的天(1-31), * H:小时(0-23), * h:小时(0-11), * m:分(0-59), * s:秒(0-59), * f:毫秒(0-999), * q:季度(1-4) * @return String * @author adswads@gmail.com */ dateFormat(date, format) { //无参数 if (date == undefined && format == undefined) { date = new Date(); format = "yyyy-MM-dd HH:mm:ss"; } //无日期 else if (typeof(date) == "string") { format = date; date = new Date(); } //无格式化参数 else if (format === undefined) { format = "yyyy-MM-dd HH:mm:ss"; } //没有分隔符的特殊处理 var map = { "y": date.getFullYear() + "", "M": date.getMonth() + 1 + "", "d": date.getDate() + "", "H": date.getHours(), "m": date.getMinutes() + "", "s": date.getSeconds() + "", "q": Math.floor((date.getMonth() + 3) / 3) + "", "f": date.getMilliseconds() + "" //毫秒 }; //小时 12 // if (map["H"] > 12) { map["h"] = map["H"] - 12 + ""; } // else { map["h"] = map["H"] + ""; } // map["H"] += ""; map["h"] = map["H"] + ""; map["H"] += ""; var reg = "yMdHhmsqf"; var all = "", str = ""; for (var i = 0, n = 0; i < reg.length; i++) { n = format.indexOf(reg[i]); if (n < 0) { continue; } all = ""; for (; n < format.length; n++) { if (format[n] != reg[i]) { break; } all += reg[i]; } if (all.length > 0) { if (all.length == map[reg[i]].length) { str = map[reg[i]]; } else if (all.length > map[reg[i]].length) { if (reg[i] == "f") { str = map[reg[i]] + this.charString("0", all.length - map[reg[i]].length); } else { str = this.charString("0", all.length - map[reg[i]].length) + map[reg[i]]; } } else { switch (reg[i]) { case "y": str = map[reg[i]].substr(map[reg[i]].length - all.length); break; case "f": str = map[reg[i]].substr(0, all.length); break; default: str = map[reg[i]]; break; } } format = format.replace(all, str); } } return format; } /** * 返回字符串 为n个char构成 * @param char 重复的字符 * @param count 次数 * @return String * @author adswads@gmail.com */ charString(char, count) { var str = ""; while (count--) { str += char; } return str; } hangup(cid, member = LoginInfo.getInstance().currentNumber) { const info = new Dispatcher.HangupT(); info.cid = cid; // info.member = member; return this._dispatcherPrx.IFCReqHangup(this._myid, info); } hangupSession(cid) { const info = new Dispatcher.HangupT(); info.cid = cid; // info.member = LoginInfo.getInstance().currentNumber; return this._dispatcherPrx.IFCReqHangup(this._myid, info); } requestSendVideoByJson(cid) { const info = { cid: cid, sid: "", employeeid: LoginInfo.getInstance().number, ip: "255.255.255.255", port: "", codec: "", stream: "", framerate: "", agentid: "", proto: "sip" }; let para = JSON.stringify(info); this._logger.warn(" requestSendVideoByJson para: " + para); return this._dispatcherPrx.IFCReqSendVideoByJson(this._myid, para).then((result) => { this._logger.warn("IFCReqSendVideoByJson success: " + result); }).catch((reason) => { this._logger.error("IFCReqSendVideoByJson fail: " + JSON.stringify(reason)); }); } getSmsGis(number) { return this._dispatcherPrx.IFCReqGetSmsGis(this._myid, number); } getSmsGisRepeat(number, timers) { return this._dispatcherPrx.IFCReqGetSmsGisRepeat(this._myid, number, timers.toString()); } negotiatedTransfer(sessionId1, sessionId2, member1, member2) { const info = new Dispatcher.NegoTransferT(); info.cid1 = sessionId1; info.cid2 = sessionId2; info.call1 = member1; info.call2 = member2; info.number = LoginInfo.getInstance().currentNumber; return this._dispatcherPrx.IFCReqNegoTransfer(this._myid, info); } getVersion() { const info = new Dispatcher.GetVersionT(); return this._dispatcherPrx.IFCReqGetVersion(this._myid, info); } getCompanyName() { return this._dispatcherPrx.IFCReqGetConfigByKey(this._myid, "CompanyName"); } getKeyframe(sessionId, mebmer) { const info = new Dispatcher.GetKeyFrameT(); info.cid = sessionId; info.employeeid = mebmer; // info.employeeid = "1002"; return this._dispatcherPrx.IFCReqGetKeyFrame(this._myid, info); } getAllRegistedUsers() { return this.getRootGroups().then((groups) => { let groupsStr = ""; let getGroups = (group) => { if (groupsStr == "") { groupsStr = group.groupNumber; } else { groupsStr = groupsStr + "," + group.groupNumber; } if (group.subGroups != null && group.subGroups.length > 0) { group.subGroups.forEach(element => { getGroups(element); }); } }; groups.forEach(element1 => { getGroups(element1); }); return this._dispatcherPrx.IFCReqAllUserRegState(this._myid, groupsStr); }); } getAllRegistedUsersById(ids) { let groupsStr = ""; ids.forEach(id => { if (groupsStr != "") { groupsStr += ","; } groupsStr += id; }); return this._dispatcherPrx.IFCReqAllUserRegState(this._myid, groupsStr); } getLoginState(number) { return this._dispatcherPrx.IFCReqLoginState(this._myid, number); } forceKickOut(employeeId) { let info = new Dispatcher.ForceKickOutT(); info.Employeeid = employeeId; info.LoginUUID = LoginInfo.getInstance().uuid; return this._dispatcherPrx.IFCReqForceLogout(this._myid, info); // let info1 = {pass:"4QrcOUm6Wau+VuBX8g+IPg==",ip:"172.19.2.215",interval:30,type:0,force:1}; // // let info = new Dispatcher.ForceKickOutT(); // // info.Employeeid = employeeId; // return this._dispatcherPrx.IFCReqLoginForce(this._myid, JSON.stringify(info1) ); } startFileBroadcast(fileId, playCount, members) { let membersStr = ""; members.forEach(element => { if (membersStr != "") { membersStr += ","; } membersStr += element; }); let info = { caller: this._username, fid: fileId, playCount: playCount, members: membersStr }; return this._dispatcherPrx.IFCReqCreateFileBroadcastConf(this._myid, JSON.stringify(info)); } getFileBroadcastState(employeeId) { let info = { EmployeeID: employeeId }; return this._dispatcherPrx.IFCReqGetFileBroadcastState(this._myid, JSON.stringify(info)); } PushStartCallAudio(cid, rtspUrl, codec) { let info = { cid: cid, url: rtspUrl, force_acodec: codec }; return this._dispatcherPrx.IFCReqPushStartCallAudio(this._myid, JSON.stringify(info)); } PushStopCallAudio(cid) { let info = { cid: cid }; return this._dispatcherPrx.IFCReqPushStopCallAudio(this._myid, JSON.stringify(info)); } } iceAPI.instance = null; const stripMediaDescription = (sdp, description) => { const descriptionRegExp = new RegExp("m=" + description + ".*$", "gm"); const groupRegExp = new RegExp("^a=group:.*$", "gm"); if (descriptionRegExp.test(sdp)) { let midLineToRemove; sdp = sdp.split(/^m=/gm).filter((section) => { if (section.substr(0, description.length) === description) { midLineToRemove = section.match(/^a=mid:.*$/gm); if (midLineToRemove) { const step = midLineToRemove[0].match(/:.+$/g); if (step) { midLineToRemove = step[0].substr(1); } } return false; } return true; }).join("m="); const groupLine = sdp.match(groupRegExp); if (groupLine && groupLine.length === 1) { let groupLinePortion = groupLine[0]; const groupRegExpReplace = new RegExp("\ *" + midLineToRemove + "[^\ ]*", "g"); groupLinePortion = groupLinePortion.replace(groupRegExpReplace, ""); sdp = sdp.split(groupRegExp).join(groupLinePortion); } } return sdp; }; function stripVideo(description) { description.sdp = stripMediaDescription(description.sdp || "", "video"); return Promise.resolve(description); } /** * SIP Methods * @internal */ var C; (function(C) { C.ACK = "ACK"; C.BYE = "BYE"; C.CANCEL = "CANCEL"; C.INFO = "INFO"; C.INVITE = "INVITE"; C.MESSAGE = "MESSAGE"; C.NOTIFY = "NOTIFY"; C.OPTIONS = "OPTIONS"; C.REGISTER = "REGISTER"; C.UPDATE = "UPDATE"; C.SUBSCRIBE = "SUBSCRIBE"; C.PUBLISH = "PUBLISH"; C.REFER = "REFER"; C.PRACK = "PRACK"; })(C || (C = {})); /** * @internal */ class Parameters { constructor(parameters) { this.parameters = {}; for (const param in parameters) { if (parameters.hasOwnProperty(param)) { this.setParam(param, parameters[param]); } } } setParam(key, value) { if (key) { this.parameters[key.toLowerCase()] = (typeof value === "undefined" || value === null) ? null : value.toString(); } } getParam(key) { if (key) { return this.parameters[key.toLowerCase()]; } } hasParam(key) { if (key) { return !!this.parameters.hasOwnProperty(key.toLowerCase()); } return false; } deleteParam(parameter) { parameter = parameter.toLowerCase(); if (this.parameters.hasOwnProperty(parameter)) { const value = this.parameters[parameter]; delete this.parameters[parameter]; return value; } } clearParams() { this.parameters = {}; } } /** * Name Address SIP header. * @public */ class NameAddrHeader extends Parameters { /** * Constructor * @param uri - * @param displayName - * @param parameters - */ constructor(uri, displayName, parameters) { super(parameters); this.uri = uri; this._displayName = displayName; } get friendlyName() { return this.displayName || this.uri.aor; } get displayName() { return this._displayName; } set displayName(value) { this._displayName = value; } clone() { return new NameAddrHeader(this.uri.clone(), this._displayName, JSON.parse(JSON.stringify(this.parameters))); } toString() { let body = (this.displayName || this.displayName === "0") ? '"' + this.displayName + '" ' : ""; body += "<" + this.uri.toString() + ">"; for (const parameter in this.parameters) { if (this.parameters.hasOwnProperty(parameter)) { body += ";" + parameter; if (this.parameters[parameter] !== null) { body += "=" + this.parameters[parameter]; } } } return body; } } /** * URI. * @public */ class URI extends Parameters { /** * Constructor * @param scheme - * @param user - * @param host - * @param port - * @param parameters - * @param headers - */ constructor(scheme, user, host, port, parameters, headers) { super(parameters); this.headers = {}; // Checks if (!host) { throw new TypeError('missing or invalid "host" parameter'); } // Initialize parameters scheme = scheme || "sip"; for (const header in headers) { if (headers.hasOwnProperty(header)) { this.setHeader(header, headers[header]); } } // Raw URI this.raw = { scheme, user, host, port }; // Normalized URI this.normal = { scheme: scheme.toLowerCase(), user, host: host.toLowerCase(), port }; } get scheme() { return this.normal.scheme; } set scheme(value) { this.raw.scheme = value; this.normal.scheme = value.toLowerCase(); } get user() { return this.normal.user; } set user(value) { this.normal.user = this.raw.user = value; } get host() { return this.normal.host; } set host(value) { this.raw.host = value; this.normal.host = value.toLowerCase(); } get aor() { return this.normal.user + "@" + this.normal.host; } get port() { return this.normal.port; } set port(value) { this.normal.port = this.raw.port = value === 0 ? value : value; } setHeader(name, value) { this.headers[this.headerize(name)] = (value instanceof Array) ? value : [value]; } getHeader(name) { if (name) { return this.headers[this.headerize(name)]; } } hasHeader(name) { return !!name && !!this.headers.hasOwnProperty(this.headerize(name)); } deleteHeader(header) { header = this.headerize(header); if (this.headers.hasOwnProperty(header)) { const value = this.headers[header]; delete this.headers[header]; return value; } } clearHeaders() { this.headers = {}; } clone() { return new URI(this._raw.scheme, this._raw.user || "", this._raw.host, this._raw.port, JSON.parse(JSON.stringify(this.parameters)), JSON.parse(JSON.stringify(this.headers))); } toRaw() { return this._toString(this._raw); } toString() { return this._toString(this._normal); } get _normal() { return this.normal; } get _raw() { return this.raw; } _toString(uri) { let uriString = uri.scheme + ":"; // add slashes if it's not a sip(s) URI if (!uri.scheme.toLowerCase().match("^sips?$")) { uriString += "//"; } if (uri.user) { uriString += this.escapeUser(uri.user) + "@"; } uriString += uri.host; if (uri.port || uri.port === 0) { uriString += ":" + uri.port; } for (const parameter in this.parameters) { if (this.parameters.hasOwnProperty(parameter)) { uriString += ";" + parameter; if (this.parameters[parameter] !== null) { uriString += "=" + this.parameters[parameter]; } } } const headers = []; for (const header in this.headers) { if (this.headers.hasOwnProperty(header)) { for (const idx in this.headers[header]) { if (this.headers[header].hasOwnProperty(idx)) { headers.push(header + "=" + this.headers[header][idx]); } } } } if (headers.length > 0) { uriString += "?" + headers.join("&"); } return uriString; } /* * Hex-escape a SIP URI user. * @private * @param {String} user */ escapeUser(user) { let decodedUser; // FIXME: This is called by toString above which should never throw, but // decodeURIComponent can throw and I've seen one case in production where // it did throw resulting in a cascading failure. This class should be // fixed so that decodeURIComponent is not called at this point (in toString). // The user should be decoded when the URI is constructor or some other // place where we can catch the error before the URI is created or somesuch. try { decodedUser = decodeURIComponent(user); } catch (error) { throw error; } // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). return encodeURIComponent(decodedUser) .replace(/%3A/ig, ":") .replace(/%2B/ig, "+") .replace(/%3F/ig, "?") .replace(/%2F/ig, "/"); } headerize(str) { const exceptions = { "Call-Id": "Call-ID", "Cseq": "CSeq", "Min-Se": "Min-SE", "Rack": "RAck", "Rseq": "RSeq", "Www-Authenticate": "WWW-Authenticate", }; const name = str.toLowerCase().replace(/_/g, "-").split("-"); const parts = name.length; let hname = ""; for (let part = 0; part < parts; part++) { if (part !== 0) { hname += "-"; } hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); } if (exceptions[hname]) { hname = exceptions[hname]; } return hname; } } // tslint:disable:interface-name class SyntaxError extends Error { constructor(message, expected, found, location) { super(); this.message = message; this.expected = expected; this.found = found; this.location = location; this.name = "SyntaxError"; if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, SyntaxError); } } static buildMessage(expected, found) { function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } function literalEscape(s) { return s .replace(/\\/g, "\\\\") .replace(/"/g, "\\\"") .replace(/\0/g, "\\0") .replace(/\t/g, "\\t") .replace(/\n/g, "\\n") .replace(/\r/g, "\\r") .replace(/[\x00-\x0F]/g, (ch) => "\\x0" + hex(ch)) .replace(/[\x10-\x1F\x7F-\x9F]/g, (ch) => "\\x" + hex(ch)); } function classEscape(s) { return s .replace(/\\/g, "\\\\") .replace(/\]/g, "\\]") .replace(/\^/g, "\\^") .replace(/-/g, "\\-") .replace(/\0/g, "\\0") .replace(/\t/g, "\\t") .replace(/\n/g, "\\n") .replace(/\r/g, "\\r") .replace(/[\x00-\x0F]/g, (ch) => "\\x0" + hex(ch)) .replace(/[\x10-\x1F\x7F-\x9F]/g, (ch) => "\\x" + hex(ch)); } function describeExpectation(expectation) { switch (expectation.type) { case "literal": return "\"" + literalEscape(expectation.text) + "\""; case "class": const escapedParts = expectation.parts.map((part) => { return Array.isArray(part) ? classEscape(part[0]) + "-" + classEscape(part[1]) : classEscape(part); }); return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; case "any": return "any character"; case "end": return "end of input"; case "other": return expectation.description; } } function describeExpected(expected1) { const descriptions = expected1.map(describeExpectation); let i; let j; descriptions.sort(); if (descriptions.length > 0) { for (i = 1, j = 1; i < descriptions.length; i++) { if (descriptions[i - 1] !== descriptions[i]) { descriptions[j] = descriptions[i]; j++; } } descriptions.length = j; } switch (descriptions.length) { case 1: return descriptions[0]; case 2: return descriptions[0] + " or " + descriptions[1]; default: return descriptions.slice(0, -1).join(", ") + ", or " + descriptions[descriptions.length - 1]; } } function describeFound(found1) { return found1 ? "\"" + literalEscape(found1) + "\"" : "end of input"; } return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; } } function peg$parse(input, options) { options = options !== undefined ? options : {}; const peg$FAILED = {}; const peg$startRuleIndices = { Contact: 119, Name_Addr_Header: 156, Record_Route: 176, Request_Response: 81, SIP_URI: 45, Subscription_State: 186, Supported: 191, Require: 182, Via: 194, absoluteURI: 84, Call_ID: 118, Content_Disposition: 130, Content_Length: 135, Content_Type: 136, CSeq: 146, displayName: 122, Event: 149, From: 151, host: 52, Max_Forwards: 154, Min_SE: 213, Proxy_Authenticate: 157, quoted_string: 40, Refer_To: 178, Replaces: 179, Session_Expires: 210, stun_URI: 217, To: 192, turn_URI: 223, uuid: 226, WWW_Authenticate: 209, challenge: 158, sipfrag: 230, Referred_By: 231 }; let peg$startRuleIndex = 119; const peg$consts = [ "\r\n", peg$literalExpectation("\r\n", false), /^[0-9]/, peg$classExpectation([ ["0", "9"] ], false, false), /^[a-zA-Z]/, peg$classExpectation([ ["a", "z"], ["A", "Z"] ], false, false), /^[0-9a-fA-F]/, peg$classExpectation([ ["0", "9"], ["a", "f"], ["A", "F"] ], false, false), /^[\0-\xFF]/, peg$classExpectation([ ["\0", "\xFF"] ], false, false), /^["]/, peg$classExpectation(["\""], false, false), " ", peg$literalExpectation(" ", false), "\t", peg$literalExpectation("\t", false), /^[a-zA-Z0-9]/, peg$classExpectation([ ["a", "z"], ["A", "Z"], ["0", "9"] ], false, false), ";", peg$literalExpectation(";", false), "/", peg$literalExpectation("/", false), "?", peg$literalExpectation("?", false), ":", peg$literalExpectation(":", false), "@", peg$literalExpectation("@", false), "&", peg$literalExpectation("&", false), "=", peg$literalExpectation("=", false), "+", peg$literalExpectation("+", false), "$", peg$literalExpectation("$", false), ",", peg$literalExpectation(",", false), "-", peg$literalExpectation("-", false), "_", peg$literalExpectation("_", false), ".", peg$literalExpectation(".", false), "!", peg$literalExpectation("!", false), "~", peg$literalExpectation("~", false), "*", peg$literalExpectation("*", false), "'", peg$literalExpectation("'", false), "(", peg$literalExpectation("(", false), ")", peg$literalExpectation(")", false), "%", peg$literalExpectation("%", false), function() { return " "; }, function() { return ':'; }, /^[!-~]/, peg$classExpectation([ ["!", "~"] ], false, false), /^[\x80-\uFFFF]/, peg$classExpectation([ ["\x80", "\uFFFF"] ], false, false), /^[\x80-\xBF]/, peg$classExpectation([ ["\x80", "\xBF"] ], false, false), /^[a-f]/, peg$classExpectation([ ["a", "f"] ], false, false), "`", peg$literalExpectation("`", false), "<", peg$literalExpectation("<", false), ">", peg$literalExpectation(">", false), "\\", peg$literalExpectation("\\", false), "[", peg$literalExpectation("[", false), "]", peg$literalExpectation("]", false), "{", peg$literalExpectation("{", false), "}", peg$literalExpectation("}", false), function() { return "*"; }, function() { return "/"; }, function() { return "="; }, function() { return "("; }, function() { return ")"; }, function() { return ">"; }, function() { return "<"; }, function() { return ","; }, function() { return ";"; }, function() { return ":"; }, function() { return "\""; }, /^[!-']/, peg$classExpectation([ ["!", "'"] ], false, false), /^[*-[]/, peg$classExpectation([ ["*", "["] ], false, false), /^[\]-~]/, peg$classExpectation([ ["]", "~"] ], false, false), function(contents) { return contents; }, /^[#-[]/, peg$classExpectation([ ["#", "["] ], false, false), /^[\0-\t]/, peg$classExpectation([ ["\0", "\t"] ], false, false), /^[\x0B-\f]/, peg$classExpectation([ ["\x0B", "\f"] ], false, false), /^[\x0E-\x7F]/, peg$classExpectation([ ["\x0E", "\x7F"] ], false, false), function() { options = options || { data: {} }; options.data.uri = new URI(options.data.scheme, options.data.user, options.data.host, options.data.port); delete options.data.scheme; delete options.data.user; delete options.data.host; delete options.data.host_type; delete options.data.port; }, function() { options = options || { data: {} }; options.data.uri = new URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); delete options.data.scheme; delete options.data.user; delete options.data.host; delete options.data.host_type; delete options.data.port; delete options.data.uri_params; if (options.startRule === 'SIP_URI') { options.data = options.data.uri; } }, "sips", peg$literalExpectation("sips", true), "sip", peg$literalExpectation("sip", true), function(uri_scheme) { options = options || { data: {} }; options.data.scheme = uri_scheme; }, function() { options = options || { data: {} }; options.data.user = decodeURIComponent(text().slice(0, -1)); }, function() { options = options || { data: {} }; options.data.password = text(); }, function() { options = options || { data: {} }; options.data.host = text(); return options.data.host; }, function() { options = options || { data: {} }; options.data.host_type = 'domain'; return text(); }, /^[a-zA-Z0-9_\-]/, peg$classExpectation([ ["a", "z"], ["A", "Z"], ["0", "9"], "_", "-" ], false, false), /^[a-zA-Z0-9\-]/, peg$classExpectation([ ["a", "z"], ["A", "Z"], ["0", "9"], "-" ], false, false), function() { options = options || { data: {} }; options.data.host_type = 'IPv6'; return text(); }, "::", peg$literalExpectation("::", false), function() { options = options || { data: {} }; options.data.host_type = 'IPv6'; return text(); }, function() { options = options || { data: {} }; options.data.host_type = 'IPv4'; return text(); }, "25", peg$literalExpectation("25", false), /^[0-5]/, peg$classExpectation([ ["0", "5"] ], false, false), "2", peg$literalExpectation("2", false), /^[0-4]/, peg$classExpectation([ ["0", "4"] ], false, false), "1", peg$literalExpectation("1", false), /^[1-9]/, peg$classExpectation([ ["1", "9"] ], false, false), function(port) { options = options || { data: {} }; port = parseInt(port.join('')); options.data.port = port; return port; }, "transport=", peg$literalExpectation("transport=", true), "udp", peg$literalExpectation("udp", true), "tcp", peg$literalExpectation("tcp", true), "sctp", peg$literalExpectation("sctp", true), "tls", peg$literalExpectation("tls", true), function(transport) { options = options || { data: {} }; if (!options.data.uri_params) options.data.uri_params = {}; options.data.uri_params['transport'] = transport.toLowerCase(); }, "user=", peg$literalExpectation("user=", true), "phone", peg$literalExpectation("phone", true), "ip", peg$literalExpectation("ip", true), function(user) { options = options || { data: {} }; if (!options.data.uri_params) options.data.uri_params = {}; options.data.uri_params['user'] = user.toLowerCase(); }, "method=", peg$literalExpectation("method=", true), function(method) { options = options || { data: {} }; if (!options.data.uri_params) options.data.uri_params = {}; options.data.uri_params['method'] = method; }, "ttl=", peg$literalExpectation("ttl=", true), function(ttl) { options = options || { data: {} }; if (!options.data.params) options.data.params = {}; options.data.params['ttl'] = ttl; }, "maddr=", peg$literalExpectation("maddr=", true), function(maddr) { options = options || { data: {} }; if (!options.data.uri_params) options.data.uri_params = {}; options.data.uri_params['maddr'] = maddr; }, "lr", peg$literalExpectation("lr", true), function() { options = options || { data: {} }; if (!options.data.uri_params) options.data.uri_params = {}; options.data.uri_params['lr'] = undefined; }, function(param, value) { options = options || { data: {} }; if (!options.data.uri_params) options.data.uri_params = {}; if (value === null) { value = undefined; } else { value = value[1]; } options.data.uri_params[param.toLowerCase()] = value; }, function(hname, hvalue) { hname = hname.join('').toLowerCase(); hvalue = hvalue.join(''); options = options || { data: {} }; if (!options.data.uri_headers) options.data.uri_headers = {}; if (!options.data.uri_headers[hname]) { options.data.uri_headers[hname] = [hvalue]; } else { options.data.uri_headers[hname].push(hvalue); } }, function() { options = options || { data: {} }; // lots of tests fail if this isn't guarded... if (options.startRule === 'Refer_To') { options.data.uri = new URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); delete options.data.scheme; delete options.data.user; delete options.data.host; delete options.data.host_type; delete options.data.port; delete options.data.uri_params; } }, "//", peg$literalExpectation("//", false), function() { options = options || { data: {} }; options.data.scheme = text(); }, peg$literalExpectation("SIP", true), function() { options = options || { data: {} }; options.data.sip_version = text(); }, "INVITE", peg$literalExpectation("INVITE", false), "ACK", peg$literalExpectation("ACK", false), "VXACH", peg$literalExpectation("VXACH", false), "OPTIONS", peg$literalExpectation("OPTIONS", false), "BYE", peg$literalExpectation("BYE", false), "CANCEL", peg$literalExpectation("CANCEL", false), "REGISTER", peg$literalExpectation("REGISTER", false), "SUBSCRIBE", peg$literalExpectation("SUBSCRIBE", false), "NOTIFY", peg$literalExpectation("NOTIFY", false), "REFER", peg$literalExpectation("REFER", false), "PUBLISH", peg$literalExpectation("PUBLISH", false), function() { options = options || { data: {} }; options.data.method = text(); return options.data.method; }, function(status_code) { options = options || { data: {} }; options.data.status_code = parseInt(status_code.join('')); }, function() { options = options || { data: {} }; options.data.reason_phrase = text(); }, function() { options = options || { data: {} }; options.data = text(); }, function() { var idx, length; options = options || { data: {} }; length = options.data.multi_header.length; for (idx = 0; idx < length; idx++) { if (options.data.multi_header[idx].parsed === null) { options.data = null; break; } } if (options.data !== null) { options.data = options.data.multi_header; } else { options.data = -1; } }, function() { var header; options = options || { data: {} }; if (!options.data.multi_header) options.data.multi_header = []; try { header = new NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); delete options.data.uri; delete options.data.displayName; delete options.data.params; } catch (e) { header = null; } options.data.multi_header.push({ 'position': peg$currPos, 'offset': location().start.offset, 'parsed': header }); }, function(displayName) { displayName = text().trim(); if (displayName[0] === '\"') { displayName = displayName.substring(1, displayName.length - 1); } options = options || { data: {} }; options.data.displayName = displayName; }, "q", peg$literalExpectation("q", true), function(q) { options = options || { data: {} }; if (!options.data.params) options.data.params = {}; options.data.params['q'] = q; }, "expires", peg$literalExpectation("expires", true), function(expires) { options = options || { data: {} }; if (!options.data.params) options.data.params = {}; options.data.params['expires'] = expires; }, function(delta_seconds) { return parseInt(delta_seconds.join('')); }, "0", peg$literalExpectation("0", false), function() { return parseFloat(text()); }, function(param, value) { options = options || { data: {} }; if (!options.data.params) options.data.params = {}; if (value === null) { value = undefined; } else { value = value[1]; } options.data.params[param.toLowerCase()] = value; }, "render", peg$literalExpectation("render", true), "session", peg$literalExpectation("session", true), "icon", peg$literalExpectation("icon", true), "alert", peg$literalExpectation("alert", true), function() { options = options || { data: {} }; if (options.startRule === 'Content_Disposition') { options.data.type = text().toLowerCase(); } }, "handling", peg$literalExpectation("handling", true), "optional", peg$literalExpectation("optional", true), "required", peg$literalExpectation("required", true), function(length) { options = options || { data: {} }; options.data = parseInt(length.join('')); }, function() { options = options || { data: {} }; options.data = text(); }, "text", peg$literalExpectation("text", true), "image", peg$literalExpectation("image", true), "audio", peg$literalExpectation("audio", true), "video", peg$literalExpectation("video", true), "application", peg$literalExpectation("application", true), "message", peg$literalExpectation("message", true), "multipart", peg$literalExpectation("multipart", true), "x-", peg$literalExpectation("x-", true), function(cseq_value) { options = options || { data: {} }; options.data.value = parseInt(cseq_value.join('')); }, function(expires) { options = options || { data: {} }; options.data = expires; }, function(event_type) { options = options || { data: {} }; options.data.event = event_type.toLowerCase(); }, function() { options = options || { data: {} }; var tag = options.data.tag; options.data = new NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); if (tag) { options.data.setParam('tag', tag); } }, "tag", peg$literalExpectation("tag", true), function(tag) { options = options || { data: {} }; options.data.tag = tag; }, function(forwards) { options = options || { data: {} }; options.data = parseInt(forwards.join('')); }, function(min_expires) { options = options || { data: {} }; options.data = min_expires; }, function() { options = options || { data: {} }; options.data = new NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); }, "digest", peg$literalExpectation("Digest", true), "realm", peg$literalExpectation("realm", true), function(realm) { options = options || { data: {} }; options.data.realm = realm; }, "domain", peg$literalExpectation("domain", true), "nonce", peg$literalExpectation("nonce", true), function(nonce) { options = options || { data: {} }; options.data.nonce = nonce; }, "opaque", peg$literalExpectation("opaque", true), function(opaque) { options = options || { data: {} }; options.data.opaque = opaque; }, "stale", peg$literalExpectation("stale", true), "true", peg$literalExpectation("true", true), function() { options = options || { data: {} }; options.data.stale = true; }, "false", peg$literalExpectation("false", true), function() { options = options || { data: {} }; options.data.stale = false; }, "algorithm", peg$literalExpectation("algorithm", true), "md5", peg$literalExpectation("MD5", true), "md5-sess", peg$literalExpectation("MD5-sess", true), function(algorithm) { options = options || { data: {} }; options.data.algorithm = algorithm.toUpperCase(); }, "qop", peg$literalExpectation("qop", true), "auth-int", peg$literalExpectation("auth-int", true), "auth", peg$literalExpectation("auth", true), function(qop_value) { options = options || { data: {} }; options.data.qop || (options.data.qop = []); options.data.qop.push(qop_value.toLowerCase()); }, function(rack_value) { options = options || { data: {} }; options.data.value = parseInt(rack_value.join('')); }, function() { var idx, length; options = options || { data: {} }; length = options.data.multi_header.length; for (idx = 0; idx < length; idx++) { if (options.data.multi_header[idx].parsed === null) { options.data = null; break; } } if (options.data !== null) { options.data = options.data.multi_header; } else { options.data = -1; } }, function() { var header; options = options || { data: {} }; if (!options.data.multi_header) options.data.multi_header = []; try { header = new NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); delete options.data.uri; delete options.data.displayName; delete options.data.params; } catch (e) { header = null; } options.data.multi_header.push({ 'position': peg$currPos, 'offset': location().start.offset, 'parsed': header }); }, function() { options = options || { data: {} }; options.data = new NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); }, function() { options = options || { data: {} }; if (!(options.data.replaces_from_tag && options.data.replaces_to_tag)) { options.data = -1; } }, function() { options = options || { data: {} }; options.data = { call_id: options.data }; }, "from-tag", peg$literalExpectation("from-tag", true), function(from_tag) { options = options || { data: {} }; options.data.replaces_from_tag = from_tag; }, "to-tag", peg$literalExpectation("to-tag", true), function(to_tag) { options = options || { data: {} }; options.data.replaces_to_tag = to_tag; }, "early-only", peg$literalExpectation("early-only", true), function() { options = options || { data: {} }; options.data.early_only = true; }, function(head, r) { return r; }, function(head, tail) { return list(head, tail); }, function(value) { options = options || { data: {} }; if (options.startRule === 'Require') { options.data = value || []; } }, function(rseq_value) { options = options || { data: {} }; options.data.value = parseInt(rseq_value.join('')); }, "active", peg$literalExpectation("active", true), "pending", peg$literalExpectation("pending", true), "terminated", peg$literalExpectation("terminated", true), function() { options = options || { data: {} }; options.data.state = text(); }, "reason", peg$literalExpectation("reason", true), function(reason) { options = options || { data: {} }; if (typeof reason !== 'undefined') options.data.reason = reason; }, function(expires) { options = options || { data: {} }; if (typeof expires !== 'undefined') options.data.expires = expires; }, "retry_after", peg$literalExpectation("retry_after", true), function(retry_after) { options = options || { data: {} }; if (typeof retry_after !== 'undefined') options.data.retry_after = retry_after; }, "deactivated", peg$literalExpectation("deactivated", true), "probation", peg$literalExpectation("probation", true), "rejected", peg$literalExpectation("rejected", true), "timeout", peg$literalExpectation("timeout", true), "giveup", peg$literalExpectation("giveup", true), "noresource", peg$literalExpectation("noresource", true), "invariant", peg$literalExpectation("invariant", true), function(value) { options = options || { data: {} }; if (options.startRule === 'Supported') { options.data = value || []; } }, function() { options = options || { data: {} }; var tag = options.data.tag; options.data = new NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); if (tag) { options.data.setParam('tag', tag); } }, "ttl", peg$literalExpectation("ttl", true), function(via_ttl_value) { options = options || { data: {} }; options.data.ttl = via_ttl_value; }, "maddr", peg$literalExpectation("maddr", true), function(via_maddr) { options = options || { data: {} }; options.data.maddr = via_maddr; }, "received", peg$literalExpectation("received", true), function(via_received) { options = options || { data: {} }; options.data.received = via_received; }, "branch", peg$literalExpectation("branch", true), function(via_branch) { options = options || { data: {} }; options.data.branch = via_branch; }, "rport", peg$literalExpectation("rport", true), function(response_port) { options = options || { data: {} }; if (typeof response_port !== 'undefined') options.data.rport = response_port.join(''); }, function(via_protocol) { options = options || { data: {} }; options.data.protocol = via_protocol; }, peg$literalExpectation("UDP", true), peg$literalExpectation("TCP", true), peg$literalExpectation("TLS", true), peg$literalExpectation("SCTP", true), function(via_transport) { options = options || { data: {} }; options.data.transport = via_transport; }, function() { options = options || { data: {} }; options.data.host = text(); }, function(via_sent_by_port) { options = options || { data: {} }; options.data.port = parseInt(via_sent_by_port.join('')); }, function(ttl) { return parseInt(ttl.join('')); }, function(deltaSeconds) { options = options || { data: {} }; if (options.startRule === 'Session_Expires') { options.data.deltaSeconds = deltaSeconds; } }, "refresher", peg$literalExpectation("refresher", false), "uas", peg$literalExpectation("uas", false), "uac", peg$literalExpectation("uac", false), function(endpoint) { options = options || { data: {} }; if (options.startRule === 'Session_Expires') { options.data.refresher = endpoint; } }, function(deltaSeconds) { options = options || { data: {} }; if (options.startRule === 'Min_SE') { options.data = deltaSeconds; } }, "stuns", peg$literalExpectation("stuns", true), "stun", peg$literalExpectation("stun", true), function(scheme) { options = options || { data: {} }; options.data.scheme = scheme; }, function(host) { options = options || { data: {} }; options.data.host = host; }, "?transport=", peg$literalExpectation("?transport=", false), "turns", peg$literalExpectation("turns", true), "turn", peg$literalExpectation("turn", true), function(transport) { options = options || { data: {} }; options.data.transport = transport; }, function() { options = options || { data: {} }; options.data = text(); }, "Referred-By", peg$literalExpectation("Referred-By", false), "b", peg$literalExpectation("b", false), "cid", peg$literalExpectation("cid", false) ]; const peg$bytecode = [ peg$decode("2 \"\"6 7!"), peg$decode("4\"\"\"5!7#"), peg$decode("4$\"\"5!7%"), peg$decode("4&\"\"5!7'"), peg$decode(";'.# &;("), peg$decode("4(\"\"5!7)"), peg$decode("4*\"\"5!7+"), peg$decode("2,\"\"6,7-"), peg$decode("2.\"\"6.7/"), peg$decode("40\"\"5!71"), peg$decode("22\"\"6273.\x89 &24\"\"6475.} &26\"\"6677.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), peg$decode(";).# &;,"), peg$decode("2F\"\"6F7G.} &2H\"\"6H7I.q &2J\"\"6J7K.e &2L\"\"6L7M.Y &2N\"\"6N7O.M &2P\"\"6P7Q.A &2R\"\"6R7S.5 &2T\"\"6T7U.) &2V\"\"6V7W"), peg$decode("%%2X\"\"6X7Y/5#;#/,$;#/#$+#)(#'#(\"'#&'#/\"!&,)"), peg$decode("%%$;$0#*;$&/,#; /#$+\")(\"'#&'#.\" &\"/=#$;$/�#*;$&&&#/'$8\":Z\" )(\"'#&'#"), peg$decode(";..\" &\""), peg$decode("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"), peg$decode("%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+\")(\"'#&'#0=*%$;.0#*;.&/,#;2/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/\"!&,)"), peg$decode("4\\\"\"5!7].# &;3"), peg$decode("4^\"\"5!7_"), peg$decode("4`\"\"5!7a"), peg$decode(";!.) &4b\"\"5!7c"), peg$decode("%$;).\x95 &2F\"\"6F7G.\x89 &2J\"\"6J7K.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O/\x9E#0\x9B*;).\x95 &2F\"\"6F7G.\x89 &2J\"\"6J7K.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O&&&#/\"!&,)"), peg$decode("%$;).\x89 &2F\"\"6F7G.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O/\x92#0\x8F*;).\x89 &2F\"\"6F7G.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O&&&#/\"!&,)"), peg$decode("2T\"\"6T7U.\xE3 &2V\"\"6V7W.\xD7 &2f\"\"6f7g.\xCB &2h\"\"6h7i.\xBF &2:\"\"6:7;.\xB3 &2D\"\"6D7E.\xA7 &22\"\"6273.\x9B &28\"\"6879.\x8F &2j\"\"6j7k.\x83 &;&.} &24\"\"6475.q &2l\"\"6l7m.e &2n\"\"6n7o.Y &26\"\"6677.M &2>\"\"6>7?.A &2p\"\"6p7q.5 &2r\"\"6r7s.) &;'.# &;("), peg$decode("%$;).\u012B &2F\"\"6F7G.\u011F &2J\"\"6J7K.\u0113 &2L\"\"6L7M.\u0107 &2X\"\"6X7Y.\xFB &2P\"\"6P7Q.\xEF &2H\"\"6H7I.\xE3 &2@\"\"6@7A.\xD7 &2d\"\"6d7e.\xCB &2R\"\"6R7S.\xBF &2N\"\"6N7O.\xB3 &2T\"\"6T7U.\xA7 &2V\"\"6V7W.\x9B &2f\"\"6f7g.\x8F &2h\"\"6h7i.\x83 &28\"\"6879.w &2j\"\"6j7k.k &;&.e &24\"\"6475.Y &2l\"\"6l7m.M &2n\"\"6n7o.A &26\"\"6677.5 &2p\"\"6p7q.) &2r\"\"6r7s/\u0134#0\u0131*;).\u012B &2F\"\"6F7G.\u011F &2J\"\"6J7K.\u0113 &2L\"\"6L7M.\u0107 &2X\"\"6X7Y.\xFB &2P\"\"6P7Q.\xEF &2H\"\"6H7I.\xE3 &2@\"\"6@7A.\xD7 &2d\"\"6d7e.\xCB &2R\"\"6R7S.\xBF &2N\"\"6N7O.\xB3 &2T\"\"6T7U.\xA7 &2V\"\"6V7W.\x9B &2f\"\"6f7g.\x8F &2h\"\"6h7i.\x83 &28\"\"6879.w &2j\"\"6j7k.k &;&.e &24\"\"6475.Y &2l\"\"6l7m.M &2n\"\"6n7o.A &26\"\"6677.5 &2p\"\"6p7q.) &2r\"\"6r7s&&&#/\"!&,)"), peg$decode("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"), peg$decode("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"), peg$decode("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"), peg$decode("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"), peg$decode("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"), peg$decode("%2h\"\"6h7i/0#;//'$8\":y\" )(\"'#&'#"), peg$decode("%;//6#2f\"\"6f7g/'$8\":z\" )(\"'#&'#"), peg$decode("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"), peg$decode("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"), peg$decode("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"), peg$decode("%;//0#;&/'$8\":~\" )(\"'#&'#"), peg$decode("%;&/0#;//'$8\":~\" )(\"'#&'#"), peg$decode("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"), peg$decode("4\x7F\"\"5!7\x80.A &4\x81\"\"5!7\x82.5 &4\x83\"\"5!7\x84.) &;3.# &;."), peg$decode("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"), peg$decode("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:\x85$!!)($'#(#'#(\"'#&'#"), peg$decode(";..G &2L\"\"6L7M.; &4\x86\"\"5!7\x87./ &4\x83\"\"5!7\x84.# &;3"), peg$decode("%2j\"\"6j7k/J#4\x88\"\"5!7\x89.5 &4\x8A\"\"5!7\x8B.) &4\x8C\"\"5!7\x8D/#$+\")(\"'#&'#"), peg$decode("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:\x8E$ )($'#(#'#(\"'#&'#"), peg$decode("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:\x8F& )(&'#(%'#($'#(#'#(\"'#&'#"), peg$decode("%3\x90\"\"5$7\x91.) &3\x92\"\"5#7\x93/' 8!:\x94!! )"), peg$decode("%;P/]#%28\"\"6879/,#;R/#$+\")(\"'#&'#.\" &\"/6$2:\"\"6:7;/'$8#:\x95# )(#'#(\"'#&'#"), peg$decode("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"), peg$decode("2<\"\"6<7=.q &2>\"\"6>7?.e &2@\"\"6@7A.Y &2B\"\"6B7C.M &2D\"\"6D7E.A &22\"\"6273.5 &26\"\"6677.) &24\"\"6475"), peg$decode("%$;+._ &;-.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E0e*;+._ &;-.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E&/& 8!:\x96! )"), peg$decode("%;T/J#%28\"\"6879/,#;^/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), peg$decode("%;U.) &;\\.# &;X/& 8!:\x97! )"), peg$decode("%$%;V/2#2J\"\"6J7K/#$+\")(\"'#&'#0<*%;V/2#2J\"\"6J7K/#$+\")(\"'#&'#&/D#;W/;$2J\"\"6J7K.\" &\"/'$8#:\x98# )(#'#(\"'#&'#"), peg$decode("$4\x99\"\"5!7\x9A/,#0)*4\x99\"\"5!7\x9A&&&#"), peg$decode("%4$\"\"5!7%/?#$4\x9B\"\"5!7\x9C0)*4\x9B\"\"5!7\x9C&/#$+\")(\"'#&'#"), peg$decode("%2l\"\"6l7m/?#;Y/6$2n\"\"6n7o/'$8#:\x9D# )(#'#(\"'#&'#"), peg$decode("%%;Z/\xB3#28\"\"6879/\xA4$;Z/\x9B$28\"\"6879/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+-)(-'#(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0790 &%2\x9E\"\"6\x9E7\x9F/\xA4#;Z/\x9B$28\"\"6879/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+,)(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u06F9 &%2\x9E\"\"6\x9E7\x9F/\x8C#;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u067A &%2\x9E\"\"6\x9E7\x9F/t#;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0613 &%2\x9E\"\"6\x9E7\x9F/\\#;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+&)(&'#(%'#($'#(#'#(\"'#&'#.\u05C4 &%2\x9E\"\"6\x9E7\x9F/D#;Z/;$28\"\"6879/,$;[/#$+$)($'#(#'#(\"'#&'#.\u058D &%2\x9E\"\"6\x9E7\x9F/,#;[/#$+\")(\"'#&'#.\u056E &%2\x9E\"\"6\x9E7\x9F/,#;Z/#$+\")(\"'#&'#.\u054F &%;Z/\x9B#2\x9E\"\"6\x9E7\x9F/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$++)(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u04C7 &%;Z/\xAA#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x83$2\x9E\"\"6\x9E7\x9F/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0430 &%;Z/\xB9#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x92$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/k$2\x9E\"\"6\x9E7\x9F/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+))()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u038A &%;Z/\xC8#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xA1$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/z$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/S$2\x9E\"\"6\x9E7\x9F/D$;Z/;$28\"\"6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u02D5 &%;Z/\xD7#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xB0$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x89$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/b$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/;$2\x9E\"\"6\x9E7\x9F/,$;[/#$+')(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0211 &%;Z/\xFE#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xD7$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xB0$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x89$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/b$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/;$2\x9E\"\"6\x9E7\x9F/,$;Z/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0126 &%;Z/\u011C#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xF5$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xCE$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xA7$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x80$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/Y$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/2$2\x9E\"\"6\x9E7\x9F/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#/& 8!:\xA0! )"), peg$decode("%;#/M#;#.\" &\"/?$;#.\" &\"/1$;#.\" &\"/#$+$)($'#(#'#(\"'#&'#"), peg$decode("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"), peg$decode("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':\xA1' )(''#(&'#(%'#($'#(#'#(\"'#&'#"), peg$decode("%2\xA2\"\"6\xA27\xA3/2#4\xA4\"\"5!7\xA5/#$+\")(\"'#&'#.\x98 &%2\xA6\"\"6\xA67\xA7/;#4\xA8\"\"5!7\xA9/,$;!/#$+#)(#'#(\"'#&'#.j &%2\xAA\"\"6\xAA7\xAB/5#;!/,$;!/#$+#)(#'#(\"'#&'#.B &%4\xAC\"\"5!7\xAD/,#;!/#$+\")(\"'#&'#.# &;!"), peg$decode("%%;!.\" &\"/[#;!.\" &\"/M$;!.\" &\"/?$;!.\" &\"/1$;!.\" &\"/#$+%)(%'#($'#(#'#(\"'#&'#/' 8!:\xAE!! )"), peg$decode("$%22\"\"6273/,#;`/#$+\")(\"'#&'#0<*%22\"\"6273/,#;`/#$+\")(\"'#&'#&"), peg$decode(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"), peg$decode("%3\xAF\"\"5*7\xB0/a#3\xB1\"\"5#7\xB2.G &3\xB3\"\"5#7\xB4.; &3\xB5\"\"5$7\xB6./ &3\xB7\"\"5#7\xB8.# &;6/($8\":\xB9\"! )(\"'#&'#"), peg$decode("%3\xBA\"\"5%7\xBB/I#3\xBC\"\"5%7\xBD./ &3\xBE\"\"5\"7\xBF.# &;6/($8\":\xC0\"! )(\"'#&'#"), peg$decode("%3\xC1\"\"5'7\xC2/1#;\x90/($8\":\xC3\"! )(\"'#&'#"), peg$decode("%3\xC4\"\"5$7\xC5/1#;\xF0/($8\":\xC6\"! )(\"'#&'#"), peg$decode("%3\xC7\"\"5&7\xC8/1#;T/($8\":\xC9\"! )(\"'#&'#"), peg$decode("%3\xCA\"\"5\"7\xCB/N#%2>\"\"6>7?/,#;6/#$+\")(\"'#&'#.\" &\"/'$8\":\xCC\" )(\"'#&'#"), peg$decode("%;h/P#%2>\"\"6>7?/,#;i/#$+\")(\"'#&'#.\" &\"/)$8\":\xCD\"\"! )(\"'#&'#"), peg$decode("%$;j/�#*;j&&&#/\"!&,)"), peg$decode("%$;j/�#*;j&&&#/\"!&,)"), peg$decode(";k.) &;+.# &;-"), peg$decode("2l\"\"6l7m.e &2n\"\"6n7o.Y &24\"\"6475.M &28\"\"6879.A &2<\"\"6<7=.5 &2@\"\"6@7A.) &2B\"\"6B7C"), peg$decode("%26\"\"6677/n#;m/e$$%2<\"\"6<7=/,#;m/#$+\")(\"'#&'#0<*%2<\"\"6<7=/,#;m/#$+\")(\"'#&'#&/#$+#)(#'#(\"'#&'#"), peg$decode("%;n/A#2>\"\"6>7?/2$;o/)$8#:\xCE#\"\" )(#'#(\"'#&'#"), peg$decode("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"), peg$decode("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"), peg$decode("2l\"\"6l7m.e &2n\"\"6n7o.Y &24\"\"6475.M &26\"\"6677.A &28\"\"6879.5 &2@\"\"6@7A.) &2B\"\"6B7C"), peg$decode(";\x91.# &;r"), peg$decode("%;\x90/G#;'/>$;s/5$;'/,$;\x84/#$+%)(%'#($'#(#'#(\"'#&'#"), peg$decode(";M.# &;t"), peg$decode("%;\x7F/E#28\"\"6879/6$;u.# &;x/'$8#:\xCF# )(#'#(\"'#&'#"), peg$decode("%;v.# &;w/J#%26\"\"6677/,#;\x83/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), peg$decode("%2\xD0\"\"6\xD07\xD1/:#;\x80/1$;w.\" &\"/#$+#)(#'#(\"'#&'#"), peg$decode("%24\"\"6475/,#;{/#$+\")(\"'#&'#"), peg$decode("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"), peg$decode(";*.) &;+.# &;-"), peg$decode(";+.\x8F &;-.\x89 &22\"\"6273.} &26\"\"6677.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), peg$decode("%;|/e#$%24\"\"6475/,#;|/#$+\")(\"'#&'#0<*%24\"\"6475/,#;|/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), peg$decode("%$;~0#*;~&/e#$%22\"\"6273/,#;}/#$+\")(\"'#&'#0<*%22\"\"6273/,#;}/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), peg$decode("$;~0#*;~&"), peg$decode(";+.w &;-.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), peg$decode("%%;\"/\x87#$;\".G &;!.A &2@\"\"6@7A.5 &2F\"\"6F7G.) &2J\"\"6J7K0M*;\".G &;!.A &2@\"\"6@7A.5 &2F\"\"6F7G.) &2J\"\"6J7K&/#$+\")(\"'#&'#/& 8!:\xD2! )"), peg$decode(";\x81.# &;\x82"), peg$decode("%%;O/2#2:\"\"6:7;/#$+\")(\"'#&'#.\" &\"/,#;S/#$+\")(\"'#&'#.\" &\""), peg$decode("$;+.\x83 &;-.} &2B\"\"6B7C.q &2D\"\"6D7E.e &22\"\"6273.Y &28\"\"6879.M &2:\"\"6:7;.A &2<\"\"6<7=.5 &2>\"\"6>7?.) &2@\"\"6@7A/\x8C#0\x89*;+.\x83 &;-.} &2B\"\"6B7C.q &2D\"\"6D7E.e &22\"\"6273.Y &28\"\"6879.M &2:\"\"6:7;.A &2<\"\"6<7=.5 &2>\"\"6>7?.) &2@\"\"6@7A&&&#"), peg$decode("$;y0#*;y&"), peg$decode("%3\x92\"\"5#7\xD3/q#24\"\"6475/b$$;!/�#*;!&&&#/L$2J\"\"6J7K/=$$;!/�#*;!&&&#/'$8%:\xD4% )(%'#($'#(#'#(\"'#&'#"), peg$decode("2\xD5\"\"6\xD57\xD6"), peg$decode("2\xD7\"\"6\xD77\xD8"), peg$decode("2\xD9\"\"6\xD97\xDA"), peg$decode("2\xDB\"\"6\xDB7\xDC"), peg$decode("2\xDD\"\"6\xDD7\xDE"), peg$decode("2\xDF\"\"6\xDF7\xE0"), peg$decode("2\xE1\"\"6\xE17\xE2"), peg$decode("2\xE3\"\"6\xE37\xE4"), peg$decode("2\xE5\"\"6\xE57\xE6"), peg$decode("2\xE7\"\"6\xE77\xE8"), peg$decode("2\xE9\"\"6\xE97\xEA"), peg$decode("%;\x85.Y &;\x86.S &;\x88.M &;\x89.G &;\x8A.A &;\x8B.; &;\x8C.5 &;\x8F./ &;\x8D.) &;\x8E.# &;6/& 8!:\xEB! )"), peg$decode("%;\x84/G#;'/>$;\x92/5$;'/,$;\x94/#$+%)(%'#($'#(#'#(\"'#&'#"), peg$decode("%;\x93/' 8!:\xEC!! )"), peg$decode("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"), peg$decode("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:\xED! )"), peg$decode("%;\xB6/Y#$%;A/,#;\xB6/#$+\")(\"'#&'#06*%;A/,#;\xB6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), peg$decode("%;9/N#%2:\"\"6:7;/,#;9/#$+\")(\"'#&'#.\" &\"/'$8\":\xEE\" )(\"'#&'#"), peg$decode("%;:.c &%;\x98/Y#$%;A/,#;\x98/#$+\")(\"'#&'#06*%;A/,#;\x98/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:\xEF! )"), peg$decode("%;L.# &;\x99/]#$%;B/,#;\x9B/#$+\")(\"'#&'#06*%;B/,#;\x9B/#$+\")(\"'#&'#&/'$8\":\xF0\" )(\"'#&'#"), peg$decode("%;\x9A.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"), peg$decode("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:\xF1!! )"), peg$decode(";\x9C.) &;\x9D.# &;\xA0"), peg$decode("%3\xF2\"\"5!7\xF3/:#;$;\xCF/5$;./,$;\x90/#$+%)(%'#($'#(#'#(\"'#&'#"), peg$decode("%$;!/�#*;!&&&#/' 8!:\u014B!! )"), peg$decode("%;\xD1/]#$%;A/,#;\xD1/#$+\")(\"'#&'#06*%;A/,#;\xD1/#$+\")(\"'#&'#&/'$8\":\u014C\" )(\"'#&'#"), peg$decode("%;\x99/]#$%;B/,#;\xA0/#$+\")(\"'#&'#06*%;B/,#;\xA0/#$+\")(\"'#&'#&/'$8\":\u014D\" )(\"'#&'#"), peg$decode("%;L.O &;\x99.I &%;@.\" &\"/:#;t/1$;?.\" &\"/#$+#)(#'#(\"'#&'#/]#$%;B/,#;\xA0/#$+\")(\"'#&'#06*%;B/,#;\xA0/#$+\")(\"'#&'#&/'$8\":\u014E\" )(\"'#&'#"), peg$decode("%;\xD4/]#$%;B/,#;\xD5/#$+\")(\"'#&'#06*%;B/,#;\xD5/#$+\")(\"'#&'#&/'$8\":\u014F\" )(\"'#&'#"), peg$decode("%;\x96/& 8!:\u0150! )"), peg$decode("%3\u0151\"\"5(7\u0152/:#;$;6/5$;;/,$;\xEC/#$+%)(%'#($'#(#'#(\"'#&'#"), peg$decode("%3\x92\"\"5#7\xD3.# &;6/' 8!:\u018B!! )"), peg$decode("%3\xB1\"\"5#7\u018C.G &3\xB3\"\"5#7\u018D.; &3\xB7\"\"5#7\u018E./ &3\xB5\"\"5$7\u018F.# &;6/' 8!:\u0190!! )"), peg$decode("%;\xEE/D#%;C/,#;\xEF/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), peg$decode("%;U.) &;\\.# &;X/& 8!:\u0191! )"), peg$decode("%%;!.\" &\"/[#;!.\" &\"/M$;!.\" &\"/?$;!.\" &\"/1$;!.\" &\"/#$+%)(%'#($'#(#'#(\"'#&'#/' 8!:\u0192!! )"), peg$decode("%%;!/?#;!.\" &\"/1$;!.\" &\"/#$+#)(#'#(\"'#&'#/' 8!:\u0193!! )"), peg$decode(";\xBE"), peg$decode("%;\x9E/^#$%;B/,#;\xF3/#$+\")(\"'#&'#06*%;B/,#;\xF3/#$+\")(\"'#&'#&/($8\":\u0194\"!!)(\"'#&'#"), peg$decode(";\xF4.# &;\xA0"), peg$decode("%2\u0195\"\"6\u01957\u0196/L#;\"\"6>7?"), peg$decode("%;\u0100/b#28\"\"6879/S$;\xFB/J$%2\u01A3\"\"6\u01A37\u01A4/,#;\xEC/#$+\")(\"'#&'#.\" &\"/#$+$)($'#(#'#(\"'#&'#"), peg$decode("%3\u01A5\"\"5%7\u01A6.) &3\u01A7\"\"5$7\u01A8/' 8!:\u01A1!! )"), peg$decode("%3\xB1\"\"5#7\xB2.6 &3\xB3\"\"5#7\xB4.* &$;+0#*;+&/' 8!:\u01A9!! )"), peg$decode("%;\u0104/\x87#2F\"\"6F7G/x$;\u0103/o$2F\"\"6F7G/`$;\u0103/W$2F\"\"6F7G/H$;\u0103/?$2F\"\"6F7G/0$;\u0105/'$8):\u01AA) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"), peg$decode("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"), peg$decode("%;\u0103/,#;\u0103/#$+\")(\"'#&'#"), peg$decode("%;\u0103/5#;\u0103/,$;\u0103/#$+#)(#'#(\"'#&'#"), peg$decode("%;q/T#$;m0#*;m&/D$%; /,#;\xF8/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"), peg$decode("%2\u01AB\"\"6\u01AB7\u01AC.) &2\u01AD\"\"6\u01AD7\u01AE/w#;0/n$;\u0108/e$$%;B/2#;\u0109.# &;\xA0/#$+\")(\"'#&'#0<*%;B/2#;\u0109.# &;\xA0/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"), peg$decode(";\x99.# &;L"), peg$decode("%2\u01AF\"\"6\u01AF7\u01B0/5#; peg$maxFailPos) { peg$maxFailPos = peg$currPos; peg$maxFailExpected = []; } peg$maxFailExpected.push(expected1); } function peg$buildStructuredError(expected1, found, location1) { return new SyntaxError(SyntaxError.buildMessage(expected1, found), expected1, found, location1); } function peg$decode(s) { return s.split("").map((ch) => ch.charCodeAt(0) - 32); } function peg$parseRule(index) { const bc = peg$bytecode[index]; let ip = 0; const ips = []; let end = bc.length; const ends = []; const stack = []; let params; while (true) { while (ip < end) { switch (bc[ip]) { case 0: stack.push(peg$consts[bc[ip + 1]]); ip += 2; break; case 1: stack.push(undefined); ip++; break; case 2: stack.push(null); ip++; break; case 3: stack.push(peg$FAILED); ip++; break; case 4: stack.push([]); ip++; break; case 5: stack.push(peg$currPos); ip++; break; case 6: stack.pop(); ip++; break; case 7: peg$currPos = stack.pop(); ip++; break; case 8: stack.length -= bc[ip + 1]; ip += 2; break; case 9: stack.splice(-2, 1); ip++; break; case 10: stack[stack.length - 2].push(stack.pop()); ip++; break; case 11: stack.push(stack.splice(stack.length - bc[ip + 1], bc[ip + 1])); ip += 2; break; case 12: stack.push(input.substring(stack.pop(), peg$currPos)); ip++; break; case 13: ends.push(end); ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); if (stack[stack.length - 1]) { end = ip + 3 + bc[ip + 1]; ip += 3; } else { end = ip + 3 + bc[ip + 1] + bc[ip + 2]; ip += 3 + bc[ip + 1]; } break; case 14: ends.push(end); ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); if (stack[stack.length - 1] === peg$FAILED) { end = ip + 3 + bc[ip + 1]; ip += 3; } else { end = ip + 3 + bc[ip + 1] + bc[ip + 2]; ip += 3 + bc[ip + 1]; } break; case 15: ends.push(end); ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); if (stack[stack.length - 1] !== peg$FAILED) { end = ip + 3 + bc[ip + 1]; ip += 3; } else { end = ip + 3 + bc[ip + 1] + bc[ip + 2]; ip += 3 + bc[ip + 1]; } break; case 16: if (stack[stack.length - 1] !== peg$FAILED) { ends.push(end); ips.push(ip); end = ip + 2 + bc[ip + 1]; ip += 2; } else { ip += 2 + bc[ip + 1]; } break; case 17: ends.push(end); ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); if (input.length > peg$currPos) { end = ip + 3 + bc[ip + 1]; ip += 3; } else { end = ip + 3 + bc[ip + 1] + bc[ip + 2]; ip += 3 + bc[ip + 1]; } break; case 18: ends.push(end); ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length) === peg$consts[bc[ip + 1]]) { end = ip + 4 + bc[ip + 2]; ip += 4; } else { end = ip + 4 + bc[ip + 2] + bc[ip + 3]; ip += 4 + bc[ip + 2]; } break; case 19: ends.push(end); ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length).toLowerCase() === peg$consts[bc[ip + 1]]) { end = ip + 4 + bc[ip + 2]; ip += 4; } else { end = ip + 4 + bc[ip + 2] + bc[ip + 3]; ip += 4 + bc[ip + 2]; } break; case 20: ends.push(end); ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); if (peg$consts[bc[ip + 1]].test(input.charAt(peg$currPos))) { end = ip + 4 + bc[ip + 2]; ip += 4; } else { end = ip + 4 + bc[ip + 2] + bc[ip + 3]; ip += 4 + bc[ip + 2]; } break; case 21: stack.push(input.substr(peg$currPos, bc[ip + 1])); peg$currPos += bc[ip + 1]; ip += 2; break; case 22: stack.push(peg$consts[bc[ip + 1]]); peg$currPos += peg$consts[bc[ip + 1]].length; ip += 2; break; case 23: stack.push(peg$FAILED); if (peg$silentFails === 0) { peg$fail(peg$consts[bc[ip + 1]]); } ip += 2; break; case 24: peg$savedPos = stack[stack.length - 1 - bc[ip + 1]]; ip += 2; break; case 25: peg$savedPos = peg$currPos; ip++; break; case 26: params = bc.slice(ip + 4, ip + 4 + bc[ip + 3]) .map(function(p) { return stack[stack.length - 1 - p]; }); stack.splice(stack.length - bc[ip + 2], bc[ip + 2], peg$consts[bc[ip + 1]].apply(null, params)); ip += 4 + bc[ip + 3]; break; case 27: stack.push(peg$parseRule(bc[ip + 1])); ip += 2; break; case 28: peg$silentFails++; ip++; break; case 29: peg$silentFails--; ip++; break; default: throw new Error("Invalid opcode: " + bc[ip] + "."); } } if (ends.length > 0) { end = ends.pop(); ip = ips.pop(); } else { break; } } return stack[0]; } options.data = {}; // Object to which header attributes will be assigned during parsing function list(head, tail) { return [head].concat(tail); } peg$result = peg$parseRule(peg$startRuleIndex); if (peg$result !== peg$FAILED && peg$currPos === input.length) { return peg$result; } else { if (peg$result !== peg$FAILED && peg$currPos < input.length) { peg$fail(peg$endExpectation()); } throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); } } const parse = peg$parse; /** * Grammar. * @internal */ var Grammar; (function(Grammar) { /** * Parse. * @param input - * @param startRule - */ function parse$1(input, startRule) { const options = { startRule }; try { parse(input, options); } catch (e) { options.data = -1; } return options.data; } Grammar.parse = parse$1; /** * Parse the given string and returns a SIP.NameAddrHeader instance or undefined if * it is an invalid NameAddrHeader. * @param name_addr_header - */ function nameAddrHeaderParse(nameAddrHeader) { const parsedNameAddrHeader = Grammar.parse(nameAddrHeader, "Name_Addr_Header"); return parsedNameAddrHeader !== -1 ? parsedNameAddrHeader : undefined; } Grammar.nameAddrHeaderParse = nameAddrHeaderParse; /** * Parse the given string and returns a SIP.URI instance or undefined if * it is an invalid URI. * @param uri - */ function URIParse(uri) { const parsedUri = Grammar.parse(uri, "SIP_URI"); return parsedUri !== -1 ? parsedUri : undefined; } Grammar.URIParse = URIParse; })(Grammar || (Grammar = {})); /** * @param size - * @param base - * @internal */ function createRandomToken(size, base = 32) { let token = ""; for (let i = 0; i < size; i++) { const r = Math.floor(Math.random() * base); token += r.toString(base); } return token; } /** * @internal */ function getReasonPhrase(code) { return REASON_PHRASE[code] || ""; } /** * @internal */ function newTag() { return createRandomToken(10); } /** * @param str - * @internal */ function headerize(str) { const exceptions = { "Call-Id": "Call-ID", "Cseq": "CSeq", "Min-Se": "Min-SE", "Rack": "RAck", "Rseq": "RSeq", "Www-Authenticate": "WWW-Authenticate", }; const name = str.toLowerCase().replace(/_/g, "-").split("-"); const parts = name.length; let hname = ""; for (let part = 0; part < parts; part++) { if (part !== 0) { hname += "-"; } hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); } if (exceptions[hname]) { hname = exceptions[hname]; } return hname; } /** * @param str - * @internal */ function str_utf8_length(str) { return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; } /** * SIP Response Reasons * DOC: http://www.iana.org/assignments/sip-parameters * @internal */ const REASON_PHRASE = { 100: "Trying", 180: "Ringing", 181: "Call Is Being Forwarded", 182: "Queued", 183: "Session Progress", 199: "Early Dialog Terminated", 200: "OK", 202: "Accepted", 204: "No Notification", 300: "Multiple Choices", 301: "Moved Permanently", 302: "Moved Temporarily", 305: "Use Proxy", 380: "Alternative Service", 400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 406: "Not Acceptable", 407: "Proxy Authentication Required", 408: "Request Timeout", 410: "Gone", 412: "Conditional Request Failed", 413: "Request Entity Too Large", 414: "Request-URI Too Long", 415: "Unsupported Media Type", 416: "Unsupported URI Scheme", 417: "Unknown Resource-Priority", 420: "Bad Extension", 421: "Extension Required", 422: "Session Interval Too Small", 423: "Interval Too Brief", 428: "Use Identity Header", 429: "Provide Referrer Identity", 430: "Flow Failed", 433: "Anonymity Disallowed", 436: "Bad Identity-Info", 437: "Unsupported Certificate", 438: "Invalid Identity Header", 439: "First Hop Lacks Outbound Support", 440: "Max-Breadth Exceeded", 469: "Bad Info Package", 470: "Consent Needed", 478: "Unresolvable Destination", 480: "Temporarily Unavailable", 481: "Call/Transaction Does Not Exist", 482: "Loop Detected", 483: "Too Many Hops", 484: "Address Incomplete", 485: "Ambiguous", 486: "Busy Here", 487: "Request Terminated", 488: "Not Acceptable Here", 489: "Bad Event", 491: "Request Pending", 493: "Undecipherable", 494: "Security Agreement Required", 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Server Time-out", 505: "Version Not Supported", 513: "Message Too Large", 580: "Precondition Failure", 600: "Busy Everywhere", 603: "Decline", 604: "Does Not Exist Anywhere", 606: "Not Acceptable" }; /** * Incoming message. * @public */ class IncomingMessage { constructor() { this.headers = {}; } /** * Insert a header of the given name and value into the last position of the * header array. * @param name - header name * @param value - header value */ addHeader(name, value) { const header = { raw: value }; name = headerize(name); if (this.headers[name]) { this.headers[name].push(header); } else { this.headers[name] = [header]; } } /** * Get the value of the given header name at the given position. * @param name - header name * @returns Returns the specified header, undefined if header doesn't exist. */ getHeader(name) { const header = this.headers[headerize(name)]; if (header) { if (header[0]) { return header[0].raw; } } else { return; } } /** * Get the header/s of the given name. * @param name - header name * @returns Array - with all the headers of the specified name. */ getHeaders(name) { const header = this.headers[headerize(name)]; const result = []; if (!header) { return []; } for (const headerPart of header) { result.push(headerPart.raw); } return result; } /** * Verify the existence of the given header. * @param name - header name * @returns true if header with given name exists, false otherwise */ hasHeader(name) { return !!this.headers[headerize(name)]; } /** * Parse the given header on the given index. * @param name - header name * @param idx - header index * @returns Parsed header object, undefined if the * header is not present or in case of a parsing error. */ parseHeader(name, idx = 0) { name = headerize(name); if (!this.headers[name]) { // this.logger.log("header '" + name + "' not present"); return; } else if (idx >= this.headers[name].length) { // this.logger.log("not so many '" + name + "' headers present"); return; } const header = this.headers[name][idx]; const value = header.raw; if (header.parsed) { return header.parsed; } // substitute '-' by '_' for grammar rule matching. const parsed = Grammar.parse(value, name.replace(/-/g, "_")); if (parsed === -1) { this.headers[name].splice(idx, 1); // delete from headers // this.logger.warn('error parsing "' + name + '" header field with value "' + value + '"'); return; } else { header.parsed = parsed; return parsed; } } /** * Message Header attribute selector. Alias of parseHeader. * @param name - header name * @param idx - header index * @returns Parsed header object, undefined if the * header is not present or in case of a parsing error. * * @example * message.s('via',3).port */ s(name, idx = 0) { return this.parseHeader(name, idx); } /** * Replace the value of the given header by the value. * @param name - header name * @param value - header value */ setHeader(name, value) { this.headers[headerize(name)] = [{ raw: value }]; } toString() { return this.data; } } /** * Incoming request message. * @public */ class IncomingRequestMessage extends IncomingMessage { constructor() { super(); } } /** * Incoming response message. * @public */ class IncomingResponseMessage extends IncomingMessage { constructor() { super(); } } /** * Outgoing SIP request message. * @public */ class OutgoingRequestMessage { constructor(method, ruri, fromURI, toURI, options, extraHeaders, body) { this.headers = {}; this.extraHeaders = []; this.options = OutgoingRequestMessage.getDefaultOptions(); // Options - merge a deep copy if (options) { this.options = Object.assign(Object.assign({}, this.options), options); if (this.options.optionTags && this.options.optionTags.length) { this.options.optionTags = this.options.optionTags.slice(); } if (this.options.routeSet && this.options.routeSet.length) { this.options.routeSet = this.options.routeSet.slice(); } } // Extra headers - deep copy if (extraHeaders && extraHeaders.length) { this.extraHeaders = extraHeaders.slice(); } // Body - deep copy if (body) { // TODO: internal representation should be Body // this.body = { ...body }; this.body = { body: body.content, contentType: body.contentType }; } // Method this.method = method; // RURI this.ruri = ruri.clone(); // From this.fromURI = fromURI.clone(); this.fromTag = this.options.fromTag ? this.options.fromTag : newTag(); this.from = OutgoingRequestMessage.makeNameAddrHeader(this.fromURI, this.options.fromDisplayName, this.fromTag); // To this.toURI = toURI.clone(); this.toTag = this.options.toTag; this.to = OutgoingRequestMessage.makeNameAddrHeader(this.toURI, this.options.toDisplayName, this.toTag); // Call-ID this.callId = this.options.callId ? this.options.callId : this.options.callIdPrefix + createRandomToken(15); // CSeq this.cseq = this.options.cseq; // The relative order of header fields with different field names is not // significant. However, it is RECOMMENDED that header fields which are // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, // Max-Forwards, and Proxy-Authorization, for example) appear towards // the top of the message to facilitate rapid parsing. // https://tools.ietf.org/html/rfc3261#section-7.3.1 this.setHeader("route", this.options.routeSet); this.setHeader("via", ""); this.setHeader("to", this.to.toString()); this.setHeader("from", this.from.toString()); this.setHeader("cseq", this.cseq + " " + this.method); this.setHeader("call-id", this.callId); this.setHeader("max-forwards", "70"); } /** Get a copy of the default options. */ static getDefaultOptions() { return { callId: "", callIdPrefix: "", cseq: 1, toDisplayName: "", toTag: "", fromDisplayName: "", fromTag: "", forceRport: false, hackViaTcp: false, optionTags: ["outbound"], routeSet: [], userAgentString: "sip.js", viaHost: "" }; } static makeNameAddrHeader(uri, displayName, tag) { const parameters = {}; if (tag) { parameters.tag = tag; } return new NameAddrHeader(uri, displayName, parameters); } /** * Get the value of the given header name at the given position. * @param name - header name * @returns Returns the specified header, undefined if header doesn't exist. */ getHeader(name) { const header = this.headers[headerize(name)]; if (header) { if (header[0]) { return header[0]; } } else { const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); for (const exHeader of this.extraHeaders) { if (regexp.test(exHeader)) { return exHeader.substring(exHeader.indexOf(":") + 1).trim(); } } } return; } /** * Get the header/s of the given name. * @param name - header name * @returns Array with all the headers of the specified name. */ getHeaders(name) { const result = []; const headerArray = this.headers[headerize(name)]; if (headerArray) { for (const headerPart of headerArray) { result.push(headerPart); } } else { const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); for (const exHeader of this.extraHeaders) { if (regexp.test(exHeader)) { result.push(exHeader.substring(exHeader.indexOf(":") + 1).trim()); } } } return result; } /** * Verify the existence of the given header. * @param name - header name * @returns true if header with given name exists, false otherwise */ hasHeader(name) { if (this.headers[headerize(name)]) { return true; } else { const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); for (const extraHeader of this.extraHeaders) { if (regexp.test(extraHeader)) { return true; } } } return false; } /** * Replace the the given header by the given value. * @param name - header name * @param value - header value */ setHeader(name, value) { this.headers[headerize(name)] = (value instanceof Array) ? value : [value]; } /** * The Via header field indicates the transport used for the transaction * and identifies the location where the response is to be sent. A Via * header field value is added only after the transport that will be * used to reach the next hop has been selected (which may involve the * usage of the procedures in [4]). * * When the UAC creates a request, it MUST insert a Via into that * request. The protocol name and protocol version in the header field * MUST be SIP and 2.0, respectively. The Via header field value MUST * contain a branch parameter. This parameter is used to identify the * transaction created by that request. This parameter is used by both * the client and the server. * https://tools.ietf.org/html/rfc3261#section-8.1.1.7 * @param branchParameter - The branch parameter. * @param scheme - The scheme. */ setViaHeader(branch, scheme = "WSS") { // FIXME: Hack if (this.options.hackViaTcp) { scheme = "TCP"; } let via = "SIP/2.0/" + scheme; via += " " + this.options.viaHost + ";branch=" + branch; if (this.options.forceRport) { via += ";rport"; } this.setHeader("via", via); this.branch = branch; } toString() { let msg = ""; msg += this.method + " " + this.ruri.toRaw() + " SIP/2.0\r\n"; for (const header in this.headers) { if (this.headers[header]) { for (const headerPart of this.headers[header]) { msg += header + ": " + headerPart + "\r\n"; } } } for (const header of this.extraHeaders) { msg += header.trim() + "\r\n"; } msg += "Supported: " + this.options.optionTags.join(", ") + "\r\n"; msg += "User-Agent: " + this.options.userAgentString + "\r\n"; if (this.body) { if (typeof this.body === "string") { msg += "Content-Length: " + str_utf8_length(this.body) + "\r\n\r\n"; msg += this.body; } else { if (this.body.body && this.body.contentType) { msg += "Content-Type: " + this.body.contentType + "\r\n"; msg += "Content-Length: " + str_utf8_length(this.body.body) + "\r\n\r\n"; msg += this.body.body; } else { msg += "Content-Length: " + 0 + "\r\n\r\n"; } } } else { msg += "Content-Length: " + 0 + "\r\n\r\n"; } return msg; } } /** * Create a Body given a legacy body type. * @param bodyLegacy - Body Object * @internal */ function fromBodyLegacy(bodyLegacy) { const content = (typeof bodyLegacy === "string") ? bodyLegacy : bodyLegacy.body; const contentType = (typeof bodyLegacy === "string") ? "application/sdp" : bodyLegacy.contentType; const contentDisposition = contentTypeToContentDisposition(contentType); const body = { contentDisposition, contentType, content }; return body; } /** * Given a message, get a normalized body. * The content disposition is inferred if not set. * @param message - The message. * @internal */ function getBody(message) { let contentDisposition; let contentType; let content; // We're in UAS role, receiving incoming request if (message instanceof IncomingRequestMessage) { if (message.body) { // FIXME: Parsing needs typing const parse = message.parseHeader("Content-Disposition"); contentDisposition = parse ? parse.type : undefined; contentType = message.parseHeader("Content-Type"); content = message.body; } } // We're in UAC role, receiving incoming response if (message instanceof IncomingResponseMessage) { if (message.body) { // FIXME: Parsing needs typing const parse = message.parseHeader("Content-Disposition"); contentDisposition = parse ? parse.type : undefined; contentType = message.parseHeader("Content-Type"); content = message.body; } } // We're in UAC role, sending outgoing request if (message instanceof OutgoingRequestMessage) { if (message.body) { contentDisposition = message.getHeader("Content-Disposition"); contentType = message.getHeader("Content-Type"); if (typeof message.body === "string") { // FIXME: OutgoingRequest should not allow a "string" body without a "Content-Type" header. if (!contentType) { throw new Error("Header content type header does not equal body content type."); } content = message.body; } else { // FIXME: OutgoingRequest should not allow the "Content-Type" header not to match th body content type if (contentType && contentType !== message.body.contentType) { throw new Error("Header content type header does not equal body content type."); } contentType = message.body.contentType; content = message.body.body; } } } // We're in UAS role, sending outgoing response if (isBody(message)) { contentDisposition = message.contentDisposition; contentType = message.contentType; content = message.content; } // No content, no body. if (!content) { return undefined; } if (contentType && !contentDisposition) { contentDisposition = contentTypeToContentDisposition(contentType); } if (!contentDisposition) { throw new Error("Content disposition undefined."); } if (!contentType) { throw new Error("Content type undefined."); } return { contentDisposition, contentType, content }; } /** * User-Defined Type Guard for Body. * @param body - Body to check. * @internal */ function isBody(body) { return body && typeof body.content === "string" && typeof body.contentType === "string" && body.contentDisposition === undefined ? true : typeof body.contentDisposition === "string"; } // If the Content-Disposition header field is missing, bodies of // Content-Type application/sdp imply the disposition "session", while // other content types imply "render". // https://tools.ietf.org/html/rfc3261#section-13.2.1 function contentTypeToContentDisposition(contentType) { if (contentType === "application/sdp") { return "session"; } else { return "render"; } } var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var core = createCommonjsModule(function(module, exports) { (function(root, factory) { { // CommonJS module.exports = exports = factory(); } }(commonjsGlobal, function() { /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function(Math, undefined$1) { /* * Local polyfil of Object.create */ var create = Object.create || (function() { function F() {} return function(obj) { var subtype; F.prototype = obj; subtype = new F(); F.prototype = null; return subtype; }; }()); /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function() { return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function(overrides) { // Spawn var subtype = create(this); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { subtype.init = function() { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function() { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function() {}, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function(properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function() { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function(words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined$1) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function(encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function(wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function() { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function() { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function(nBytes) { var words = []; var r = (function(m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function() { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function(wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function(hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function(wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function(latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function(wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function(utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function() { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function(data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function(doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function() { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function(cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function() { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function(messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function(messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512 / 32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function(hasher) { return function(message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function(hasher) { return function(message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); }); var md5 = createCommonjsModule(function(module, exports) { (function(root, factory) { { // CommonJS module.exports = exports = factory(core); } }(commonjsGlobal, function(CryptoJS) { (function(Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var T = []; // Compute constants (function() { for (var i = 0; i < 64; i++) { T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; } }()); /** * MD5 hash algorithm. */ var MD5 = C_algo.MD5 = Hasher.extend({ _doReset: function() { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 ]); }, _doProcessBlock: function(M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcuts var H = this._hash.words; var M_offset_0 = M[offset + 0]; var M_offset_1 = M[offset + 1]; var M_offset_2 = M[offset + 2]; var M_offset_3 = M[offset + 3]; var M_offset_4 = M[offset + 4]; var M_offset_5 = M[offset + 5]; var M_offset_6 = M[offset + 6]; var M_offset_7 = M[offset + 7]; var M_offset_8 = M[offset + 8]; var M_offset_9 = M[offset + 9]; var M_offset_10 = M[offset + 10]; var M_offset_11 = M[offset + 11]; var M_offset_12 = M[offset + 12]; var M_offset_13 = M[offset + 13]; var M_offset_14 = M[offset + 14]; var M_offset_15 = M[offset + 15]; // Working varialbes var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; // Computation a = FF(a, b, c, d, M_offset_0, 7, T[0]); d = FF(d, a, b, c, M_offset_1, 12, T[1]); c = FF(c, d, a, b, M_offset_2, 17, T[2]); b = FF(b, c, d, a, M_offset_3, 22, T[3]); a = FF(a, b, c, d, M_offset_4, 7, T[4]); d = FF(d, a, b, c, M_offset_5, 12, T[5]); c = FF(c, d, a, b, M_offset_6, 17, T[6]); b = FF(b, c, d, a, M_offset_7, 22, T[7]); a = FF(a, b, c, d, M_offset_8, 7, T[8]); d = FF(d, a, b, c, M_offset_9, 12, T[9]); c = FF(c, d, a, b, M_offset_10, 17, T[10]); b = FF(b, c, d, a, M_offset_11, 22, T[11]); a = FF(a, b, c, d, M_offset_12, 7, T[12]); d = FF(d, a, b, c, M_offset_13, 12, T[13]); c = FF(c, d, a, b, M_offset_14, 17, T[14]); b = FF(b, c, d, a, M_offset_15, 22, T[15]); a = GG(a, b, c, d, M_offset_1, 5, T[16]); d = GG(d, a, b, c, M_offset_6, 9, T[17]); c = GG(c, d, a, b, M_offset_11, 14, T[18]); b = GG(b, c, d, a, M_offset_0, 20, T[19]); a = GG(a, b, c, d, M_offset_5, 5, T[20]); d = GG(d, a, b, c, M_offset_10, 9, T[21]); c = GG(c, d, a, b, M_offset_15, 14, T[22]); b = GG(b, c, d, a, M_offset_4, 20, T[23]); a = GG(a, b, c, d, M_offset_9, 5, T[24]); d = GG(d, a, b, c, M_offset_14, 9, T[25]); c = GG(c, d, a, b, M_offset_3, 14, T[26]); b = GG(b, c, d, a, M_offset_8, 20, T[27]); a = GG(a, b, c, d, M_offset_13, 5, T[28]); d = GG(d, a, b, c, M_offset_2, 9, T[29]); c = GG(c, d, a, b, M_offset_7, 14, T[30]); b = GG(b, c, d, a, M_offset_12, 20, T[31]); a = HH(a, b, c, d, M_offset_5, 4, T[32]); d = HH(d, a, b, c, M_offset_8, 11, T[33]); c = HH(c, d, a, b, M_offset_11, 16, T[34]); b = HH(b, c, d, a, M_offset_14, 23, T[35]); a = HH(a, b, c, d, M_offset_1, 4, T[36]); d = HH(d, a, b, c, M_offset_4, 11, T[37]); c = HH(c, d, a, b, M_offset_7, 16, T[38]); b = HH(b, c, d, a, M_offset_10, 23, T[39]); a = HH(a, b, c, d, M_offset_13, 4, T[40]); d = HH(d, a, b, c, M_offset_0, 11, T[41]); c = HH(c, d, a, b, M_offset_3, 16, T[42]); b = HH(b, c, d, a, M_offset_6, 23, T[43]); a = HH(a, b, c, d, M_offset_9, 4, T[44]); d = HH(d, a, b, c, M_offset_12, 11, T[45]); c = HH(c, d, a, b, M_offset_15, 16, T[46]); b = HH(b, c, d, a, M_offset_2, 23, T[47]); a = II(a, b, c, d, M_offset_0, 6, T[48]); d = II(d, a, b, c, M_offset_7, 10, T[49]); c = II(c, d, a, b, M_offset_14, 15, T[50]); b = II(b, c, d, a, M_offset_5, 21, T[51]); a = II(a, b, c, d, M_offset_12, 6, T[52]); d = II(d, a, b, c, M_offset_3, 10, T[53]); c = II(c, d, a, b, M_offset_10, 15, T[54]); b = II(b, c, d, a, M_offset_1, 21, T[55]); a = II(a, b, c, d, M_offset_8, 6, T[56]); d = II(d, a, b, c, M_offset_15, 10, T[57]); c = II(c, d, a, b, M_offset_6, 15, T[58]); b = II(b, c, d, a, M_offset_13, 21, T[59]); a = II(a, b, c, d, M_offset_4, 6, T[60]); d = II(d, a, b, c, M_offset_11, 10, T[61]); c = II(c, d, a, b, M_offset_2, 15, T[62]); b = II(b, c, d, a, M_offset_9, 21, T[63]); // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; }, _doFinalize: function() { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); var nBitsTotalL = nBitsTotal; dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) ); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 4; i++) { // Shortcut var H_i = H[i]; H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function() { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function FF(a, b, c, d, x, s, t) { var n = a + ((b & c) | (~b & d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function GG(a, b, c, d, x, s, t) { var n = a + ((b & d) | (c & ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function HH(a, b, c, d, x, s, t) { var n = a + (b ^ c ^ d) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function II(a, b, c, d, x, s, t) { var n = a + (c ^ (b | ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.MD5('message'); * var hash = CryptoJS.MD5(wordArray); */ C.MD5 = Hasher._createHelper(MD5); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacMD5(message, key); */ C.HmacMD5 = Hasher._createHmacHelper(MD5); }(Math)); return CryptoJS.MD5; })); }); /** * Digest Authentication. * @internal */ class DigestAuthentication { /** * Constructor. * @param loggerFactory - LoggerFactory. * @param username - Username. * @param password - Password. */ constructor(loggerFactory, username, password) { this.logger = loggerFactory.getLogger("sipjs.digestauthentication"); this.username = username; this.password = password; this.nc = 0; this.ncHex = "00000000"; } /** * Performs Digest authentication given a SIP request and the challenge * received in a response to that request. * @param request - * @param challenge - * @returns true if credentials were successfully generated, false otherwise. */ authenticate(request, challenge, body) { // Inspect and validate the challenge. this.algorithm = challenge.algorithm; this.realm = challenge.realm; this.nonce = challenge.nonce; this.opaque = challenge.opaque; this.stale = challenge.stale; if (this.algorithm) { if (this.algorithm !== "MD5") { this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"); return false; } } else { this.algorithm = "MD5"; } if (!this.realm) { this.logger.warn("challenge without Digest realm, authentication aborted"); return false; } if (!this.nonce) { this.logger.warn("challenge without Digest nonce, authentication aborted"); return false; } // 'qop' can contain a list of values (Array). Let's choose just one. if (challenge.qop) { if (challenge.qop.indexOf("auth") > -1) { this.qop = "auth"; } else if (challenge.qop.indexOf("auth-int") > -1) { this.qop = "auth-int"; } else { // Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here. this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"); return false; } } else { this.qop = undefined; } // Fill other attributes. this.method = request.method; this.uri = request.ruri; this.cnonce = createRandomToken(12); this.nc += 1; this.updateNcHex(); // nc-value = 8LHEX. Max value = 'FFFFFFFF'. if (this.nc === 4294967296) { this.nc = 1; this.ncHex = "00000001"; } // Calculate the Digest "response" value. this.calculateResponse(body); return true; } /** * Return the Proxy-Authorization or WWW-Authorization header value. */ toString() { const authParams = []; if (!this.response) { throw new Error("response field does not exist, cannot generate Authorization header"); } authParams.push("algorithm=" + this.algorithm); authParams.push('username="' + this.username + '"'); authParams.push('realm="' + this.realm + '"'); authParams.push('nonce="' + this.nonce + '"'); authParams.push('uri="' + this.uri + '"'); authParams.push('response="' + this.response + '"'); if (this.opaque) { authParams.push('opaque="' + this.opaque + '"'); } if (this.qop) { authParams.push("qop=" + this.qop); authParams.push('cnonce="' + this.cnonce + '"'); authParams.push("nc=" + this.ncHex); } return "Digest " + authParams.join(", "); } /** * Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc. */ updateNcHex() { const hex = Number(this.nc).toString(16); this.ncHex = "00000000".substr(0, 8 - hex.length) + hex; } /** * Generate Digest 'response' value. */ calculateResponse(body) { let ha2; // HA1 = MD5(A1) = MD5(username:realm:password) const ha1 = md5(this.username + ":" + this.realm + ":" + this.password); if (this.qop === "auth") { // HA2 = MD5(A2) = MD5(method:digestURI) ha2 = md5(this.method + ":" + this.uri); // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) this.response = md5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth:" + ha2); } else if (this.qop === "auth-int") { // HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody)) ha2 = md5(this.method + ":" + this.uri + ":" + md5(body ? body : "")); // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) this.response = md5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth-int:" + ha2); } else if (this.qop === undefined) { // HA2 = MD5(A2) = MD5(method:digestURI) ha2 = md5(this.method + ":" + this.uri); // response = MD5(HA1:nonce:HA2) this.response = md5(ha1 + ":" + this.nonce + ":" + ha2); } } } /** * When a UAS wishes to construct a response to a request, it follows * the general procedures detailed in the following subsections. * Additional behaviors specific to the response code in question, which * are not detailed in this section, may also be required. * https://tools.ietf.org/html/rfc3261#section-8.2.6 * @internal */ function constructOutgoingResponse(message, options) { const CRLF = "\r\n"; if (options.statusCode < 100 || options.statusCode > 699) { throw new TypeError("Invalid statusCode: " + options.statusCode); } const reasonPhrase = options.reasonPhrase ? options.reasonPhrase : getReasonPhrase(options.statusCode); // SIP responses are distinguished from requests by having a Status-Line // as their start-line. A Status-Line consists of the protocol version // followed by a numeric Status-Code and its associated textual phrase, // with each element separated by a single SP character. // https://tools.ietf.org/html/rfc3261#section-7.2 let response = "SIP/2.0 " + options.statusCode + " " + reasonPhrase + CRLF; // One largely non-method-specific guideline for the generation of // responses is that UASs SHOULD NOT issue a provisional response for a // non-INVITE request. Rather, UASs SHOULD generate a final response to // a non-INVITE request as soon as possible. // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 if (options.statusCode >= 100 && options.statusCode < 200); // When a 100 (Trying) response is generated, any Timestamp header field // present in the request MUST be copied into this 100 (Trying) // response. If there is a delay in generating the response, the UAS // SHOULD add a delay value into the Timestamp value in the response. // This value MUST contain the difference between the time of sending of // the response and receipt of the request, measured in seconds. // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 if (options.statusCode === 100); // The From field of the response MUST equal the From header field of // the request. The Call-ID header field of the response MUST equal the // Call-ID header field of the request. The CSeq header field of the // response MUST equal the CSeq field of the request. The Via header // field values in the response MUST equal the Via header field values // in the request and MUST maintain the same ordering. // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 const fromHeader = "From: " + message.getHeader("From") + CRLF; const callIdHeader = "Call-ID: " + message.callId + CRLF; const cSeqHeader = "CSeq: " + message.cseq + " " + message.method + CRLF; const viaHeaders = message.getHeaders("via").reduce((previous, current) => { return previous + "Via: " + current + CRLF; }, ""); // If a request contained a To tag in the request, the To header field // in the response MUST equal that of the request. However, if the To // header field in the request did not contain a tag, the URI in the To // header field in the response MUST equal the URI in the To header // field; additionally, the UAS MUST add a tag to the To header field in // the response (with the exception of the 100 (Trying) response, in // which a tag MAY be present). This serves to identify the UAS that is // responding, possibly resulting in a component of a dialog ID. The // same tag MUST be used for all responses to that request, both final // and provisional (again excepting the 100 (Trying)). // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 let toHeader = "To: " + message.getHeader("to"); if (options.statusCode > 100 && !message.parseHeader("to").hasParam("tag")) { let toTag = options.toTag; if (!toTag) { // Stateless UAS Behavior... // o To header tags MUST be generated for responses in a stateless // manner - in a manner that will generate the same tag for the // same request consistently. For information on tag construction // see Section 19.3. // https://tools.ietf.org/html/rfc3261#section-8.2.7 toTag = newTag(); // FIXME: newTag() currently generates random tags } toHeader += ";tag=" + toTag; } toHeader += CRLF; // FIXME: TODO: needs review... moved to InviteUserAgentServer (as it is specific to that) // let recordRouteHeaders = ""; // if (request.method === C.INVITE && statusCode > 100 && statusCode <= 200) { // recordRouteHeaders = request.getHeaders("record-route").reduce((previous, current) => { // return previous + "Record-Route: " + current + CRLF; // }, ""); // } // FIXME: TODO: needs review... let supportedHeader = ""; if (options.supported) { supportedHeader = "Supported: " + options.supported.join(", ") + CRLF; } // FIXME: TODO: needs review... let userAgentHeader = ""; if (options.userAgent) { userAgentHeader = "User-Agent: " + options.userAgent + CRLF; } let extensionHeaders = ""; if (options.extraHeaders) { extensionHeaders = options.extraHeaders.reduce((previous, current) => { return previous + current.trim() + CRLF; }, ""); } // The relative order of header fields with different field names is not // significant. However, it is RECOMMENDED that header fields which are // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, // Max-Forwards, and Proxy-Authorization, for example) appear towards // the top of the message to facilitate rapid parsing. // https://tools.ietf.org/html/rfc3261#section-7.3.1 // response += recordRouteHeaders; response += viaHeaders; response += fromHeader; response += toHeader; response += cSeqHeader; response += callIdHeader; response += supportedHeader; response += userAgentHeader; response += extensionHeaders; if (options.body) { response += "Content-Type: " + options.body.contentType + CRLF; response += "Content-Length: " + str_utf8_length(options.body.content) + CRLF + CRLF; response += options.body.content; } else { response += "Content-Length: " + 0 + CRLF + CRLF; } return { message: response }; } /** * Extract and parse every header of a SIP message. * @internal */ var Parser; (function(Parser) { function getHeader(data, headerStart) { // 'start' position of the header. let start = headerStart; // 'end' position of the header. let end = 0; // 'partial end' position of the header. let partialEnd = 0; // End of message. if (data.substring(start, start + 2).match(/(^\r\n)/)) { return -2; } while (end === 0) { // Partial End of Header. partialEnd = data.indexOf("\r\n", start); // 'indexOf' returns -1 if the value to be found never occurs. if (partialEnd === -1) { return partialEnd; } if (!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && data.charAt(partialEnd + 2).match(/(^\s+)/)) { // Not the end of the message. Continue from the next position. start = partialEnd + 2; } else { end = partialEnd; } } return end; } Parser.getHeader = getHeader; function parseHeader(message, data, headerStart, headerEnd) { const hcolonIndex = data.indexOf(":", headerStart); const headerName = data.substring(headerStart, hcolonIndex).trim(); const headerValue = data.substring(hcolonIndex + 1, headerEnd).trim(); let parsed; // If header-field is well-known, parse it. switch (headerName.toLowerCase()) { case "via": case "v": message.addHeader("via", headerValue); if (message.getHeaders("via").length === 1) { parsed = message.parseHeader("Via"); if (parsed) { message.via = parsed; message.viaBranch = parsed.branch; } } else { parsed = 0; } break; case "from": case "f": message.setHeader("from", headerValue); parsed = message.parseHeader("from"); if (parsed) { message.from = parsed; message.fromTag = parsed.getParam("tag"); } break; case "to": case "t": message.setHeader("to", headerValue); parsed = message.parseHeader("to"); if (parsed) { message.to = parsed; message.toTag = parsed.getParam("tag"); } break; case "record-route": parsed = Grammar.parse(headerValue, "Record_Route"); if (parsed === -1) { parsed = undefined; break; } if (!(parsed instanceof Array)) { parsed = undefined; break; } parsed.forEach((header) => { message.addHeader("record-route", headerValue.substring(header.position, header.offset)); message.headers["Record-Route"][message.getHeaders("record-route").length - 1].parsed = header.parsed; }); break; case "call-id": case "i": message.setHeader("call-id", headerValue); parsed = message.parseHeader("call-id"); if (parsed) { message.callId = headerValue; } break; case "contact": case "m": parsed = Grammar.parse(headerValue, "Contact"); if (parsed === -1) { parsed = undefined; break; } if (!(parsed instanceof Array)) { parsed = undefined; break; } parsed.forEach((header) => { message.addHeader("contact", headerValue.substring(header.position, header.offset)); message.headers.Contact[message.getHeaders("contact").length - 1].parsed = header.parsed; }); break; case "content-length": case "l": message.setHeader("content-length", headerValue); parsed = message.parseHeader("content-length"); break; case "content-type": case "c": message.setHeader("content-type", headerValue); parsed = message.parseHeader("content-type"); break; case "cseq": message.setHeader("cseq", headerValue); parsed = message.parseHeader("cseq"); if (parsed) { message.cseq = parsed.value; } if (message instanceof IncomingResponseMessage) { message.method = parsed.method; } break; case "max-forwards": message.setHeader("max-forwards", headerValue); parsed = message.parseHeader("max-forwards"); break; case "www-authenticate": message.setHeader("www-authenticate", headerValue); parsed = message.parseHeader("www-authenticate"); break; case "proxy-authenticate": message.setHeader("proxy-authenticate", headerValue); parsed = message.parseHeader("proxy-authenticate"); break; case "refer-to": case "r": message.setHeader("refer-to", headerValue); parsed = message.parseHeader("refer-to"); if (parsed) { message.referTo = parsed; } break; default: // Do not parse this header. message.addHeader(headerName.toLowerCase(), headerValue); parsed = 0; } if (parsed === undefined) { return { error: "error parsing header '" + headerName + "'" }; } else { return true; } } Parser.parseHeader = parseHeader; function parseMessage(data, logger) { let headerStart = 0; let headerEnd = data.indexOf("\r\n"); if (headerEnd === -1) { logger.warn("no CRLF found, not a SIP message, discarded"); return; } // Parse first line. Check if it is a Request or a Reply. const firstLine = data.substring(0, headerEnd); const parsed = Grammar.parse(firstLine, "Request_Response"); let message; if (parsed === -1) { logger.warn('error parsing first line of SIP message: "' + firstLine + '"'); return; } else if (!parsed.status_code) { message = new IncomingRequestMessage(); message.method = parsed.method; message.ruri = parsed.uri; } else { message = new IncomingResponseMessage(); message.statusCode = parsed.status_code; message.reasonPhrase = parsed.reason_phrase; } message.data = data; headerStart = headerEnd + 2; // Loop over every line in data. Detect the end of each header and parse // it or simply add to the headers collection. let bodyStart; while (true) { headerEnd = getHeader(data, headerStart); // The SIP message has normally finished. if (headerEnd === -2) { bodyStart = headerStart + 2; break; } else if (headerEnd === -1) { // data.indexOf returned -1 due to a malformed message. logger.error("malformed message"); return; } const parsedHeader = parseHeader(message, data, headerStart, headerEnd); if (parsedHeader !== true) { logger.error(parsed.error); return; } headerStart = headerEnd + 2; } // RFC3261 18.3. // If there are additional bytes in the transport packet // beyond the end of the body, they MUST be discarded. if (message.hasHeader("content-length")) { message.body = data.substr(bodyStart, Number(message.getHeader("content-length"))); } else { message.body = data.substring(bodyStart); } return message; } Parser.parseMessage = parseMessage; })(Parser || (Parser = {})); /** * Dialog. * @remarks * A key concept for a user agent is that of a dialog. A dialog * represents a peer-to-peer SIP relationship between two user agents * that persists for some time. The dialog facilitates sequencing of * messages between the user agents and proper routing of requests * between both of them. The dialog represents a context in which to * interpret SIP messages. * https://tools.ietf.org/html/rfc3261#section-12 * @public */ class Dialog { /** * Dialog constructor. * @param core - User agent core. * @param dialogState - Initial dialog state. */ constructor(core, dialogState) { this.core = core; this.dialogState = dialogState; this.core.dialogs.set(this.id, this); } /** * When a UAC receives a response that establishes a dialog, it * constructs the state of the dialog. This state MUST be maintained * for the duration of the dialog. * https://tools.ietf.org/html/rfc3261#section-12.1.2 * @param outgoingRequestMessage - Outgoing request message for dialog. * @param incomingResponseMessage - Incoming response message creating dialog. */ static initialDialogStateForUserAgentClient(outgoingRequestMessage, incomingResponseMessage) { // If the request was sent over TLS, and the Request-URI contained a // SIPS URI, the "secure" flag is set to TRUE. // https://tools.ietf.org/html/rfc3261#section-12.1.2 const secure = false; // FIXME: Currently no support for TLS. // The route set MUST be set to the list of URIs in the Record-Route // header field from the response, taken in reverse order and preserving // all URI parameters. If no Record-Route header field is present in // the response, the route set MUST be set to the empty set. This route // set, even if empty, overrides any pre-existing route set for future // requests in this dialog. The remote target MUST be set to the URI // from the Contact header field of the response. // https://tools.ietf.org/html/rfc3261#section-12.1.2 const routeSet = incomingResponseMessage.getHeaders("record-route").reverse(); const contact = incomingResponseMessage.parseHeader("contact"); if (!contact) { // TODO: Review to make sure this will never happen throw new Error("Contact undefined."); } if (!(contact instanceof NameAddrHeader)) { throw new Error("Contact not instance of NameAddrHeader."); } const remoteTarget = contact.uri; // The local sequence number MUST be set to the value of the sequence // number in the CSeq header field of the request. The remote sequence // number MUST be empty (it is established when the remote UA sends a // request within the dialog). The call identifier component of the // dialog ID MUST be set to the value of the Call-ID in the request. // The local tag component of the dialog ID MUST be set to the tag in // the From field in the request, and the remote tag component of the // dialog ID MUST be set to the tag in the To field of the response. A // UAC MUST be prepared to receive a response without a tag in the To // field, in which case the tag is considered to have a value of null. // // This is to maintain backwards compatibility with RFC 2543, which // did not mandate To tags. // // https://tools.ietf.org/html/rfc3261#section-12.1.2 const localSequenceNumber = outgoingRequestMessage.cseq; const remoteSequenceNumber = undefined; const callId = outgoingRequestMessage.callId; const localTag = outgoingRequestMessage.fromTag; const remoteTag = incomingResponseMessage.toTag; if (!callId) { // TODO: Review to make sure this will never happen throw new Error("Call id undefined."); } if (!localTag) { // TODO: Review to make sure this will never happen throw new Error("From tag undefined."); } if (!remoteTag) { // TODO: Review to make sure this will never happen throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 } // The remote URI MUST be set to the URI in the To field, and the local // URI MUST be set to the URI in the From field. // https://tools.ietf.org/html/rfc3261#section-12.1.2 if (!outgoingRequestMessage.from) { // TODO: Review to make sure this will never happen throw new Error("From undefined."); } if (!outgoingRequestMessage.to) { // TODO: Review to make sure this will never happen throw new Error("To undefined."); } const localURI = outgoingRequestMessage.from.uri; const remoteURI = outgoingRequestMessage.to.uri; // A dialog can also be in the "early" state, which occurs when it is // created with a provisional response, and then transition to the // "confirmed" state when a 2xx final response arrives. // https://tools.ietf.org/html/rfc3261#section-12 if (!incomingResponseMessage.statusCode) { throw new Error("Incoming response status code undefined."); } const early = incomingResponseMessage.statusCode < 200 ? true : false; const dialogState = { id: callId + localTag + remoteTag, early, callId, localTag, remoteTag, localSequenceNumber, remoteSequenceNumber, localURI, remoteURI, remoteTarget, routeSet, secure }; return dialogState; } /** * The UAS then constructs the state of the dialog. This state MUST be * maintained for the duration of the dialog. * https://tools.ietf.org/html/rfc3261#section-12.1.1 * @param incomingRequestMessage - Incoming request message creating dialog. * @param toTag - Tag in the To field in the response to the incoming request. */ static initialDialogStateForUserAgentServer(incomingRequestMessage, toTag, early = false) { // If the request arrived over TLS, and the Request-URI contained a SIPS // URI, the "secure" flag is set to TRUE. // https://tools.ietf.org/html/rfc3261#section-12.1.1 const secure = false; // FIXME: Currently no support for TLS. // The route set MUST be set to the list of URIs in the Record-Route // header field from the request, taken in order and preserving all URI // parameters. If no Record-Route header field is present in the // request, the route set MUST be set to the empty set. This route set, // even if empty, overrides any pre-existing route set for future // requests in this dialog. The remote target MUST be set to the URI // from the Contact header field of the request. // https://tools.ietf.org/html/rfc3261#section-12.1.1 const routeSet = incomingRequestMessage.getHeaders("record-route"); const contact = incomingRequestMessage.parseHeader("contact"); if (!contact) { // TODO: Review to make sure this will never happen throw new Error("Contact undefined."); } if (!(contact instanceof NameAddrHeader)) { throw new Error("Contact not instance of NameAddrHeader."); } const remoteTarget = contact.uri; // The remote sequence number MUST be set to the value of the sequence // number in the CSeq header field of the request. The local sequence // number MUST be empty. The call identifier component of the dialog ID // MUST be set to the value of the Call-ID in the request. The local // tag component of the dialog ID MUST be set to the tag in the To field // in the response to the request (which always includes a tag), and the // remote tag component of the dialog ID MUST be set to the tag from the // From field in the request. A UAS MUST be prepared to receive a // request without a tag in the From field, in which case the tag is // considered to have a value of null. // // This is to maintain backwards compatibility with RFC 2543, which // did not mandate From tags. // // https://tools.ietf.org/html/rfc3261#section-12.1.1 const remoteSequenceNumber = incomingRequestMessage.cseq; const localSequenceNumber = undefined; const callId = incomingRequestMessage.callId; const localTag = toTag; const remoteTag = incomingRequestMessage.fromTag; // The remote URI MUST be set to the URI in the From field, and the // local URI MUST be set to the URI in the To field. // https://tools.ietf.org/html/rfc3261#section-12.1.1 const remoteURI = incomingRequestMessage.from.uri; const localURI = incomingRequestMessage.to.uri; const dialogState = { id: callId + localTag + remoteTag, early, callId, localTag, remoteTag, localSequenceNumber, remoteSequenceNumber, localURI, remoteURI, remoteTarget, routeSet, secure }; return dialogState; } /** Destructor. */ dispose() { this.core.dialogs.delete(this.id); } /** * A dialog is identified at each UA with a dialog ID, which consists of * a Call-ID value, a local tag and a remote tag. The dialog ID at each * UA involved in the dialog is not the same. Specifically, the local * tag at one UA is identical to the remote tag at the peer UA. The * tags are opaque tokens that facilitate the generation of unique * dialog IDs. * https://tools.ietf.org/html/rfc3261#section-12 */ get id() { return this.dialogState.id; } /** * A dialog can also be in the "early" state, which occurs when it is * created with a provisional response, and then it transition to the * "confirmed" state when a 2xx final response received or is sent. * * Note: RFC 3261 is concise on when a dialog is "confirmed", but it * can be a point of confusion if an INVITE dialog is "confirmed" after * a 2xx is sent or after receiving the ACK for the 2xx response. * With careful reading it can be inferred a dialog is always is * "confirmed" when the 2xx is sent (regardless of type of dialog). * However a INVITE dialog does have additional considerations * when it is confirmed but an ACK has not yet been received (in * particular with regard to a callee sending BYE requests). */ get early() { return this.dialogState.early; } /** Call identifier component of the dialog id. */ get callId() { return this.dialogState.callId; } /** Local tag component of the dialog id. */ get localTag() { return this.dialogState.localTag; } /** Remote tag component of the dialog id. */ get remoteTag() { return this.dialogState.remoteTag; } /** Local sequence number (used to order requests from the UA to its peer). */ get localSequenceNumber() { return this.dialogState.localSequenceNumber; } /** Remote sequence number (used to order requests from its peer to the UA). */ get remoteSequenceNumber() { return this.dialogState.remoteSequenceNumber; } /** Local URI. */ get localURI() { return this.dialogState.localURI; } /** Remote URI. */ get remoteURI() { return this.dialogState.remoteURI; } /** Remote target. */ get remoteTarget() { return this.dialogState.remoteTarget; } /** * Route set, which is an ordered list of URIs. The route set is the * list of servers that need to be traversed to send a request to the peer. */ get routeSet() { return this.dialogState.routeSet; } /** * If the request was sent over TLS, and the Request-URI contained * a SIPS URI, the "secure" flag is set to true. *NOT IMPLEMENTED* */ get secure() { return this.dialogState.secure; } /** The user agent core servicing this dialog. */ get userAgentCore() { return this.core; } /** Confirm the dialog. Only matters if dialog is currently early. */ confirm() { this.dialogState.early = false; } /** * Requests sent within a dialog, as any other requests, are atomic. If * a particular request is accepted by the UAS, all the state changes * associated with it are performed. If the request is rejected, none * of the state changes are performed. * * Note that some requests, such as INVITEs, affect several pieces of * state. * * https://tools.ietf.org/html/rfc3261#section-12.2.2 * @param message - Incoming request message within this dialog. */ receiveRequest(message) { // ACK guard. // By convention, the handling of ACKs is the responsibility // the particular dialog implementation. For example, see SessionDialog. // Furthermore, ACKs have same sequence number as the associated INVITE. if (message.method === C.ACK) { return; } // If the remote sequence number was not empty, but the sequence number // of the request is lower than the remote sequence number, the request // is out of order and MUST be rejected with a 500 (Server Internal // Error) response. If the remote sequence number was not empty, and // the sequence number of the request is greater than the remote // sequence number, the request is in order. It is possible for the // CSeq sequence number to be higher than the remote sequence number by // more than one. This is not an error condition, and a UAS SHOULD be // prepared to receive and process requests with CSeq values more than // one higher than the previous received request. The UAS MUST then set // the remote sequence number to the value of the sequence number in the // CSeq header field value in the request. // // If a proxy challenges a request generated by the UAC, the UAC has // to resubmit the request with credentials. The resubmitted request // will have a new CSeq number. The UAS will never see the first // request, and thus, it will notice a gap in the CSeq number space. // Such a gap does not represent any error condition. // // https://tools.ietf.org/html/rfc3261#section-12.2.2 if (this.remoteSequenceNumber) { if (message.cseq <= this.remoteSequenceNumber) { throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?"); } this.dialogState.remoteSequenceNumber = message.cseq; } // If the remote sequence number is empty, it MUST be set to the value // of the sequence number in the CSeq header field value in the request. // https://tools.ietf.org/html/rfc3261#section-12.2.2 if (!this.remoteSequenceNumber) { this.dialogState.remoteSequenceNumber = message.cseq; } // When a UAS receives a target refresh request, it MUST replace the // dialog's remote target URI with the URI from the Contact header field // in that request, if present. // https://tools.ietf.org/html/rfc3261#section-12.2.2 // Note: "target refresh request" processing delegated to sub-class. } /** * If the dialog identifier in the 2xx response matches the dialog * identifier of an existing dialog, the dialog MUST be transitioned to * the "confirmed" state, and the route set for the dialog MUST be * recomputed based on the 2xx response using the procedures of Section * 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be * constructed using the procedures of Section 12.1.2. * * Note that the only piece of state that is recomputed is the route * set. Other pieces of state such as the highest sequence numbers * (remote and local) sent within the dialog are not recomputed. The * route set only is recomputed for backwards compatibility. RFC * 2543 did not mandate mirroring of the Record-Route header field in * a 1xx, only 2xx. However, we cannot update the entire state of * the dialog, since mid-dialog requests may have been sent within * the early dialog, modifying the sequence numbers, for example. * * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 */ recomputeRouteSet(message) { this.dialogState.routeSet = message.getHeaders("record-route").reverse(); } /** * A request within a dialog is constructed by using many of the * components of the state stored as part of the dialog. * https://tools.ietf.org/html/rfc3261#section-12.2.1.1 * @param method - Outgoing request method. */ createOutgoingRequestMessage(method, options) { // The URI in the To field of the request MUST be set to the remote URI // from the dialog state. The tag in the To header field of the request // MUST be set to the remote tag of the dialog ID. The From URI of the // request MUST be set to the local URI from the dialog state. The tag // in the From header field of the request MUST be set to the local tag // of the dialog ID. If the value of the remote or local tags is null, // the tag parameter MUST be omitted from the To or From header fields, // respectively. // // Usage of the URI from the To and From fields in the original // request within subsequent requests is done for backwards // compatibility with RFC 2543, which used the URI for dialog // identification. In this specification, only the tags are used for // dialog identification. It is expected that mandatory reflection // of the original To and From URI in mid-dialog requests will be // deprecated in a subsequent revision of this specification. // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 const toUri = this.remoteURI; const toTag = this.remoteTag; const fromUri = this.localURI; const fromTag = this.localTag; // The Call-ID of the request MUST be set to the Call-ID of the dialog. // Requests within a dialog MUST contain strictly monotonically // increasing and contiguous CSeq sequence numbers (increasing-by-one) // in each direction (excepting ACK and CANCEL of course, whose numbers // equal the requests being acknowledged or cancelled). Therefore, if // the local sequence number is not empty, the value of the local // sequence number MUST be incremented by one, and this value MUST be // placed into the CSeq header field. If the local sequence number is // empty, an initial value MUST be chosen using the guidelines of // Section 8.1.1.5. The method field in the CSeq header field value // MUST match the method of the request. // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 const callId = this.callId; let cseq; if (options && options.cseq) { cseq = options.cseq; } else if (!this.dialogState.localSequenceNumber) { cseq = this.dialogState.localSequenceNumber = 1; // https://tools.ietf.org/html/rfc3261#section-8.1.1.5 } else { cseq = this.dialogState.localSequenceNumber += 1; } // The UAC uses the remote target and route set to build the Request-URI // and Route header field of the request. // // If the route set is empty, the UAC MUST place the remote target URI // into the Request-URI. The UAC MUST NOT add a Route header field to // the request. // // If the route set is not empty, and the first URI in the route set // contains the lr parameter (see Section 19.1.1), the UAC MUST place // the remote target URI into the Request-URI and MUST include a Route // header field containing the route set values in order, including all // parameters. // // If the route set is not empty, and its first URI does not contain the // lr parameter, the UAC MUST place the first URI from the route set // into the Request-URI, stripping any parameters that are not allowed // in a Request-URI. The UAC MUST add a Route header field containing // the remainder of the route set values in order, including all // parameters. The UAC MUST then place the remote target URI into the // Route header field as the last value. // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 // The lr parameter, when present, indicates that the element // responsible for this resource implements the routing mechanisms // specified in this document. This parameter will be used in the // URIs proxies place into Record-Route header field values, and // may appear in the URIs in a pre-existing route set. // // This parameter is used to achieve backwards compatibility with // systems implementing the strict-routing mechanisms of RFC 2543 // and the rfc2543bis drafts up to bis-05. An element preparing // to send a request based on a URI not containing this parameter // can assume the receiving element implements strict-routing and // reformat the message to preserve the information in the // Request-URI. // https://tools.ietf.org/html/rfc3261#section-19.1.1 // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). const ruri = this.remoteTarget; const routeSet = this.routeSet; const extraHeaders = options && options.extraHeaders; const body = options && options.body; // The relative order of header fields with different field names is not // significant. However, it is RECOMMENDED that header fields which are // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, // Max-Forwards, and Proxy-Authorization, for example) appear towards // the top of the message to facilitate rapid parsing. // https://tools.ietf.org/html/rfc3261#section-7.3.1 const message = this.userAgentCore.makeOutgoingRequestMessage(method, ruri, fromUri, toUri, { callId, cseq, fromTag, toTag, routeSet }, extraHeaders, body); return message; } /** * If the remote sequence number was not empty, but the sequence number * of the request is lower than the remote sequence number, the request * is out of order and MUST be rejected with a 500 (Server Internal * Error) response. * https://tools.ietf.org/html/rfc3261#section-12.2.2 * @param request - Incoming request to guard. * @returns True if the program execution is to continue in the branch in question. * Otherwise a 500 Server Internal Error was stateless sent and request processing must stop. */ sequenceGuard(message) { // ACK guard. // By convention, handling of unexpected ACKs is responsibility // the particular dialog implementation. For example, see SessionDialog. // Furthermore, we cannot reply to an "out of sequence" ACK. if (message.method === C.ACK) { return true; } // Note: We are rejecting on "less than or equal to" the remote // sequence number (excepting ACK whose numbers equal the requests // being acknowledged or cancelled), which is the correct thing to // do in our case. The only time a request with the same sequence number // will show up here if is a) it is a very late retransmission of a // request we already handled or b) it is a different request with the // same sequence number which would be violation of the standard. // Request retransmissions are absorbed by the transaction layer, // so any request with a duplicate sequence number getting here // would have to be a retransmission after the transaction terminated // or a broken request (with unique via branch value). // Requests within a dialog MUST contain strictly monotonically // increasing and contiguous CSeq sequence numbers (increasing-by-one) // in each direction (excepting ACK and CANCEL of course, whose numbers // equal the requests being acknowledged or cancelled). Therefore, if // the local sequence number is not empty, the value of the local // sequence number MUST be incremented by one, and this value MUST be // placed into the CSeq header field. // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 if (this.remoteSequenceNumber && message.cseq <= this.remoteSequenceNumber) { this.core.replyStateless(message, { statusCode: 500 }); return false; } return true; } } /** * Session state. * @remarks * https://tools.ietf.org/html/rfc3261#section-13 * @public */ var SessionState; (function(SessionState) { SessionState["Initial"] = "Initial"; SessionState["Early"] = "Early"; SessionState["AckWait"] = "AckWait"; SessionState["Confirmed"] = "Confirmed"; SessionState["Terminated"] = "Terminated"; })(SessionState || (SessionState = {})); /** * Offer/Answer state. * @remarks * ```txt * Offer Answer RFC Ini Est Early * ------------------------------------------------------------------- * 1. INVITE Req. 2xx INVITE Resp. RFC 3261 Y Y N * 2. 2xx INVITE Resp. ACK Req. RFC 3261 Y Y N * 3. INVITE Req. 1xx-rel INVITE Resp. RFC 3262 Y Y N * 4. 1xx-rel INVITE Resp. PRACK Req. RFC 3262 Y Y N * 5. PRACK Req. 200 PRACK Resp. RFC 3262 N Y Y * 6. UPDATE Req. 2xx UPDATE Resp. RFC 3311 N Y Y * * Table 1: Summary of SIP Usage of the Offer/Answer Model * ``` * https://tools.ietf.org/html/rfc6337#section-2.2 * @public */ var SignalingState; (function(SignalingState) { SignalingState["Initial"] = "Initial"; SignalingState["HaveLocalOffer"] = "HaveLocalOffer"; SignalingState["HaveRemoteOffer"] = "HaveRemoteOffer"; SignalingState["Stable"] = "Stable"; SignalingState["Closed"] = "Closed"; })(SignalingState || (SignalingState = {})); const T1 = 500; const T2 = 4000; const T4 = 5000; /** * Timers. * @public */ const Timers = { T1, T2, T4, TIMER_B: 64 * T1, TIMER_D: 0 * T1, TIMER_F: 64 * T1, TIMER_H: 64 * T1, TIMER_I: 0 * T4, TIMER_J: 0 * T1, TIMER_K: 0 * T4, TIMER_L: 64 * T1, TIMER_M: 64 * T1, TIMER_N: 64 * T1, PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1 }; /** * An Exception is considered a condition that a reasonable application may wish to catch. * An Error indicates serious problems that a reasonable application should not try to catch. * @public */ class Exception extends Error { constructor(message) { super(message); // 'Error' breaks prototype chain here Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain } } /** * Indicates that the operation could not be completed given the current transaction state. * @public */ class TransactionStateError extends Exception { constructor(message) { super(message ? message : "Transaction state error."); } } /** * Transport error. * @public */ class TransportError extends Exception { constructor(message) { super(message ? message : "Unspecified transport error."); } } /** * Transaction. * @remarks * SIP is a transactional protocol: interactions between components take * place in a series of independent message exchanges. Specifically, a * SIP transaction consists of a single request and any responses to * that request, which include zero or more provisional responses and * one or more final responses. In the case of a transaction where the * request was an INVITE (known as an INVITE transaction), the * transaction also includes the ACK only if the final response was not * a 2xx response. If the response was a 2xx, the ACK is not considered * part of the transaction. * https://tools.ietf.org/html/rfc3261#section-17 * @public */ class Transaction extends EventEmitter { constructor(_transport, _user, _id, _state, loggerCategory) { super(); this._transport = _transport; this._user = _user; this._id = _id; this._state = _state; this.logger = _user.loggerFactory.getLogger(loggerCategory, _id); this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`); } /** * Destructor. * Once the transaction is in the "terminated" state, it is destroyed * immediately and there is no need to call `dispose`. However, if a * transaction needs to be ended prematurely, the transaction user may * do so by calling this method (for example, perhaps the UA is shutting down). * No state transition will occur upon calling this method, all outstanding * transmission timers will be cancelled, and use of the transaction after * calling `dispose` is undefined. */ dispose() { this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`); } /** Transaction id. */ get id() { return this._id; } /** Transaction kind. Deprecated. */ get kind() { throw new Error("Invalid kind."); } /** Transaction state. */ get state() { return this._state; } /** Transaction transport. */ get transport() { return this._transport; } on(name, callback) { return super.on(name, callback); } logTransportError(error, message) { this.logger.error(error.message); this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`); this.logger.error(message); } /** * Pass message to transport for transmission. If transport fails, * the transaction user is notified by callback to onTransportError(). * @returns * Rejects with `TransportError` if transport fails. */ send(message) { return this.transport.send(message).catch((error) => { // If the transport rejects, it SHOULD reject with a TransportError. // But the transport may be external code, so we are careful // make sure we convert it to a TransportError if need be. if (error instanceof TransportError) { this.onTransportError(error); throw error; } let transportError; if (error && typeof error.message === "string") { transportError = new TransportError(error.message); } else { transportError = new TransportError(); } this.onTransportError(transportError); throw transportError; }); } setState(state) { this.logger.debug(`State change to "${state}" on ${this.typeToString()} with id ${this.id}.`); this._state = state; if (this._user.onStateChange) { this._user.onStateChange(state); } this.emit("stateChanged"); } typeToString() { return "UnknownType"; } } /** * Client Transaction. * @remarks * The client transaction provides its functionality through the * maintenance of a state machine. * * The TU communicates with the client transaction through a simple * interface. When the TU wishes to initiate a new transaction, it * creates a client transaction and passes it the SIP request to send * and an IP address, port, and transport to which to send it. The * client transaction begins execution of its state machine. Valid * responses are passed up to the TU from the client transaction. * https://tools.ietf.org/html/rfc3261#section-17.1 * @public */ class ClientTransaction extends Transaction { constructor(_request, transport, user, state, loggerCategory) { super(transport, user, ClientTransaction.makeId(_request), state, loggerCategory); this._request = _request; this.user = user; // The Via header field indicates the transport used for the transaction // and identifies the location where the response is to be sent. A Via // header field value is added only after the transport that will be // used to reach the next hop has been selected (which may involve the // usage of the procedures in [4]). // https://tools.ietf.org/html/rfc3261#section-8.1.1.7 // FIXME: Transport's server property is not typed (as of writing this). const scheme = transport.server && transport.server.scheme ? transport.server.scheme : undefined; _request.setViaHeader(this.id, scheme); } static makeId(request) { if (request.method === "CANCEL") { if (!request.branch) { throw new Error("Outgoing CANCEL request without a branch."); } return request.branch; } else { return "z9hG4bK" + Math.floor(Math.random() * 10000000); } } /** The outgoing request the transaction handling. */ get request() { return this._request; } /** * A 408 to non-INVITE will always arrive too late to be useful ([3]), * The client already has full knowledge of the timeout. The only * information this message would convey is whether or not the server * believed the transaction timed out. However, with the current design * of the NIT, a client cannot do anything with this knowledge. Thus, * the 408 is simply wasting network resources and contributes to the * response bombardment illustrated in [3]. * https://tools.ietf.org/html/rfc4320#section-4.1 */ onRequestTimeout() { if (this.user.onRequestTimeout) { this.user.onRequestTimeout(); } } } /** * Transaction state. * @public */ var TransactionState; (function(TransactionState) { TransactionState["Accepted"] = "Accepted"; TransactionState["Calling"] = "Calling"; TransactionState["Completed"] = "Completed"; TransactionState["Confirmed"] = "Confirmed"; TransactionState["Proceeding"] = "Proceeding"; TransactionState["Terminated"] = "Terminated"; TransactionState["Trying"] = "Trying"; })(TransactionState || (TransactionState = {})); /** * INVITE Client Transaction. * @remarks * The INVITE transaction consists of a three-way handshake. The client * transaction sends an INVITE, the server transaction sends responses, * and the client transaction sends an ACK. * https://tools.ietf.org/html/rfc3261#section-17.1.1 * @public */ class InviteClientTransaction extends ClientTransaction { /** * Constructor. * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. * Then `toString` is called on the outgoing request and the message is sent via the transport. * After construction the transaction will be in the "calling" state and the transaction id * will equal the branch parameter set in the Via header of the outgoing request. * https://tools.ietf.org/html/rfc3261#section-17.1.1 * @param request - The outgoing INVITE request. * @param transport - The transport. * @param user - The transaction user. */ constructor(request, transport, user) { super(request, transport, user, TransactionState.Calling, "sip.transaction.ict"); /** * Map of 2xx to-tag to ACK. * If value is not undefined, value is the ACK which was sent. * If key exists but value is undefined, a 2xx was received but the ACK not yet sent. * Otherwise, a 2xx was not (yet) received for this transaction. */ this.ackRetransmissionCache = new Map(); // FIXME: Timer A for unreliable transport not implemented // // If an unreliable transport is being used, the client transaction // MUST start timer A with a value of T1. If a reliable transport is being used, // the client transaction SHOULD NOT start timer A (Timer A controls request retransmissions). // For any transport, the client transaction MUST start timer B with a value // of 64*T1 seconds (Timer B controls transaction timeouts). // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 // // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender // will wait for an INVITE message to be acknowledged (a SIP response message is received). // So Timer B should be cleared when the transaction state proceeds from "Calling". this.B = setTimeout(() => this.timer_B(), Timers.TIMER_B); this.send(request.toString()).catch((error) => { this.logTransportError(error, "Failed to send initial outgoing request."); }); } /** * Destructor. */ dispose() { if (this.B) { clearTimeout(this.B); this.B = undefined; } if (this.D) { clearTimeout(this.D); this.D = undefined; } if (this.M) { clearTimeout(this.M); this.M = undefined; } super.dispose(); } /** Transaction kind. Deprecated. */ get kind() { return "ict"; } /** * ACK a 2xx final response. * * The transaction includes the ACK only if the final response was not a 2xx response (the * transaction will generate and send the ACK to the transport automagically). If the * final response was a 2xx, the ACK is not considered part of the transaction (the * transaction user needs to generate and send the ACK). * * This library is not strictly RFC compliant with regard to ACK handling for 2xx final * responses. Specifically, retransmissions of ACKs to a 2xx final responses is handled * by the transaction layer (instead of the UAC core). The "standard" approach is for * the UAC core to receive all 2xx responses and manage sending ACK retransmissions to * the transport directly. Herein the transaction layer manages sending ACKs to 2xx responses * and any retransmissions of those ACKs as needed. * * @param ack - The outgoing ACK request. */ ackResponse(ack) { const toTag = ack.toTag; if (!toTag) { throw new Error("To tag undefined."); } const id = "z9hG4bK" + Math.floor(Math.random() * 10000000); // FIXME: Transport's server property is not typed (as of writing this). const scheme = this.transport.server && this.transport.server.scheme ? this.transport.server.scheme : undefined; ack.setViaHeader(id, scheme); this.ackRetransmissionCache.set(toTag, ack); // Add to ACK retransmission cache this.send(ack.toString()).catch((error) => { this.logTransportError(error, "Failed to send ACK to 2xx response."); }); } /** * Handler for incoming responses from the transport which match this transaction. * @param response - The incoming response. */ receiveResponse(response) { const statusCode = response.statusCode; if (!statusCode || statusCode < 100 || statusCode > 699) { throw new Error(`Invalid status code ${statusCode}`); } switch (this.state) { case TransactionState.Calling: // If the client transaction receives a provisional response while in // the "Calling" state, it transitions to the "Proceeding" state. In the // "Proceeding" state, the client transaction SHOULD NOT retransmit the // request any longer. Furthermore, the provisional response MUST be // passed to the TU. Any further provisional responses MUST be passed // up to the TU while in the "Proceeding" state. // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 if (statusCode >= 100 && statusCode <= 199) { this.stateTransition(TransactionState.Proceeding); if (this.user.receiveResponse) { this.user.receiveResponse(response); } return; } // When a 2xx response is received while in either the "Calling" or // "Proceeding" states, the client transaction MUST transition to // the "Accepted" state... The 2xx response MUST be passed up to the TU. // The client transaction MUST NOT generate an ACK to the 2xx response -- its // handling is delegated to the TU. A UAC core will send an ACK to // the 2xx response using a new transaction. // https://tools.ietf.org/html/rfc6026#section-8.4 if (statusCode >= 200 && statusCode <= 299) { this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache this.stateTransition(TransactionState.Accepted); if (this.user.receiveResponse) { this.user.receiveResponse(response); } return; } // When in either the "Calling" or "Proceeding" states, reception of // a response with status code from 300-699 MUST cause the client // transaction to transition to "Completed". The client transaction // MUST pass the received response up to the TU, and the client // transaction MUST generate an ACK request, even if the transport is // reliable (guidelines for constructing the ACK from the response // are given in Section 17.1.1.3), and then pass the ACK to the // transport layer for transmission. The ACK MUST be sent to the // same address, port, and transport to which the original request was sent. // https://tools.ietf.org/html/rfc6026#section-8.4 if (statusCode >= 300 && statusCode <= 699) { this.stateTransition(TransactionState.Completed); this.ack(response); if (this.user.receiveResponse) { this.user.receiveResponse(response); } return; } break; case TransactionState.Proceeding: // In the "Proceeding" state, the client transaction SHOULD NOT retransmit the // request any longer. Furthermore, the provisional response MUST be // passed to the TU. Any further provisional responses MUST be passed // up to the TU while in the "Proceeding" state. // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 if (statusCode >= 100 && statusCode <= 199) { if (this.user.receiveResponse) { this.user.receiveResponse(response); } return; } // When a 2xx response is received while in either the "Calling" or "Proceeding" states, // the client transaction MUST transition to the "Accepted" state... // The 2xx response MUST be passed up to the TU. The client // transaction MUST NOT generate an ACK to the 2xx response -- its // handling is delegated to the TU. A UAC core will send an ACK to // the 2xx response using a new transaction. // https://tools.ietf.org/html/rfc6026#section-8.4 if (statusCode >= 200 && statusCode <= 299) { this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache this.stateTransition(TransactionState.Accepted); if (this.user.receiveResponse) { this.user.receiveResponse(response); } return; } // When in either the "Calling" or "Proceeding" states, reception of // a response with status code from 300-699 MUST cause the client // transaction to transition to "Completed". The client transaction // MUST pass the received response up to the TU, and the client // transaction MUST generate an ACK request, even if the transport is // reliable (guidelines for constructing the ACK from the response // are given in Section 17.1.1.3), and then pass the ACK to the // transport layer for transmission. The ACK MUST be sent to the // same address, port, and transport to which the original request was sent. // https://tools.ietf.org/html/rfc6026#section-8.4 if (statusCode >= 300 && statusCode <= 699) { this.stateTransition(TransactionState.Completed); this.ack(response); if (this.user.receiveResponse) { this.user.receiveResponse(response); } return; } break; case TransactionState.Accepted: // The purpose of the "Accepted" state is to allow the client // transaction to continue to exist to receive, and pass to the TU, // any retransmissions of the 2xx response and any additional 2xx // responses from other branches of the INVITE if it forked // downstream. Timer M reflects the amount of time that the // transaction user will wait for such messages. // // Any 2xx responses that match this client transaction and that are // received while in the "Accepted" state MUST be passed up to the // TU. The client transaction MUST NOT generate an ACK to the 2xx // response. The client transaction takes no further action. // https://tools.ietf.org/html/rfc6026#section-8.4 if (statusCode >= 200 && statusCode <= 299) { // NOTE: This implementation herein is intentionally not RFC compliant. // While the first 2xx response for a given branch is passed up to the TU, // retransmissions of 2xx responses are absorbed and the ACK associated // with the original response is resent. This approach is taken because // our current transaction users are not currently in a good position to // deal with 2xx retransmission. This SHOULD NOT cause any compliance issues - ;) // // If we don't have a cache hit, pass the response to the TU. if (!this.ackRetransmissionCache.has(response.toTag)) { this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache if (this.user.receiveResponse) { this.user.receiveResponse(response); } return; } // If we have a cache hit, try pulling the ACK from cache and retransmitting it. const ack = this.ackRetransmissionCache.get(response.toTag); if (ack) { this.send(ack.toString()).catch((error) => { this.logTransportError(error, "Failed to send retransmission of ACK to 2xx response."); }); return; } // If an ACK was not found in cache then we have received a retransmitted 2xx // response before the TU responded to the original response (we don't have an ACK yet). // So discard this response under the assumption that the TU will eventually // get us a ACK for the original response. return; } break; case TransactionState.Completed: // Any retransmissions of a response with status code 300-699 that // are received while in the "Completed" state MUST cause the ACK to // be re-passed to the transport layer for retransmission, but the // newly received response MUST NOT be passed up to the TU. // https://tools.ietf.org/html/rfc6026#section-8.4 if (statusCode >= 300 && statusCode <= 699) { this.ack(response); return; } break; case TransactionState.Terminated: break; default: throw new Error(`Invalid state ${this.state}`); } // Any response received that does not match an existing client // transaction state machine is simply dropped. (Implementations are, // of course, free to log or do other implementation-specific things // with such responses, but the implementer should be sure to consider // the impact of large numbers of malicious stray responses.) // https://tools.ietf.org/html/rfc6026#section-7.2 const message = `Received unexpected ${statusCode} response while in state ${this.state}.`; this.logger.warn(message); return; } /** * The client transaction SHOULD inform the TU that a transport failure * has occurred, and the client transaction SHOULD transition directly * to the "Terminated" state. The TU will handle the failover * mechanisms described in [4]. * https://tools.ietf.org/html/rfc3261#section-17.1.4 * @param error - The error. */ onTransportError(error) { if (this.user.onTransportError) { this.user.onTransportError(error); } this.stateTransition(TransactionState.Terminated, true); } /** For logging. */ typeToString() { return "INVITE client transaction"; } ack(response) { // The ACK request constructed by the client transaction MUST contain // values for the Call-ID, From, and Request-URI that are equal to the // values of those header fields in the request passed to the transport // by the client transaction (call this the "original request"). The To // header field in the ACK MUST equal the To header field in the // response being acknowledged, and therefore will usually differ from // the To header field in the original request by the addition of the // tag parameter. The ACK MUST contain a single Via header field, and // this MUST be equal to the top Via header field of the original // request. The CSeq header field in the ACK MUST contain the same // value for the sequence number as was present in the original request, // but the method parameter MUST be equal to "ACK". // // If the INVITE request whose response is being acknowledged had Route // header fields, those header fields MUST appear in the ACK. This is // to ensure that the ACK can be routed properly through any downstream // stateless proxies. // https://tools.ietf.org/html/rfc3261#section-17.1.1.3 const ruri = this.request.ruri; const callId = this.request.callId; const cseq = this.request.cseq; const from = this.request.getHeader("from"); const to = response.getHeader("to"); const via = this.request.getHeader("via"); const route = this.request.getHeader("route"); if (!from) { throw new Error("From undefined."); } if (!to) { throw new Error("To undefined."); } if (!via) { throw new Error("Via undefined."); } let ack = `ACK ${ruri} SIP/2.0\r\n`; if (route) { ack += `Route: ${route}\r\n`; } ack += `Via: ${via}\r\n`; ack += `To: ${to}\r\n`; ack += `From: ${from}\r\n`; ack += `Call-ID: ${callId}\r\n`; ack += `CSeq: ${cseq} ACK\r\n`; ack += `Max-Forwards: 70\r\n`; ack += `Content-Length: 0\r\n\r\n`; // TOOO: "User-Agent" header this.send(ack).catch((error) => { this.logTransportError(error, "Failed to send ACK to non-2xx response."); }); return; } /** * Execute a state transition. * @param newState - New state. */ stateTransition(newState, dueToTransportError = false) { // Assert valid state transitions. const invalidStateTransition = () => { throw new Error(`Invalid state transition from ${this.state} to ${newState}`); }; switch (newState) { case TransactionState.Calling: invalidStateTransition(); break; case TransactionState.Proceeding: if (this.state !== TransactionState.Calling) { invalidStateTransition(); } break; case TransactionState.Accepted: case TransactionState.Completed: if (this.state !== TransactionState.Calling && this.state !== TransactionState.Proceeding) { invalidStateTransition(); } break; case TransactionState.Terminated: if (this.state !== TransactionState.Calling && this.state !== TransactionState.Accepted && this.state !== TransactionState.Completed) { if (!dueToTransportError) { invalidStateTransition(); } } break; default: invalidStateTransition(); } // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender // will wait for an INVITE message to be acknowledged (a SIP response message is received). // So Timer B should be cleared when the transaction state proceeds from "Calling". if (this.B) { clearTimeout(this.B); this.B = undefined; } if (newState === TransactionState.Proceeding); // The client transaction MUST start Timer D when it enters the "Completed" state // for any reason, with a value of at least 32 seconds for unreliable transports, // and a value of zero seconds for reliable transports. // https://tools.ietf.org/html/rfc6026#section-8.4 if (newState === TransactionState.Completed) { this.D = setTimeout(() => this.timer_D(), Timers.TIMER_D); } // The client transaction MUST transition to the "Accepted" state, // and Timer M MUST be started with a value of 64*T1. // https://tools.ietf.org/html/rfc6026#section-8.4 if (newState === TransactionState.Accepted) { this.M = setTimeout(() => this.timer_M(), Timers.TIMER_M); } // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. // https://tools.ietf.org/html/rfc6026#section-8.7 if (newState === TransactionState.Terminated) { this.dispose(); } // Update state. this.setState(newState); } /** * When timer A fires, the client transaction MUST retransmit the * request by passing it to the transport layer, and MUST reset the * timer with a value of 2*T1. * When timer A fires 2*T1 seconds later, the request MUST be * retransmitted again (assuming the client transaction is still in this * state). This process MUST continue so that the request is * retransmitted with intervals that double after each transmission. * These retransmissions SHOULD only be done while the client * transaction is in the "Calling" state. * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 */ timer_A() { // TODO } /** * If the client transaction is still in the "Calling" state when timer * B fires, the client transaction SHOULD inform the TU that a timeout * has occurred. The client transaction MUST NOT generate an ACK. * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 */ timer_B() { this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`); if (this.state === TransactionState.Calling) { this.onRequestTimeout(); this.stateTransition(TransactionState.Terminated); } } /** * If Timer D fires while the client transaction is in the "Completed" state, * the client transaction MUST move to the "Terminated" state. * https://tools.ietf.org/html/rfc6026#section-8.4 */ timer_D() { this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`); if (this.state === TransactionState.Completed) { this.stateTransition(TransactionState.Terminated); } } /** * If Timer M fires while the client transaction is in the "Accepted" * state, the client transaction MUST move to the "Terminated" state. * https://tools.ietf.org/html/rfc6026#section-8.4 */ timer_M() { this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`); if (this.state === TransactionState.Accepted) { this.stateTransition(TransactionState.Terminated); } } } /** * Server Transaction. * @remarks * The server transaction is responsible for the delivery of requests to * the TU and the reliable transmission of responses. It accomplishes * this through a state machine. Server transactions are created by the * core when a request is received, and transaction handling is desired * for that request (this is not always the case). * https://tools.ietf.org/html/rfc3261#section-17.2 * @public */ class ServerTransaction extends Transaction { constructor(_request, transport, user, state, loggerCategory) { super(transport, user, _request.viaBranch, state, loggerCategory); this._request = _request; this.user = user; } /** The incoming request the transaction handling. */ get request() { return this._request; } } /** * INVITE Server Transaction. * @remarks * https://tools.ietf.org/html/rfc3261#section-17.2.1 * @public */ class InviteServerTransaction extends ServerTransaction { /** * Constructor. * Upon construction, a "100 Trying" reply will be immediately sent. * After construction the transaction will be in the "proceeding" state and the transaction * `id` will equal the branch parameter set in the Via header of the incoming request. * https://tools.ietf.org/html/rfc3261#section-17.2.1 * @param request - Incoming INVITE request from the transport. * @param transport - The transport. * @param user - The transaction user. */ constructor(request, transport, user) { super(request, transport, user, TransactionState.Proceeding, "sip.transaction.ist"); } /** * Destructor. */ dispose() { this.stopProgressExtensionTimer(); if (this.H) { clearTimeout(this.H); this.H = undefined; } if (this.I) { clearTimeout(this.I); this.I = undefined; } if (this.L) { clearTimeout(this.L); this.L = undefined; } super.dispose(); } /** Transaction kind. Deprecated. */ get kind() { return "ist"; } /** * Receive requests from transport matching this transaction. * @param request - Request matching this transaction. */ receiveRequest(request) { switch (this.state) { case TransactionState.Proceeding: // If a request retransmission is received while in the "Proceeding" state, the most // recent provisional response that was received from the TU MUST be passed to the // transport layer for retransmission. // https://tools.ietf.org/html/rfc3261#section-17.2.1 if (request.method === C.INVITE) { if (this.lastProvisionalResponse) { this.send(this.lastProvisionalResponse).catch((error) => { this.logTransportError(error, "Failed to send retransmission of provisional response."); }); } return; } break; case TransactionState.Accepted: // While in the "Accepted" state, any retransmissions of the INVITE // received will match this transaction state machine and will be // absorbed by the machine without changing its state. These // retransmissions are not passed onto the TU. // https://tools.ietf.org/html/rfc6026#section-7.1 if (request.method === C.INVITE) { return; } break; case TransactionState.Completed: // Furthermore, while in the "Completed" state, if a request retransmission is // received, the server SHOULD pass the response to the transport for retransmission. // https://tools.ietf.org/html/rfc3261#section-17.2.1 if (request.method === C.INVITE) { if (!this.lastFinalResponse) { throw new Error("Last final response undefined."); } this.send(this.lastFinalResponse).catch((error) => { this.logTransportError(error, "Failed to send retransmission of final response."); }); return; } // If an ACK is received while the server transaction is in the "Completed" state, // the server transaction MUST transition to the "Confirmed" state. // https://tools.ietf.org/html/rfc3261#section-17.2.1 if (request.method === C.ACK) { this.stateTransition(TransactionState.Confirmed); return; } break; case TransactionState.Confirmed: // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, // triggered from retransmissions of the final response. // https://tools.ietf.org/html/rfc3261#section-17.2.1 if (request.method === C.INVITE || request.method === C.ACK) { return; } break; case TransactionState.Terminated: // For good measure absorb any additional messages that arrive (should not happen). if (request.method === C.INVITE || request.method === C.ACK) { return; } break; default: throw new Error(`Invalid state ${this.state}`); } const message = `INVITE server transaction received unexpected ${request.method} request while in state ${this.state}.`; this.logger.warn(message); return; } /** * Receive responses from TU for this transaction. * @param statusCode - Status code of response. * @param response - Response. */ receiveResponse(statusCode, response) { if (statusCode < 100 || statusCode > 699) { throw new Error(`Invalid status code ${statusCode}`); } switch (this.state) { case TransactionState.Proceeding: // The TU passes any number of provisional responses to the server // transaction. So long as the server transaction is in the // "Proceeding" state, each of these MUST be passed to the transport // layer for transmission. They are not sent reliably by the // transaction layer (they are not retransmitted by it) and do not cause // a change in the state of the server transaction. // https://tools.ietf.org/html/rfc3261#section-17.2.1 if (statusCode >= 100 && statusCode <= 199) { this.lastProvisionalResponse = response; // Start the progress extension timer only for a non-100 provisional response. if (statusCode > 100) { this.startProgressExtensionTimer(); // FIXME: remove } this.send(response).catch((error) => { this.logTransportError(error, "Failed to send 1xx response."); }); return; } // If, while in the "Proceeding" state, the TU passes a 2xx response // to the server transaction, the server transaction MUST pass this // response to the transport layer for transmission. It is not // retransmitted by the server transaction; retransmissions of 2xx // responses are handled by the TU. The server transaction MUST then // transition to the "Accepted" state. // https://tools.ietf.org/html/rfc6026#section-8.5 if (statusCode >= 200 && statusCode <= 299) { this.lastFinalResponse = response; this.stateTransition(TransactionState.Accepted); this.send(response).catch((error) => { this.logTransportError(error, "Failed to send 2xx response."); }); return; } // While in the "Proceeding" state, if the TU passes a response with // status code from 300 to 699 to the server transaction, the response // MUST be passed to the transport layer for transmission, and the state // machine MUST enter the "Completed" state. // https://tools.ietf.org/html/rfc3261#section-17.2.1 if (statusCode >= 300 && statusCode <= 699) { this.lastFinalResponse = response; this.stateTransition(TransactionState.Completed); this.send(response).catch((error) => { this.logTransportError(error, "Failed to send non-2xx final response."); }); return; } break; case TransactionState.Accepted: // While in the "Accepted" state, if the TU passes a 2xx response, // the server transaction MUST pass the response to the transport layer for transmission. // https://tools.ietf.org/html/rfc6026#section-8.7 if (statusCode >= 200 && statusCode <= 299) { this.send(response).catch((error) => { this.logTransportError(error, "Failed to send 2xx response."); }); return; } break; case TransactionState.Completed: break; case TransactionState.Confirmed: break; case TransactionState.Terminated: break; default: throw new Error(`Invalid state ${this.state}`); } const message = `INVITE server transaction received unexpected ${statusCode} response from TU while in state ${this.state}.`; this.logger.error(message); throw new Error(message); } /** * Retransmit the last 2xx response. This is a noop if not in the "accepted" state. */ retransmitAcceptedResponse() { if (this.state === TransactionState.Accepted && this.lastFinalResponse) { this.send(this.lastFinalResponse).catch((error) => { this.logTransportError(error, "Failed to send 2xx response."); }); } } /** * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD * inform the TU that a failure has occurred, and MUST remain in the current state. * https://tools.ietf.org/html/rfc6026#section-8.8 */ onTransportError(error) { if (this.user.onTransportError) { this.user.onTransportError(error); } } /** For logging. */ typeToString() { return "INVITE server transaction"; } /** * Execute a state transition. * @param newState - New state. */ stateTransition(newState) { // Assert valid state transitions. const invalidStateTransition = () => { throw new Error(`Invalid state transition from ${this.state} to ${newState}`); }; switch (newState) { case TransactionState.Proceeding: invalidStateTransition(); break; case TransactionState.Accepted: case TransactionState.Completed: if (this.state !== TransactionState.Proceeding) { invalidStateTransition(); } break; case TransactionState.Confirmed: if (this.state !== TransactionState.Completed) { invalidStateTransition(); } break; case TransactionState.Terminated: if (this.state !== TransactionState.Accepted && this.state !== TransactionState.Completed && this.state !== TransactionState.Confirmed) { invalidStateTransition(); } break; default: invalidStateTransition(); } // On any state transition, stop resending provisonal responses this.stopProgressExtensionTimer(); // The purpose of the "Accepted" state is to absorb retransmissions of an accepted INVITE request. // Any such retransmissions are absorbed entirely within the server transaction. // They are not passed up to the TU since any downstream UAS cores that accepted the request have // taken responsibility for reliability and will already retransmit their 2xx responses if necessary. // https://tools.ietf.org/html/rfc6026#section-8.7 if (newState === TransactionState.Accepted) { this.L = setTimeout(() => this.timer_L(), Timers.TIMER_L); } // When the "Completed" state is entered, timer H MUST be set to fire in 64*T1 seconds for all transports. // Timer H determines when the server transaction abandons retransmitting the response. // If an ACK is received while the server transaction is in the "Completed" state, // the server transaction MUST transition to the "Confirmed" state. // https://tools.ietf.org/html/rfc3261#section-17.2.1 if (newState === TransactionState.Completed) { // FIXME: Missing timer G for unreliable transports. this.H = setTimeout(() => this.timer_H(), Timers.TIMER_H); } // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, // triggered from retransmissions of the final response. When this state is entered, timer I // is set to fire in T4 seconds for unreliable transports, and zero seconds for reliable // transports. Once timer I fires, the server MUST transition to the "Terminated" state. // https://tools.ietf.org/html/rfc3261#section-17.2.1 if (newState === TransactionState.Confirmed) { // FIXME: This timer is not getting set correctly for unreliable transports. this.I = setTimeout(() => this.timer_I(), Timers.TIMER_I); } // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. // https://tools.ietf.org/html/rfc6026#section-8.7 if (newState === TransactionState.Terminated) { this.dispose(); } // Update state. this.setState(newState); } /** * FIXME: UAS Provisional Retransmission Timer. See RFC 3261 Section 13.3.1.1 * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. */ startProgressExtensionTimer() { // Start the progress extension timer only for the first non-100 provisional response. if (this.progressExtensionTimer === undefined) { this.progressExtensionTimer = setInterval(() => { this.logger.debug(`Progress extension timer expired for INVITE server transaction ${this.id}.`); if (!this.lastProvisionalResponse) { throw new Error("Last provisional response undefined."); } this.send(this.lastProvisionalResponse).catch((error) => { this.logTransportError(error, "Failed to send retransmission of provisional response."); }); }, Timers.PROVISIONAL_RESPONSE_INTERVAL); } } /** * FIXME: UAS Provisional Retransmission Timer id. See RFC 3261 Section 13.3.1.1 * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. */ stopProgressExtensionTimer() { if (this.progressExtensionTimer !== undefined) { clearInterval(this.progressExtensionTimer); this.progressExtensionTimer = undefined; } } /** * While in the "Proceeding" state, if the TU passes a response with status code * from 300 to 699 to the server transaction, the response MUST be passed to the * transport layer for transmission, and the state machine MUST enter the "Completed" state. * For unreliable transports, timer G is set to fire in T1 seconds, and is not set to fire for * reliable transports. If timer G fires, the response is passed to the transport layer once * more for retransmission, and timer G is set to fire in MIN(2*T1, T2) seconds. From then on, * when timer G fires, the response is passed to the transport again for transmission, and * timer G is reset with a value that doubles, unless that value exceeds T2, in which case * it is reset with the value of T2. * https://tools.ietf.org/html/rfc3261#section-17.2.1 */ timer_G() { // TODO } /** * If timer H fires while in the "Completed" state, it implies that the ACK was never received. * In this case, the server transaction MUST transition to the "Terminated" state, and MUST * indicate to the TU that a transaction failure has occurred. * https://tools.ietf.org/html/rfc3261#section-17.2.1 */ timer_H() { this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`); if (this.state === TransactionState.Completed) { this.logger.warn("ACK to negative final response was never received, terminating transaction."); this.stateTransition(TransactionState.Terminated); } } /** * Once timer I fires, the server MUST transition to the "Terminated" state. * https://tools.ietf.org/html/rfc3261#section-17.2.1 */ timer_I() { this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`); this.stateTransition(TransactionState.Terminated); } /** * When Timer L fires and the state machine is in the "Accepted" state, the machine MUST * transition to the "Terminated" state. Once the transaction is in the "Terminated" state, * it MUST be destroyed immediately. Timer L reflects the amount of time the server * transaction could receive 2xx responses for retransmission from the * TU while it is waiting to receive an ACK. * https://tools.ietf.org/html/rfc6026#section-7.1 * https://tools.ietf.org/html/rfc6026#section-8.7 */ timer_L() { this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`); if (this.state === TransactionState.Accepted) { this.stateTransition(TransactionState.Terminated); } } } /** * Non-INVITE Client Transaction. * @remarks * Non-INVITE transactions do not make use of ACK. * They are simple request-response interactions. * https://tools.ietf.org/html/rfc3261#section-17.1.2 * @public */ class NonInviteClientTransaction extends ClientTransaction { /** * Constructor * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. * Then `toString` is called on the outgoing request and the message is sent via the transport. * After construction the transaction will be in the "calling" state and the transaction id * will equal the branch parameter set in the Via header of the outgoing request. * https://tools.ietf.org/html/rfc3261#section-17.1.2 * @param request - The outgoing Non-INVITE request. * @param transport - The transport. * @param user - The transaction user. */ constructor(request, transport, user) { super(request, transport, user, TransactionState.Trying, "sip.transaction.nict"); // FIXME: Timer E for unreliable transports not implemented. // // The "Trying" state is entered when the TU initiates a new client // transaction with a request. When entering this state, the client // transaction SHOULD set timer F to fire in 64*T1 seconds. The request // MUST be passed to the transport layer for transmission. // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 this.F = setTimeout(() => this.timer_F(), Timers.TIMER_F); this.send(request.toString()).catch((error) => { this.logTransportError(error, "Failed to send initial outgoing request."); }); } /** * Destructor. */ dispose() { if (this.F) { clearTimeout(this.F); this.F = undefined; } if (this.K) { clearTimeout(this.K); this.K = undefined; } super.dispose(); } /** Transaction kind. Deprecated. */ get kind() { return "nict"; } /** * Handler for incoming responses from the transport which match this transaction. * @param response - The incoming response. */ receiveResponse(response) { const statusCode = response.statusCode; if (!statusCode || statusCode < 100 || statusCode > 699) { throw new Error(`Invalid status code ${statusCode}`); } switch (this.state) { case TransactionState.Trying: // If a provisional response is received while in the "Trying" state, the // response MUST be passed to the TU, and then the client transaction // SHOULD move to the "Proceeding" state. // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 if (statusCode >= 100 && statusCode <= 199) { this.stateTransition(TransactionState.Proceeding); if (this.user.receiveResponse) { this.user.receiveResponse(response); } return; } // If a final response (status codes 200-699) is received while in the // "Trying" state, the response MUST be passed to the TU, and the // client transaction MUST transition to the "Completed" state. // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 if (statusCode >= 200 && statusCode <= 699) { this.stateTransition(TransactionState.Completed); if (statusCode === 408) { this.onRequestTimeout(); return; } if (this.user.receiveResponse) { this.user.receiveResponse(response); } return; } break; case TransactionState.Proceeding: // If a provisional response is received while in the "Proceeding" state, // the response MUST be passed to the TU. (From Figure 6) // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 if (statusCode >= 100 && statusCode <= 199) { if (this.user.receiveResponse) { return this.user.receiveResponse(response); } } // If a final response (status codes 200-699) is received while in the // "Proceeding" state, the response MUST be passed to the TU, and the // client transaction MUST transition to the "Completed" state. // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 if (statusCode >= 200 && statusCode <= 699) { this.stateTransition(TransactionState.Completed); if (statusCode === 408) { this.onRequestTimeout(); return; } if (this.user.receiveResponse) { this.user.receiveResponse(response); } return; } case TransactionState.Completed: // The "Completed" state exists to buffer any additional response // retransmissions that may be received (which is why the client // transaction remains there only for unreliable transports). // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 return; case TransactionState.Terminated: // For good measure just absorb additional response retransmissions. return; default: throw new Error(`Invalid state ${this.state}`); } const message = `Non-INVITE client transaction received unexpected ${statusCode} response while in state ${this.state}.`; this.logger.warn(message); return; } /** * The client transaction SHOULD inform the TU that a transport failure has occurred, * and the client transaction SHOULD transition directly to the "Terminated" state. * The TU will handle the failover mechanisms described in [4]. * https://tools.ietf.org/html/rfc3261#section-17.1.4 * @param error - Trasnsport error */ onTransportError(error) { if (this.user.onTransportError) { this.user.onTransportError(error); } this.stateTransition(TransactionState.Terminated, true); } /** For logging. */ typeToString() { return "non-INVITE client transaction"; } /** * Execute a state transition. * @param newState - New state. */ stateTransition(newState, dueToTransportError = false) { // Assert valid state transitions. const invalidStateTransition = () => { throw new Error(`Invalid state transition from ${this.state} to ${newState}`); }; switch (newState) { case TransactionState.Trying: invalidStateTransition(); break; case TransactionState.Proceeding: if (this.state !== TransactionState.Trying) { invalidStateTransition(); } break; case TransactionState.Completed: if (this.state !== TransactionState.Trying && this.state !== TransactionState.Proceeding) { invalidStateTransition(); } break; case TransactionState.Terminated: if (this.state !== TransactionState.Trying && this.state !== TransactionState.Proceeding && this.state !== TransactionState.Completed) { if (!dueToTransportError) { invalidStateTransition(); } } break; default: invalidStateTransition(); } // Once the client transaction enters the "Completed" state, it MUST set // Timer K to fire in T4 seconds for unreliable transports, and zero // seconds for reliable transports The "Completed" state exists to // buffer any additional response retransmissions that may be received // (which is why the client transaction remains there only for unreliable transports). // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 if (newState === TransactionState.Completed) { if (this.F) { clearTimeout(this.F); this.F = undefined; } this.K = setTimeout(() => this.timer_K(), Timers.TIMER_K); } // Once the transaction is in the terminated state, it MUST be destroyed immediately. // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 if (newState === TransactionState.Terminated) { this.dispose(); } // Update state. this.setState(newState); } /** * If Timer F fires while the client transaction is still in the * "Trying" state, the client transaction SHOULD inform the TU about the * timeout, and then it SHOULD enter the "Terminated" state. * If timer F fires while in the "Proceeding" state, the TU MUST be informed of * a timeout, and the client transaction MUST transition to the terminated state. * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 */ timer_F() { this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`); if (this.state === TransactionState.Trying || this.state === TransactionState.Proceeding) { this.onRequestTimeout(); this.stateTransition(TransactionState.Terminated); } } /** * If Timer K fires while in this (COMPLETED) state, the client transaction * MUST transition to the "Terminated" state. * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 */ timer_K() { if (this.state === TransactionState.Completed) { this.stateTransition(TransactionState.Terminated); } } } /** * Non-INVITE Server Transaction. * @remarks * https://tools.ietf.org/html/rfc3261#section-17.2.2 * @public */ class NonInviteServerTransaction extends ServerTransaction { /** * Constructor. * After construction the transaction will be in the "trying": state and the transaction * `id` will equal the branch parameter set in the Via header of the incoming request. * https://tools.ietf.org/html/rfc3261#section-17.2.2 * @param request - Incoming Non-INVITE request from the transport. * @param transport - The transport. * @param user - The transaction user. */ constructor(request, transport, user) { super(request, transport, user, TransactionState.Trying, "sip.transaction.nist"); } /** * Destructor. */ dispose() { if (this.J) { clearTimeout(this.J); this.J = undefined; } super.dispose(); } /** Transaction kind. Deprecated. */ get kind() { return "nist"; } /** * Receive requests from transport matching this transaction. * @param request - Request matching this transaction. */ receiveRequest(request) { switch (this.state) { case TransactionState.Trying: // Once in the "Trying" state, any further request retransmissions are discarded. // https://tools.ietf.org/html/rfc3261#section-17.2.2 break; case TransactionState.Proceeding: // If a retransmission of the request is received while in the "Proceeding" state, // the most recently sent provisional response MUST be passed to the transport layer for retransmission. // https://tools.ietf.org/html/rfc3261#section-17.2.2 if (!this.lastResponse) { throw new Error("Last response undefined."); } this.send(this.lastResponse).catch((error) => { this.logTransportError(error, "Failed to send retransmission of provisional response."); }); break; case TransactionState.Completed: // While in the "Completed" state, the server transaction MUST pass the final response to the transport // layer for retransmission whenever a retransmission of the request is received. Any other final responses // passed by the TU to the server transaction MUST be discarded while in the "Completed" state. // https://tools.ietf.org/html/rfc3261#section-17.2.2 if (!this.lastResponse) { throw new Error("Last response undefined."); } this.send(this.lastResponse).catch((error) => { this.logTransportError(error, "Failed to send retransmission of final response."); }); break; case TransactionState.Terminated: break; default: throw new Error(`Invalid state ${this.state}`); } } /** * Receive responses from TU for this transaction. * @param statusCode - Status code of repsonse. 101-199 not allowed per RFC 4320. * @param response - Response to send. */ receiveResponse(statusCode, response) { if (statusCode < 100 || statusCode > 699) { throw new Error(`Invalid status code ${statusCode}`); } // An SIP element MUST NOT send any provisional response with a // Status-Code other than 100 to a non-INVITE request. // An SIP element MUST NOT respond to a non-INVITE request with a // Status-Code of 100 over any unreliable transport, such as UDP, // before the amount of time it takes a client transaction's Timer E to be reset to T2. // An SIP element MAY respond to a non-INVITE request with a // Status-Code of 100 over a reliable transport at any time. // https://tools.ietf.org/html/rfc4320#section-4.1 if (statusCode > 100 && statusCode <= 199) { throw new Error("Provisional response other than 100 not allowed."); } switch (this.state) { case TransactionState.Trying: // While in the "Trying" state, if the TU passes a provisional response // to the server transaction, the server transaction MUST enter the "Proceeding" state. // The response MUST be passed to the transport layer for transmission. // https://tools.ietf.org/html/rfc3261#section-17.2.2 this.lastResponse = response; if (statusCode >= 100 && statusCode < 200) { this.stateTransition(TransactionState.Proceeding); this.send(response).catch((error) => { this.logTransportError(error, "Failed to send provisional response."); }); return; } if (statusCode >= 200 && statusCode <= 699) { this.stateTransition(TransactionState.Completed); this.send(response).catch((error) => { this.logTransportError(error, "Failed to send final response."); }); return; } break; case TransactionState.Proceeding: // Any further provisional responses that are received from the TU while // in the "Proceeding" state MUST be passed to the transport layer for transmission. // If the TU passes a final response (status codes 200-699) to the server while in // the "Proceeding" state, the transaction MUST enter the "Completed" state, and // the response MUST be passed to the transport layer for transmission. // https://tools.ietf.org/html/rfc3261#section-17.2.2 this.lastResponse = response; if (statusCode >= 200 && statusCode <= 699) { this.stateTransition(TransactionState.Completed); this.send(response).catch((error) => { this.logTransportError(error, "Failed to send final response."); }); return; } break; case TransactionState.Completed: // Any other final responses passed by the TU to the server // transaction MUST be discarded while in the "Completed" state. // https://tools.ietf.org/html/rfc3261#section-17.2.2 return; case TransactionState.Terminated: break; default: throw new Error(`Invalid state ${this.state}`); } const message = `Non-INVITE server transaction received unexpected ${statusCode} response from TU while in state ${this.state}.`; this.logger.error(message); throw new Error(message); } /** * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD * inform the TU that a failure has occurred, and SHOULD transition to the terminated state. * https://tools.ietf.org/html/rfc3261#section-17.2.4 */ onTransportError(error) { if (this.user.onTransportError) { this.user.onTransportError(error); } this.stateTransition(TransactionState.Terminated, true); } /** For logging. */ typeToString() { return "non-INVITE server transaction"; } stateTransition(newState, dueToTransportError = false) { // Assert valid state transitions. const invalidStateTransition = () => { throw new Error(`Invalid state transition from ${this.state} to ${newState}`); }; switch (newState) { case TransactionState.Trying: invalidStateTransition(); break; case TransactionState.Proceeding: if (this.state !== TransactionState.Trying) { invalidStateTransition(); } break; case TransactionState.Completed: if (this.state !== TransactionState.Trying && this.state !== TransactionState.Proceeding) { invalidStateTransition(); } break; case TransactionState.Terminated: if (this.state !== TransactionState.Proceeding && this.state !== TransactionState.Completed) { if (!dueToTransportError) { invalidStateTransition(); } } break; default: invalidStateTransition(); } // When the server transaction enters the "Completed" state, it MUST set Timer J to fire // in 64*T1 seconds for unreliable transports, and zero seconds for reliable transports. // https://tools.ietf.org/html/rfc3261#section-17.2.2 if (newState === TransactionState.Completed) { this.J = setTimeout(() => this.timer_J(), Timers.TIMER_J); } // The server transaction MUST be destroyed the instant it enters the "Terminated" state. // https://tools.ietf.org/html/rfc3261#section-17.2.2 if (newState === TransactionState.Terminated) { this.dispose(); } this.setState(newState); } /** * The server transaction remains in this state until Timer J fires, * at which point it MUST transition to the "Terminated" state. * https://tools.ietf.org/html/rfc3261#section-17.2.2 */ timer_J() { this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`); if (this.state === TransactionState.Completed) { this.stateTransition(TransactionState.Terminated); } } } /** * User Agent Client (UAC). * @remarks * A user agent client is a logical entity * that creates a new request, and then uses the client * transaction state machinery to send it. The role of UAC lasts * only for the duration of that transaction. In other words, if * a piece of software initiates a request, it acts as a UAC for * the duration of that transaction. If it receives a request * later, it assumes the role of a user agent server for the * processing of that transaction. * https://tools.ietf.org/html/rfc3261#section-6 * @public */ class UserAgentClient { constructor(transactionConstructor, core, message, delegate) { this.transactionConstructor = transactionConstructor; this.core = core; this.message = message; this.delegate = delegate; this.challenged = false; this.stale = false; this.logger = this.loggerFactory.getLogger("sip.user-agent-client"); this.init(); } dispose() { this.transaction.dispose(); } get loggerFactory() { return this.core.loggerFactory; } /** The transaction associated with this request. */ get transaction() { if (!this._transaction) { throw new Error("Transaction undefined."); } return this._transaction; } /** * Since requests other than INVITE are responded to immediately, sending a * CANCEL for a non-INVITE request would always create a race condition. * A CANCEL request SHOULD NOT be sent to cancel a request other than INVITE. * https://tools.ietf.org/html/rfc3261#section-9.1 * @param options - Cancel options bucket. */ cancel(reason, options = {}) { if (!this.transaction) { throw new Error("Transaction undefined."); } if (!this.message.to) { throw new Error("To undefined."); } if (!this.message.from) { throw new Error("From undefined."); } // The following procedures are used to construct a CANCEL request. The // Request-URI, Call-ID, To, the numeric part of CSeq, and From header // fields in the CANCEL request MUST be identical to those in the // request being cancelled, including tags. A CANCEL constructed by a // client MUST have only a single Via header field value matching the // top Via value in the request being cancelled. Using the same values // for these header fields allows the CANCEL to be matched with the // request it cancels (Section 9.2 indicates how such matching occurs). // However, the method part of the CSeq header field MUST have a value // of CANCEL. This allows it to be identified and processed as a // transaction in its own right (See Section 17). // https://tools.ietf.org/html/rfc3261#section-9.1 const message = this.core.makeOutgoingRequestMessage(C.CANCEL, this.message.ruri, this.message.from.uri, this.message.to.uri, { toTag: this.message.toTag, fromTag: this.message.fromTag, callId: this.message.callId, cseq: this.message.cseq }, options.extraHeaders); // TODO: Revisit this. // The CANCEL needs to use the same branch parameter so that // it matches the INVITE transaction, but this is a hacky way to do this. // Or at the very least not well documented. If the the branch parameter // is set on the outgoing request, the transaction will use it. // Otherwise the transaction will make a new one. message.branch = this.message.branch; if (this.message.headers.Route) { message.headers.Route = this.message.headers.Route; } if (reason) { message.setHeader("Reason", reason); } // If no provisional response has been received, the CANCEL request MUST // NOT be sent; rather, the client MUST wait for the arrival of a // provisional response before sending the request. If the original // request has generated a final response, the CANCEL SHOULD NOT be // sent, as it is an effective no-op, since CANCEL has no effect on // requests that have already generated a final response. // https://tools.ietf.org/html/rfc3261#section-9.1 if (this.transaction.state === TransactionState.Proceeding) { const uac = new UserAgentClient(NonInviteClientTransaction, this.core, message); } else { this.transaction.once("stateChanged", () => { if (this.transaction && this.transaction.state === TransactionState.Proceeding) { const uac = new UserAgentClient(NonInviteClientTransaction, this.core, message); } }); } return message; } /** * If a 401 (Unauthorized) or 407 (Proxy Authentication Required) * response is received, the UAC SHOULD follow the authorization * procedures of Section 22.2 and Section 22.3 to retry the request with * credentials. * https://tools.ietf.org/html/rfc3261#section-8.1.3.5 * 22 Usage of HTTP Authentication * https://tools.ietf.org/html/rfc3261#section-22 * 22.1 Framework * https://tools.ietf.org/html/rfc3261#section-22.1 * 22.2 User-to-User Authentication * https://tools.ietf.org/html/rfc3261#section-22.2 * 22.3 Proxy-to-User Authentication * https://tools.ietf.org/html/rfc3261#section-22.3 * * FIXME: This "guard for and retry the request with credentials" * implementation is not complete and at best minimally passable. * @param response - The incoming response to guard. * @returns True if the program execution is to continue in the branch in question. * Otherwise the request is retried with credentials and current request processing must stop. */ authenticationGuard(message) { const statusCode = message.statusCode; if (!statusCode) { throw new Error("Response status code undefined."); } // If a 401 (Unauthorized) or 407 (Proxy Authentication Required) // response is received, the UAC SHOULD follow the authorization // procedures of Section 22.2 and Section 22.3 to retry the request with // credentials. // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 if (statusCode !== 401 && statusCode !== 407) { return true; } // Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header. let challenge; let authorizationHeaderName; if (statusCode === 401) { challenge = message.parseHeader("www-authenticate"); authorizationHeaderName = "authorization"; } else { challenge = message.parseHeader("proxy-authenticate"); authorizationHeaderName = "proxy-authorization"; } // Verify it seems a valid challenge. if (!challenge) { this.logger.warn(statusCode + " with wrong or missing challenge, cannot authenticate"); return true; } // Avoid infinite authentications. if (this.challenged && (this.stale || challenge.stale !== true)) { this.logger.warn(statusCode + " apparently in authentication loop, cannot authenticate"); return true; } // Get credentials. if (!this.credentials) { this.credentials = this.core.configuration.authenticationFactory(); if (!this.credentials) { this.logger.warn("Unable to obtain credentials, cannot authenticate"); return true; } } // Verify that the challenge is really valid. if (!this.credentials.authenticate(this.message, challenge)) { return true; } this.challenged = true; if (challenge.stale) { this.stale = true; } const cseq = this.message.cseq += 1; this.message.setHeader("cseq", cseq + " " + this.message.method); this.message.setHeader(authorizationHeaderName, this.credentials.toString()); // Calling init (again) will swap out our existing client transaction with a new one. // FIXME: HACK: An assumption is being made here that there is nothing that needs to // be cleaned up beyond the client transaction which is being replaced. For example, // it is assumed that no early dialogs have been created. this.init(); return false; } /** * 8.1.3.1 Transaction Layer Errors * In some cases, the response returned by the transaction layer will * not be a SIP message, but rather a transaction layer error. When a * timeout error is received from the transaction layer, it MUST be * treated as if a 408 (Request Timeout) status code has been received. * If a fatal transport error is reported by the transport layer * (generally, due to fatal ICMP errors in UDP or connection failures in * TCP), the condition MUST be treated as a 503 (Service Unavailable) * status code. * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 */ onRequestTimeout() { this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout."); const message = new IncomingResponseMessage(); message.statusCode = 408; message.reasonPhrase = "Request Timeout"; this.receiveResponse(message); return; } /** * 8.1.3.1 Transaction Layer Errors * In some cases, the response returned by the transaction layer will * not be a SIP message, but rather a transaction layer error. When a * timeout error is received from the transaction layer, it MUST be * treated as if a 408 (Request Timeout) status code has been received. * If a fatal transport error is reported by the transport layer * (generally, due to fatal ICMP errors in UDP or connection failures in * TCP), the condition MUST be treated as a 503 (Service Unavailable) * status code. * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 * @param error - Transport error */ onTransportError(error) { this.logger.error(error.message); this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable."); const message = new IncomingResponseMessage(); message.statusCode = 503; message.reasonPhrase = "Service Unavailable"; this.receiveResponse(message); } /** * Receive a response from the transaction layer. * @param message - Incoming response message. */ receiveResponse(message) { if (!this.authenticationGuard(message)) { return; } const statusCode = message.statusCode ? message.statusCode.toString() : ""; if (!statusCode) { throw new Error("Response status code undefined."); } switch (true) { case /^100$/.test(statusCode): if (this.delegate && this.delegate.onTrying) { this.delegate.onTrying({ message }); } break; case /^1[0-9]{2}$/.test(statusCode): if (this.delegate && this.delegate.onProgress) { this.delegate.onProgress({ message }); } break; case /^2[0-9]{2}$/.test(statusCode): if (this.delegate && this.delegate.onAccept) { this.delegate.onAccept({ message }); } break; case /^3[0-9]{2}$/.test(statusCode): if (this.delegate && this.delegate.onRedirect) { this.delegate.onRedirect({ message }); } break; case /^[4-6][0-9]{2}$/.test(statusCode): if (this.delegate && this.delegate.onReject) { this.delegate.onReject({ message }); } break; default: throw new Error(`Invalid status code ${statusCode}`); } } init() { // We are the transaction user. const user = { loggerFactory: this.loggerFactory, onRequestTimeout: () => this.onRequestTimeout(), onStateChange: (newState) => { if (newState === TransactionState.Terminated) { // Remove the terminated transaction from the core. this.core.userAgentClients.delete(userAgentClientId); // FIXME: HACK: Our transaction may have been swapped out with a new one // post authentication (see above), so make sure to only to dispose of // ourselves if this terminating transaction is our current transaction. if (transaction === this._transaction) { this.dispose(); } } }, onTransportError: (error) => this.onTransportError(error), receiveResponse: (message) => this.receiveResponse(message) }; // Create a new transaction with us as the user. const transaction = new this.transactionConstructor(this.message, this.core.transport, user); this._transaction = transaction; // Add the new transaction to the core. const userAgentClientId = transaction.id + transaction.request.method; this.core.userAgentClients.set(userAgentClientId, this); } } /** * BYE UAC. * @public */ class ByeUserAgentClient extends UserAgentClient { constructor(dialog, delegate, options) { const message = dialog.createOutgoingRequestMessage(C.BYE, options); super(NonInviteClientTransaction, dialog.userAgentCore, message, delegate); dialog.dispose(); } } /** * User Agent Server (UAS). * @remarks * A user agent server is a logical entity * that generates a response to a SIP request. The response * accepts, rejects, or redirects the request. This role lasts * only for the duration of that transaction. In other words, if * a piece of software responds to a request, it acts as a UAS for * the duration of that transaction. If it generates a request * later, it assumes the role of a user agent client for the * processing of that transaction. * https://tools.ietf.org/html/rfc3261#section-6 * @public */ class UserAgentServer { constructor(transactionConstructor, core, message, delegate) { this.transactionConstructor = transactionConstructor; this.core = core; this.message = message; this.delegate = delegate; this.logger = this.loggerFactory.getLogger("sip.user-agent-server"); this.toTag = message.toTag ? message.toTag : newTag(); this.init(); } dispose() { this.transaction.dispose(); } get loggerFactory() { return this.core.loggerFactory; } /** The transaction associated with this request. */ get transaction() { if (!this._transaction) { throw new Error("Transaction undefined."); } return this._transaction; } accept(options = { statusCode: 200 }) { if (!this.acceptable) { throw new TransactionStateError(`${this.message.method} not acceptable in state ${this.transaction.state}.`); } const statusCode = options.statusCode; if (statusCode < 200 || statusCode > 299) { throw new TypeError(`Invalid statusCode: ${statusCode}`); } const response = this.reply(options); return response; } progress(options = { statusCode: 180 }) { if (!this.progressable) { throw new TransactionStateError(`${this.message.method} not progressable in state ${this.transaction.state}.`); } const statusCode = options.statusCode; if (statusCode < 101 || statusCode > 199) { throw new TypeError(`Invalid statusCode: ${statusCode}`); } const response = this.reply(options); return response; } redirect(contacts, options = { statusCode: 302 }) { if (!this.redirectable) { throw new TransactionStateError(`${this.message.method} not redirectable in state ${this.transaction.state}.`); } const statusCode = options.statusCode; if (statusCode < 300 || statusCode > 399) { throw new TypeError(`Invalid statusCode: ${statusCode}`); } const contactHeaders = new Array(); contacts.forEach((contact) => contactHeaders.push(`Contact: ${contact.toString()}`)); options.extraHeaders = (options.extraHeaders || []).concat(contactHeaders); const response = this.reply(options); return response; } reject(options = { statusCode: 480 }) { if (!this.rejectable) { throw new TransactionStateError(`${this.message.method} not rejectable in state ${this.transaction.state}.`); } const statusCode = options.statusCode; if (statusCode < 400 || statusCode > 699) { throw new TypeError(`Invalid statusCode: ${statusCode}`); } const response = this.reply(options); return response; } trying(options) { if (!this.tryingable) { throw new TransactionStateError(`${this.message.method} not tryingable in state ${this.transaction.state}.`); } const response = this.reply({ statusCode: 100 }); return response; } /** * If the UAS did not find a matching transaction for the CANCEL * according to the procedure above, it SHOULD respond to the CANCEL * with a 481 (Call Leg/Transaction Does Not Exist). If the transaction * for the original request still exists, the behavior of the UAS on * receiving a CANCEL request depends on whether it has already sent a * final response for the original request. If it has, the CANCEL * request has no effect on the processing of the original request, no * effect on any session state, and no effect on the responses generated * for the original request. If the UAS has not issued a final response * for the original request, its behavior depends on the method of the * original request. If the original request was an INVITE, the UAS * SHOULD immediately respond to the INVITE with a 487 (Request * Terminated). A CANCEL request has no impact on the processing of * transactions with any other method defined in this specification. * https://tools.ietf.org/html/rfc3261#section-9.2 * @param request - Incoming CANCEL request. */ receiveCancel(message) { // Note: Currently CANCEL is being handled as a special case. // No UAS is created to handle the CANCEL and the response to // it CANCEL is being handled statelessly by the user agent core. // As such, there is currently no way to externally impact the // response to the a CANCEL request. if (this.delegate && this.delegate.onCancel) { this.delegate.onCancel(message); } } get acceptable() { if (this.transaction instanceof InviteServerTransaction) { return (this.transaction.state === TransactionState.Proceeding || this.transaction.state === TransactionState.Accepted); } if (this.transaction instanceof NonInviteServerTransaction) { return (this.transaction.state === TransactionState.Trying || this.transaction.state === TransactionState.Proceeding); } throw new Error("Unknown transaction type."); } get progressable() { if (this.transaction instanceof InviteServerTransaction) { return this.transaction.state === TransactionState.Proceeding; } if (this.transaction instanceof NonInviteServerTransaction) { return false; // https://tools.ietf.org/html/rfc4320#section-4.1 } throw new Error("Unknown transaction type."); } get redirectable() { if (this.transaction instanceof InviteServerTransaction) { return this.transaction.state === TransactionState.Proceeding; } if (this.transaction instanceof NonInviteServerTransaction) { return (this.transaction.state === TransactionState.Trying || this.transaction.state === TransactionState.Proceeding); } throw new Error("Unknown transaction type."); } get rejectable() { if (this.transaction instanceof InviteServerTransaction) { return this.transaction.state === TransactionState.Proceeding; } if (this.transaction instanceof NonInviteServerTransaction) { return (this.transaction.state === TransactionState.Trying || this.transaction.state === TransactionState.Proceeding); } throw new Error("Unknown transaction type."); } get tryingable() { if (this.transaction instanceof InviteServerTransaction) { return this.transaction.state === TransactionState.Proceeding; } if (this.transaction instanceof NonInviteServerTransaction) { return this.transaction.state === TransactionState.Trying; } throw new Error("Unknown transaction type."); } /** * When a UAS wishes to construct a response to a request, it follows * the general procedures detailed in the following subsections. * Additional behaviors specific to the response code in question, which * are not detailed in this section, may also be required. * * Once all procedures associated with the creation of a response have * been completed, the UAS hands the response back to the server * transaction from which it received the request. * https://tools.ietf.org/html/rfc3261#section-8.2.6 * @param statusCode - Status code to reply with. * @param options - Reply options bucket. */ reply(options) { if (!options.toTag && options.statusCode !== 100) { options.toTag = this.toTag; } options.userAgent = options.userAgent || this.core.configuration.userAgentHeaderFieldValue; options.supported = options.supported || this.core.configuration.supportedOptionTagsResponse; const response = constructOutgoingResponse(this.message, options); this.transaction.receiveResponse(options.statusCode, response.message); return response; } init() { // We are the transaction user. const user = { loggerFactory: this.loggerFactory, onStateChange: (newState) => { if (newState === TransactionState.Terminated) { // Remove the terminated transaction from the core. this.core.userAgentServers.delete(userAgentServerId); this.dispose(); } }, onTransportError: (error) => { this.logger.error(error.message); if (this.delegate && this.delegate.onTransportError) { this.delegate.onTransportError(error); } else { this.logger.error("User agent server response transport error."); } } }; // Create a new transaction with us as the user. const transaction = new this.transactionConstructor(this.message, this.core.transport, user); this._transaction = transaction; // Add the new transaction to the core. const userAgentServerId = transaction.id; this.core.userAgentServers.set(transaction.id, this); } } /** * BYE UAS. * @public */ class ByeUserAgentServer extends UserAgentServer { constructor(dialog, message, delegate) { super(NonInviteServerTransaction, dialog.userAgentCore, message, delegate); } } /** * INFO UAC. * @public */ class InfoUserAgentClient extends UserAgentClient { constructor(dialog, delegate, options) { const message = dialog.createOutgoingRequestMessage(C.INFO, options); super(NonInviteClientTransaction, dialog.userAgentCore, message, delegate); } } /** * INFO UAS. * @public */ class InfoUserAgentServer extends UserAgentServer { constructor(dialog, message, delegate) { super(NonInviteServerTransaction, dialog.userAgentCore, message, delegate); } } /** * NOTIFY UAS. * @public */ class NotifyUserAgentClient extends UserAgentClient { constructor(dialog, delegate, options) { const message = dialog.createOutgoingRequestMessage(C.NOTIFY, options); super(NonInviteClientTransaction, dialog.userAgentCore, message, delegate); } } /** * NOTIFY UAS. * @public */ class NotifyUserAgentServer extends UserAgentServer { /** * NOTIFY UAS constructor. * @param dialogOrCore - Dialog for in dialog NOTIFY, UserAgentCore for out of dialog NOTIFY (deprecated). * @param message - Incoming NOTIFY request message. */ constructor(dialogOrCore, message, delegate) { const userAgentCore = instanceOfDialog(dialogOrCore) ? dialogOrCore.userAgentCore : dialogOrCore; super(NonInviteServerTransaction, userAgentCore, message, delegate); } } function instanceOfDialog(object) { return object.userAgentCore !== undefined; } /** * PRACK UAC. * @public */ class PrackUserAgentClient extends UserAgentClient { constructor(dialog, delegate, options) { const message = dialog.createOutgoingRequestMessage(C.PRACK, options); super(NonInviteClientTransaction, dialog.userAgentCore, message, delegate); dialog.signalingStateTransition(message); } } /** * PRACK UAS. * @public */ class PrackUserAgentServer extends UserAgentServer { constructor(dialog, message, delegate) { super(NonInviteServerTransaction, dialog.userAgentCore, message, delegate); // Update dialog signaling state with offer/answer in body dialog.signalingStateTransition(message); this.dialog = dialog; } /** * Update the dialog signaling state on a 2xx response. * @param options - Options bucket. */ accept(options = { statusCode: 200 }) { if (options.body) { // Update dialog signaling state with offer/answer in body this.dialog.signalingStateTransition(options.body); } return super.accept(options); } } /** * Re-INVITE UAC. * @remarks * 14 Modifying an Existing Session * https://tools.ietf.org/html/rfc3261#section-14 * 14.1 UAC Behavior * https://tools.ietf.org/html/rfc3261#section-14.1 * @public */ class ReInviteUserAgentClient extends UserAgentClient { constructor(dialog, delegate, options) { const message = dialog.createOutgoingRequestMessage(C.INVITE, options); super(InviteClientTransaction, dialog.userAgentCore, message, delegate); this.delegate = delegate; dialog.signalingStateTransition(message); // FIXME: TODO: next line obviously needs to be improved... dialog.reinviteUserAgentClient = this; // let the dialog know re-invite request sent this.dialog = dialog; } receiveResponse(message) { const statusCode = message.statusCode ? message.statusCode.toString() : ""; if (!statusCode) { throw new Error("Response status code undefined."); } switch (true) { case /^100$/.test(statusCode): if (this.delegate && this.delegate.onTrying) { this.delegate.onTrying({ message }); } break; case /^1[0-9]{2}$/.test(statusCode): if (this.delegate && this.delegate.onProgress) { this.delegate.onProgress({ message, session: this.dialog, prack: (options) => { throw new Error("Unimplemented."); } }); } break; case /^2[0-9]{2}$/.test(statusCode): // Update dialog signaling state with offer/answer in body this.dialog.signalingStateTransition(message); if (this.delegate && this.delegate.onAccept) { this.delegate.onAccept({ message, session: this.dialog, ack: (options) => { const outgoingAckRequest = this.dialog.ack(options); return outgoingAckRequest; } }); } break; case /^3[0-9]{2}$/.test(statusCode): this.dialog.signalingStateRollback(); this.dialog.reinviteUserAgentClient = undefined; // ACK was handled by transaction if (this.delegate && this.delegate.onRedirect) { this.delegate.onRedirect({ message }); } break; case /^[4-6][0-9]{2}$/.test(statusCode): this.dialog.signalingStateRollback(); this.dialog.reinviteUserAgentClient = undefined; // ACK was handled by transaction if (this.delegate && this.delegate.onReject) { this.delegate.onReject({ message }); } break; default: throw new Error(`Invalid status code ${statusCode}`); } } } /** * Re-INVITE UAS. * @remarks * 14 Modifying an Existing Session * https://tools.ietf.org/html/rfc3261#section-14 * 14.2 UAS Behavior * https://tools.ietf.org/html/rfc3261#section-14.2 * @public */ class ReInviteUserAgentServer extends UserAgentServer { constructor(dialog, message, delegate) { super(InviteServerTransaction, dialog.userAgentCore, message, delegate); dialog.reinviteUserAgentServer = this; this.dialog = dialog; } /** * Update the dialog signaling state on a 2xx response. * @param options - Options bucket. */ accept(options = { statusCode: 200 }) { // FIXME: The next two lines SHOULD go away, but I suppose it's technically harmless... // These are here because some versions of SIP.js prior to 0.13.8 set the route set // of all in dialog ACKs based on the Record-Route headers in the associated 2xx // response. While this worked for dialog forming 2xx responses, it was technically // broken for re-INVITE ACKS as it only worked if the UAS populated the Record-Route // headers in the re-INVITE 2xx response (which is not required and a waste of bandwidth // as the should be ignored if present in re-INVITE ACKS) and the UAS populated // the Record-Route headers with the correct values (would be weird not too, but...). // Anyway, for now the technically useless Record-Route headers are being added // to maintain "backwards compatibility" with the older broken versions of SIP.js. options.extraHeaders = options.extraHeaders || []; options.extraHeaders = options.extraHeaders.concat(this.dialog.routeSet.map((route) => `Record-Route: ${route}`)); // Send and return the response const response = super.accept(options); const session = this.dialog; const result = Object.assign(Object.assign({}, response), { session }); if (options.body) { // Update dialog signaling state with offer/answer in body this.dialog.signalingStateTransition(options.body); } // Update dialog this.dialog.reConfirm(); return result; } /** * Update the dialog signaling state on a 1xx response. * @param options - Progress options bucket. */ progress(options = { statusCode: 180 }) { // Send and return the response const response = super.progress(options); const session = this.dialog; const result = Object.assign(Object.assign({}, response), { session }); // Update dialog signaling state if (options.body) { this.dialog.signalingStateTransition(options.body); } return result; } /** * TODO: Not Yet Supported * @param contacts - Contacts to redirect to. * @param options - Redirect options bucket. */ redirect(contacts, options = { statusCode: 302 }) { this.dialog.signalingStateRollback(); this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction throw new Error("Unimplemented."); } /** * 3.1 Background on Re-INVITE Handling by UASs * An error response to a re-INVITE has the following semantics. As * specified in Section 12.2.2 of RFC 3261 [RFC3261], if a re-INVITE is * rejected, no state changes are performed. * https://tools.ietf.org/html/rfc6141#section-3.1 * @param options - Reject options bucket. */ reject(options = { statusCode: 488 }) { this.dialog.signalingStateRollback(); this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction return super.reject(options); } } /** * REFER UAC. * @public */ class ReferUserAgentClient extends UserAgentClient { constructor(dialog, delegate, options) { const message = dialog.createOutgoingRequestMessage(C.REFER, options); super(NonInviteClientTransaction, dialog.userAgentCore, message, delegate); } } /** * REFER UAS. * @public */ class ReferUserAgentServer extends UserAgentServer { /** * REFER UAS constructor. * @param dialogOrCore - Dialog for in dialog REFER, UserAgentCore for out of dialog REFER. * @param message - Incoming REFER request message. */ constructor(dialogOrCore, message, delegate) { const userAgentCore = instanceOfSessionDialog(dialogOrCore) ? dialogOrCore.userAgentCore : dialogOrCore; super(NonInviteServerTransaction, userAgentCore, message, delegate); } } function instanceOfSessionDialog(object) { return object.userAgentCore !== undefined; } /** * Session Dialog. * @public */ class SessionDialog extends Dialog { constructor(initialTransaction, core, state, delegate) { super(core, state); this.initialTransaction = initialTransaction; /** The state of the offer/answer exchange. */ this._signalingState = SignalingState.Initial; /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ this.ackWait = false; this.delegate = delegate; if (initialTransaction instanceof InviteServerTransaction) { // If we're created by an invite server transaction, we're // going to be waiting for an ACK if are to be confirmed. this.ackWait = true; } // If we're confirmed upon creation start the retransmitting whatever // the 2xx final response was that confirmed us into existence. if (!this.early) { this.start2xxRetransmissionTimer(); } this.signalingStateTransition(initialTransaction.request); this.logger = core.loggerFactory.getLogger("sip.invite-dialog"); this.logger.log(`INVITE dialog ${this.id} constructed`); } dispose() { super.dispose(); this._signalingState = SignalingState.Closed; this._offer = undefined; this._answer = undefined; if (this.invite2xxTimer) { clearTimeout(this.invite2xxTimer); this.invite2xxTimer = undefined; } // The UAS MUST still respond to any pending requests received for that // dialog. It is RECOMMENDED that a 487 (Request Terminated) response // be generated to those pending requests. // https://tools.ietf.org/html/rfc3261#section-15.1.2 // TODO: // this.userAgentServers.forEach((uas) => uas.reply(487)); this.logger.log(`INVITE dialog ${this.id} destroyed`); } // FIXME: Need real state machine get sessionState() { if (this.early) { return SessionState.Early; } else if (this.ackWait) { return SessionState.AckWait; } else if (this._signalingState === SignalingState.Closed) { return SessionState.Terminated; } else { return SessionState.Confirmed; } } /** The state of the offer/answer exchange. */ get signalingState() { return this._signalingState; } /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ get offer() { return this._offer; } /** The current answer. Undefined unless signaling state Stable. */ get answer() { return this._answer; } /** Confirm the dialog. Only matters if dialog is currently early. */ confirm() { // When we're confirmed start the retransmitting whatever // the 2xx final response that may have confirmed us. if (this.early) { this.start2xxRetransmissionTimer(); } super.confirm(); } /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ reConfirm() { // When we're confirmed start the retransmitting whatever // the 2xx final response that may have confirmed us. if (this.reinviteUserAgentServer) { this.startReInvite2xxRetransmissionTimer(); } } /** * The UAC core MUST generate an ACK request for each 2xx received from * the transaction layer. The header fields of the ACK are constructed * in the same way as for any request sent within a dialog (see Section * 12) with the exception of the CSeq and the header fields related to * authentication. The sequence number of the CSeq header field MUST be * the same as the INVITE being acknowledged, but the CSeq method MUST * be ACK. The ACK MUST contain the same credentials as the INVITE. If * the 2xx contains an offer (based on the rules above), the ACK MUST * carry an answer in its body. If the offer in the 2xx response is not * acceptable, the UAC core MUST generate a valid answer in the ACK and * then send a BYE immediately. * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 * @param options - ACK options bucket. */ ack(options = {}) { this.logger.log(`INVITE dialog ${this.id} sending ACK request`); let transaction; if (this.reinviteUserAgentClient) { // We're sending ACK for a re-INVITE if (!(this.reinviteUserAgentClient.transaction instanceof InviteClientTransaction)) { throw new Error("Transaction not instance of InviteClientTransaction."); } transaction = this.reinviteUserAgentClient.transaction; this.reinviteUserAgentClient = undefined; } else { // We're sending ACK for the initial INVITE if (!(this.initialTransaction instanceof InviteClientTransaction)) { throw new Error("Initial transaction not instance of InviteClientTransaction."); } transaction = this.initialTransaction; } options.cseq = transaction.request.cseq; // ACK cseq is INVITE cseq const message = this.createOutgoingRequestMessage(C.ACK, options); transaction.ackResponse(message); // See InviteClientTransaction for details. this.signalingStateTransition(message); return { message }; } /** * Terminating a Session * * This section describes the procedures for terminating a session * established by SIP. The state of the session and the state of the * dialog are very closely related. When a session is initiated with an * INVITE, each 1xx or 2xx response from a distinct UAS creates a * dialog, and if that response completes the offer/answer exchange, it * also creates a session. As a result, each session is "associated" * with a single dialog - the one which resulted in its creation. If an * initial INVITE generates a non-2xx final response, that terminates * all sessions (if any) and all dialogs (if any) that were created * through responses to the request. By virtue of completing the * transaction, a non-2xx final response also prevents further sessions * from being created as a result of the INVITE. The BYE request is * used to terminate a specific session or attempted session. In this * case, the specific session is the one with the peer UA on the other * side of the dialog. When a BYE is received on a dialog, any session * associated with that dialog SHOULD terminate. A UA MUST NOT send a * BYE outside of a dialog. The caller's UA MAY send a BYE for either * confirmed or early dialogs, and the callee's UA MAY send a BYE on * confirmed dialogs, but MUST NOT send a BYE on early dialogs. * * However, the callee's UA MUST NOT send a BYE on a confirmed dialog * until it has received an ACK for its 2xx response or until the server * transaction times out. If no SIP extensions have defined other * application layer states associated with the dialog, the BYE also * terminates the dialog. * * https://tools.ietf.org/html/rfc3261#section-15 * FIXME: Make these proper Exceptions... * @param options - BYE options bucket. * @returns * Throws `Error` if callee's UA attempts a BYE on an early dialog. * Throws `Error` if callee's UA attempts a BYE on a confirmed dialog * while it's waiting on the ACK for its 2xx response. */ bye(delegate, options) { this.logger.log(`INVITE dialog ${this.id} sending BYE request`); // The caller's UA MAY send a BYE for either // confirmed or early dialogs, and the callee's UA MAY send a BYE on // confirmed dialogs, but MUST NOT send a BYE on early dialogs. // // However, the callee's UA MUST NOT send a BYE on a confirmed dialog // until it has received an ACK for its 2xx response or until the server // transaction times out. // https://tools.ietf.org/html/rfc3261#section-15 if (this.initialTransaction instanceof InviteServerTransaction) { if (this.early) { // FIXME: TODO: This should throw a proper exception. throw new Error("UAS MUST NOT send a BYE on early dialogs."); } if (this.ackWait && this.initialTransaction.state !== TransactionState.Terminated) { // FIXME: TODO: This should throw a proper exception. throw new Error("UAS MUST NOT send a BYE on a confirmed dialog " + "until it has received an ACK for its 2xx response " + "or until the server transaction times out."); } } // A BYE request is constructed as would any other request within a // dialog, as described in Section 12. // // Once the BYE is constructed, the UAC core creates a new non-INVITE // client transaction, and passes it the BYE request. The UAC MUST // consider the session terminated (and therefore stop sending or // listening for media) as soon as the BYE request is passed to the // client transaction. If the response for the BYE is a 481 // (Call/Transaction Does Not Exist) or a 408 (Request Timeout) or no // response at all is received for the BYE (that is, a timeout is // returned by the client transaction), the UAC MUST consider the // session and the dialog terminated. // https://tools.ietf.org/html/rfc3261#section-15.1.1 return new ByeUserAgentClient(this, delegate, options); } /** * An INFO request can be associated with an Info Package (see * Section 5), or associated with a legacy INFO usage (see Section 2). * * The construction of the INFO request is the same as any other * non-target refresh request within an existing invite dialog usage as * described in Section 12.2 of RFC 3261. * https://tools.ietf.org/html/rfc6086#section-4.2.1 * @param options - Options bucket. */ info(delegate, options) { this.logger.log(`INVITE dialog ${this.id} sending INFO request`); if (this.early) { // FIXME: TODO: This should throw a proper exception. throw new Error("Dialog not confirmed."); } return new InfoUserAgentClient(this, delegate, options); } /** * Modifying an Existing Session * * A successful INVITE request (see Section 13) establishes both a * dialog between two user agents and a session using the offer-answer * model. Section 12 explains how to modify an existing dialog using a * target refresh request (for example, changing the remote target URI * of the dialog). This section describes how to modify the actual * session. This modification can involve changing addresses or ports, * adding a media stream, deleting a media stream, and so on. This is * accomplished by sending a new INVITE request within the same dialog * that established the session. An INVITE request sent within an * existing dialog is known as a re-INVITE. * * Note that a single re-INVITE can modify the dialog and the * parameters of the session at the same time. * * Either the caller or callee can modify an existing session. * https://tools.ietf.org/html/rfc3261#section-14 * @param options - Options bucket */ invite(delegate, options) { this.logger.log(`INVITE dialog ${this.id} sending INVITE request`); if (this.early) { // FIXME: TODO: This should throw a proper exception. throw new Error("Dialog not confirmed."); } // Note that a UAC MUST NOT initiate a new INVITE transaction within a // dialog while another INVITE transaction is in progress in either // direction. // // 1. If there is an ongoing INVITE client transaction, the TU MUST // wait until the transaction reaches the completed or terminated // state before initiating the new INVITE. // // 2. If there is an ongoing INVITE server transaction, the TU MUST // wait until the transaction reaches the confirmed or terminated // state before initiating the new INVITE. // // However, a UA MAY initiate a regular transaction while an INVITE // transaction is in progress. A UA MAY also initiate an INVITE // transaction while a regular transaction is in progress. // https://tools.ietf.org/html/rfc3261#section-14.1 if (this.reinviteUserAgentClient) { // FIXME: TODO: This should throw a proper exception. throw new Error("There is an ongoing re-INVITE client transaction."); } if (this.reinviteUserAgentServer) { // FIXME: TODO: This should throw a proper exception. throw new Error("There is an ongoing re-INVITE server transaction."); } return new ReInviteUserAgentClient(this, delegate, options); } /** * The NOTIFY mechanism defined in [2] MUST be used to inform the agent * sending the REFER of the status of the reference. * https://tools.ietf.org/html/rfc3515#section-2.4.4 * @param options - Options bucket. */ notify(delegate, options) { this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`); if (this.early) { // FIXME: TODO: This should throw a proper exception. throw new Error("Dialog not confirmed."); } return new NotifyUserAgentClient(this, delegate, options); } /** * Assuming the response is to be transmitted reliably, the UAC MUST * create a new request with method PRACK. This request is sent within * the dialog associated with the provisional response (indeed, the * provisional response may have created the dialog). PRACK requests * MAY contain bodies, which are interpreted according to their type and * disposition. * https://tools.ietf.org/html/rfc3262#section-4 * @param options - Options bucket. */ prack(delegate, options) { this.logger.log(`INVITE dialog ${this.id} sending PRACK request`); return new PrackUserAgentClient(this, delegate, options); } /** * REFER is a SIP request and is constructed as defined in [1]. A REFER * request MUST contain exactly one Refer-To header field value. * https://tools.ietf.org/html/rfc3515#section-2.4.1 * @param options - Options bucket. */ refer(delegate, options) { this.logger.log(`INVITE dialog ${this.id} sending REFER request`); if (this.early) { // FIXME: TODO: This should throw a proper exception. throw new Error("Dialog not confirmed."); } // FIXME: TODO: Validate Refer-To header field value. return new ReferUserAgentClient(this, delegate, options); } /** * Requests sent within a dialog, as any other requests, are atomic. If * a particular request is accepted by the UAS, all the state changes * associated with it are performed. If the request is rejected, none * of the state changes are performed. * https://tools.ietf.org/html/rfc3261#section-12.2.2 * @param message - Incoming request message within this dialog. */ receiveRequest(message) { this.logger.log(`INVITE dialog ${this.id} received ${message.method} request`); // Response retransmissions cease when an ACK request for the // response is received. This is independent of whatever transport // protocols are used to send the response. // https://tools.ietf.org/html/rfc6026#section-8.1 if (message.method === C.ACK) { // If ackWait is true, then this is the ACK to the initial INVITE, // otherwise this is an ACK to an in dialog INVITE. In either case, // guard to make sure the sequence number of the ACK matches the INVITE. if (this.ackWait) { if (this.initialTransaction instanceof InviteClientTransaction) { this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`); return; } if (this.initialTransaction.request.cseq !== message.cseq) { this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`); return; } // Update before the delegate has a chance to handle the // message as delegate may callback into this dialog. this.ackWait = false; } else { if (!this.reinviteUserAgentServer) { this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`); return; } if (this.reinviteUserAgentServer.transaction.request.cseq !== message.cseq) { this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`); return; } this.reinviteUserAgentServer = undefined; } this.signalingStateTransition(message); if (this.delegate && this.delegate.onAck) { this.delegate.onAck({ message }); } return; } // Request within a dialog out of sequence guard. // https://tools.ietf.org/html/rfc3261#section-12.2.2 if (!this.sequenceGuard(message)) { this.logger.log(`INVITE dialog ${this.id} rejected out of order ${message.method} request.`); return; } if (message.method === C.INVITE) { // A UAS that receives a second INVITE before it sends the final // response to a first INVITE with a lower CSeq sequence number on the // same dialog MUST return a 500 (Server Internal Error) response to the // second INVITE and MUST include a Retry-After header field with a // randomly chosen value of between 0 and 10 seconds. // https://tools.ietf.org/html/rfc3261#section-14.2 if (this.reinviteUserAgentServer) { // https://tools.ietf.org/html/rfc3261#section-20.33 const retryAfter = Math.floor((Math.random() * 10)) + 1; const extraHeaders = [`Retry-After: ${retryAfter}`]; this.core.replyStateless(message, { statusCode: 500, extraHeaders }); return; } // A UAS that receives an INVITE on a dialog while an INVITE it had sent // on that dialog is in progress MUST return a 491 (Request Pending) // response to the received INVITE. // https://tools.ietf.org/html/rfc3261#section-14.2 if (this.reinviteUserAgentClient) { this.core.replyStateless(message, { statusCode: 491 }); return; } } // Request within a dialog common processing. // https://tools.ietf.org/html/rfc3261#section-12.2.2 super.receiveRequest(message); // Requests within a dialog MAY contain Record-Route and Contact header // fields. However, these requests do not cause the dialog's route set // to be modified, although they may modify the remote target URI. // Specifically, requests that are not target refresh requests do not // modify the dialog's remote target URI, and requests that are target // refresh requests do. For dialogs that have been established with an // INVITE, the only target refresh request defined is re-INVITE (see // Section 14). Other extensions may define different target refresh // requests for dialogs established in other ways. // // Note that an ACK is NOT a target refresh request. // // Target refresh requests only update the dialog's remote target URI, // and not the route set formed from the Record-Route. Updating the // latter would introduce severe backwards compatibility problems with // RFC 2543-compliant systems. // https://tools.ietf.org/html/rfc3261#section-15 if (message.method === C.INVITE) { // FIXME: parser needs to be typed... const contact = message.parseHeader("contact"); if (!contact) { // TODO: Review to make sure this will never happen throw new Error("Contact undefined."); } if (!(contact instanceof NameAddrHeader)) { throw new Error("Contact not instance of NameAddrHeader."); } this.dialogState.remoteTarget = contact.uri; } // Switch on method and then delegate. switch (message.method) { case C.BYE: // A UAS core receiving a BYE request for an existing dialog MUST follow // the procedures of Section 12.2.2 to process the request. Once done, // the UAS SHOULD terminate the session (and therefore stop sending and // listening for media). The only case where it can elect not to are // multicast sessions, where participation is possible even if the other // participant in the dialog has terminated its involvement in the // session. Whether or not it ends its participation on the session, // the UAS core MUST generate a 2xx response to the BYE, and MUST pass // that to the server transaction for transmission. // // The UAS MUST still respond to any pending requests received for that // dialog. It is RECOMMENDED that a 487 (Request Terminated) response // be generated to those pending requests. // https://tools.ietf.org/html/rfc3261#section-15.1.2 { const uas = new ByeUserAgentServer(this, message); this.delegate && this.delegate.onBye ? this.delegate.onBye(uas) : uas.accept(); this.dispose(); } break; case C.INFO: // If a UA receives an INFO request associated with an Info Package that // the UA has not indicated willingness to receive, the UA MUST send a // 469 (Bad Info Package) response (see Section 11.6), which contains a // Recv-Info header field with Info Packages for which the UA is willing // to receive INFO requests. { const uas = new InfoUserAgentServer(this, message); this.delegate && this.delegate.onInfo ? this.delegate.onInfo(uas) : uas.reject({ statusCode: 469, extraHeaders: ["Recv-Info :"] }); } break; case C.INVITE: // If the new session description is not acceptable, the UAS can reject // it by returning a 488 (Not Acceptable Here) response for the re- // INVITE. This response SHOULD include a Warning header field. // https://tools.ietf.org/html/rfc3261#section-14.2 { const uas = new ReInviteUserAgentServer(this, message); this.signalingStateTransition(message); this.delegate && this.delegate.onInvite ? this.delegate.onInvite(uas) : uas.reject({ statusCode: 488 }); // TODO: Warning header field. } break; case C.NOTIFY: // https://tools.ietf.org/html/rfc3515#section-2.4.4 { const uas = new NotifyUserAgentServer(this, message); this.delegate && this.delegate.onNotify ? this.delegate.onNotify(uas) : uas.accept(); } break; case C.PRACK: // https://tools.ietf.org/html/rfc3262#section-4 { const uas = new PrackUserAgentServer(this, message); this.delegate && this.delegate.onPrack ? this.delegate.onPrack(uas) : uas.accept(); } break; case C.REFER: // https://tools.ietf.org/html/rfc3515#section-2.4.2 { const uas = new ReferUserAgentServer(this, message); this.delegate && this.delegate.onRefer ? this.delegate.onRefer(uas) : uas.reject(); } break; default: { this.logger.log(`INVITE dialog ${this.id} received unimplemented ${message.method} request`); this.core.replyStateless(message, { statusCode: 501 }); } break; } } reliableSequenceGuard(message) { const statusCode = message.statusCode; if (!statusCode) { throw new Error("Status code undefined"); } if (statusCode > 100 && statusCode < 200) { // If a provisional response is received for an initial request, and // that response contains a Require header field containing the option // tag 100rel, the response is to be sent reliably. If the response is // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be // ignored, and the procedures below MUST NOT be used. // https://tools.ietf.org/html/rfc3262#section-4 const requireHeader = message.getHeader("require"); const rseqHeader = message.getHeader("rseq"); const rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; if (rseq) { // Handling of subsequent reliable provisional responses for the same // initial request follows the same rules as above, with the following // difference: reliable provisional responses are guaranteed to be in // order. As a result, if the UAC receives another reliable provisional // response to the same request, and its RSeq value is not one higher // than the value of the sequence number, that response MUST NOT be // acknowledged with a PRACK, and MUST NOT be processed further by the // UAC. An implementation MAY discard the response, or MAY cache the // response in the hopes of receiving the missing responses. // https://tools.ietf.org/html/rfc3262#section-4 if (this.rseq && this.rseq + 1 !== rseq) { return false; } // Once a reliable provisional response is received, retransmissions of // that response MUST be discarded. A response is a retransmission when // its dialog ID, CSeq, and RSeq match the original response. The UAC // MUST maintain a sequence number that indicates the most recently // received in-order reliable provisional response for the initial // request. This sequence number MUST be maintained until a final // response is received for the initial request. Its value MUST be // initialized to the RSeq header field in the first reliable // provisional response received for the initial request. // https://tools.ietf.org/html/rfc3262#section-4 if (!this.rseq) { this.rseq = rseq; } } } return true; } /** * If not in a stable signaling state, rollback to prior stable signaling state. */ signalingStateRollback() { if (this._signalingState === SignalingState.HaveLocalOffer || this.signalingState === SignalingState.HaveRemoteOffer) { if (this._rollbackOffer && this._rollbackAnswer) { this._signalingState = SignalingState.Stable; this._offer = this._rollbackOffer; this._answer = this._rollbackAnswer; } } } /** * Update the signaling state of the dialog. * @param message - The message to base the update off of. */ signalingStateTransition(message) { const body = getBody(message); // No body, no session. No, woman, no cry. if (!body || body.contentDisposition !== "session") { return; } // We've got an existing offer and answer which we may wish to rollback to if (this._signalingState === SignalingState.Stable) { this._rollbackOffer = this._offer; this._rollbackAnswer = this._answer; } // We're in UAS role, receiving incoming request with session description if (message instanceof IncomingRequestMessage) { switch (this._signalingState) { case SignalingState.Initial: case SignalingState.Stable: this._signalingState = SignalingState.HaveRemoteOffer; this._offer = body; this._answer = undefined; break; case SignalingState.HaveLocalOffer: this._signalingState = SignalingState.Stable; this._answer = body; break; case SignalingState.HaveRemoteOffer: // You cannot make a new offer while one is in progress. // https://tools.ietf.org/html/rfc3261#section-13.2.1 // FIXME: What to do here? break; case SignalingState.Closed: break; default: throw new Error("Unexpected signaling state."); } } // We're in UAC role, receiving incoming response with session description if (message instanceof IncomingResponseMessage) { switch (this._signalingState) { case SignalingState.Initial: case SignalingState.Stable: this._signalingState = SignalingState.HaveRemoteOffer; this._offer = body; this._answer = undefined; break; case SignalingState.HaveLocalOffer: this._signalingState = SignalingState.Stable; this._answer = body; break; case SignalingState.HaveRemoteOffer: // You cannot make a new offer while one is in progress. // https://tools.ietf.org/html/rfc3261#section-13.2.1 // FIXME: What to do here? break; case SignalingState.Closed: break; default: throw new Error("Unexpected signaling state."); } } // We're in UAC role, sending outgoing request with session description if (message instanceof OutgoingRequestMessage) { switch (this._signalingState) { case SignalingState.Initial: case SignalingState.Stable: this._signalingState = SignalingState.HaveLocalOffer; this._offer = body; this._answer = undefined; break; case SignalingState.HaveLocalOffer: // You cannot make a new offer while one is in progress. // https://tools.ietf.org/html/rfc3261#section-13.2.1 // FIXME: What to do here? break; case SignalingState.HaveRemoteOffer: this._signalingState = SignalingState.Stable; this._answer = body; break; case SignalingState.Closed: break; default: throw new Error("Unexpected signaling state."); } } // We're in UAS role, sending outgoing response with session description if (isBody(message)) { switch (this._signalingState) { case SignalingState.Initial: case SignalingState.Stable: this._signalingState = SignalingState.HaveLocalOffer; this._offer = body; this._answer = undefined; break; case SignalingState.HaveLocalOffer: // You cannot make a new offer while one is in progress. // https://tools.ietf.org/html/rfc3261#section-13.2.1 // FIXME: What to do here? break; case SignalingState.HaveRemoteOffer: this._signalingState = SignalingState.Stable; this._answer = body; break; case SignalingState.Closed: break; default: throw new Error("Unexpected signaling state."); } } } start2xxRetransmissionTimer() { if (this.initialTransaction instanceof InviteServerTransaction) { const transaction = this.initialTransaction; // Once the response has been constructed, it is passed to the INVITE // server transaction. In order to ensure reliable end-to-end // transport of the response, it is necessary to periodically pass // the response directly to the transport until the ACK arrives. The // 2xx response is passed to the transport with an interval that // starts at T1 seconds and doubles for each retransmission until it // reaches T2 seconds (T1 and T2 are defined in Section 17). // Response retransmissions cease when an ACK request for the // response is received. This is independent of whatever transport // protocols are used to send the response. // https://tools.ietf.org/html/rfc6026#section-8.1 let timeout = Timers.T1; const retransmission = () => { if (!this.ackWait) { this.invite2xxTimer = undefined; return; } this.logger.log("No ACK for 2xx response received, attempting retransmission"); transaction.retransmitAcceptedResponse(); timeout = Math.min(timeout * 2, Timers.T2); this.invite2xxTimer = setTimeout(retransmission, timeout); }; this.invite2xxTimer = setTimeout(retransmission, timeout); // If the server retransmits the 2xx response for 64*T1 seconds without // receiving an ACK, the dialog is confirmed, but the session SHOULD be // terminated. This is accomplished with a BYE, as described in Section 15. // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 const stateChanged = () => { if (transaction.state === TransactionState.Terminated) { transaction.removeListener("stateChanged", stateChanged); if (this.invite2xxTimer) { clearTimeout(this.invite2xxTimer); this.invite2xxTimer = undefined; } if (this.ackWait) { if (this.delegate && this.delegate.onAckTimeout) { this.delegate.onAckTimeout(); } else { this.bye(); } } } }; transaction.addListener("stateChanged", stateChanged); } } // FIXME: Refactor startReInvite2xxRetransmissionTimer() { if (this.reinviteUserAgentServer && this.reinviteUserAgentServer.transaction instanceof InviteServerTransaction) { const transaction = this.reinviteUserAgentServer.transaction; // Once the response has been constructed, it is passed to the INVITE // server transaction. In order to ensure reliable end-to-end // transport of the response, it is necessary to periodically pass // the response directly to the transport until the ACK arrives. The // 2xx response is passed to the transport with an interval that // starts at T1 seconds and doubles for each retransmission until it // reaches T2 seconds (T1 and T2 are defined in Section 17). // Response retransmissions cease when an ACK request for the // response is received. This is independent of whatever transport // protocols are used to send the response. // https://tools.ietf.org/html/rfc6026#section-8.1 let timeout = Timers.T1; const retransmission = () => { if (!this.reinviteUserAgentServer) { this.invite2xxTimer = undefined; return; } this.logger.log("No ACK for 2xx response received, attempting retransmission"); transaction.retransmitAcceptedResponse(); timeout = Math.min(timeout * 2, Timers.T2); this.invite2xxTimer = setTimeout(retransmission, timeout); }; this.invite2xxTimer = setTimeout(retransmission, timeout); // If the server retransmits the 2xx response for 64*T1 seconds without // receiving an ACK, the dialog is confirmed, but the session SHOULD be // terminated. This is accomplished with a BYE, as described in Section 15. // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 const stateChanged = () => { if (transaction.state === TransactionState.Terminated) { transaction.removeListener("stateChanged", stateChanged); if (this.invite2xxTimer) { clearTimeout(this.invite2xxTimer); this.invite2xxTimer = undefined; } if (this.reinviteUserAgentServer); } }; transaction.addListener("stateChanged", stateChanged); } } } /** * Subscription state. * @remarks * https://tools.ietf.org/html/rfc6665#section-4.1.2 * @public */ var SubscriptionState; (function(SubscriptionState) { SubscriptionState["Initial"] = "Initial"; SubscriptionState["NotifyWait"] = "NotifyWait"; SubscriptionState["Pending"] = "Pending"; SubscriptionState["Active"] = "Active"; SubscriptionState["Terminated"] = "Terminated"; })(SubscriptionState || (SubscriptionState = {})); /** * FIXME: TODO: Should be configurable/variable. */ const AllowedMethods = [ C.ACK, C.BYE, C.CANCEL, C.INFO, C.INVITE, C.MESSAGE, C.NOTIFY, C.OPTIONS, C.PRACK, C.REFER, C.REGISTER, C.SUBSCRIBE ]; /** * Re-SUBSCRIBE UAC. * @public */ class ReSubscribeUserAgentClient extends UserAgentClient { constructor(dialog, delegate, options) { const message = dialog.createOutgoingRequestMessage(C.SUBSCRIBE, options); super(NonInviteClientTransaction, dialog.userAgentCore, message, delegate); this.dialog = dialog; } waitNotifyStop() { // TODO: Placeholder. Not utilized currently. return; } /** * Receive a response from the transaction layer. * @param message - Incoming response message. */ receiveResponse(message) { if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { // The "Expires" header field in a 200-class response to SUBSCRIBE // request indicates the actual duration for which the subscription will // remain active (unless refreshed). The received value might be // smaller than the value indicated in the SUBSCRIBE request but cannot // be larger; see Section 4.2.1 for details. // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 const expires = message.getHeader("Expires"); if (!expires) { this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); } else { const subscriptionExpiresReceived = Number(expires); if (this.dialog.subscriptionExpires > subscriptionExpiresReceived) { this.dialog.subscriptionExpires = subscriptionExpiresReceived; } } } if (message.statusCode && message.statusCode >= 400 && message.statusCode < 700) { // If a SUBSCRIBE request to refresh a subscription receives a 404, 405, // 410, 416, 480-485, 489, 501, or 604 response, the subscriber MUST // consider the subscription terminated. (See [RFC5057] for further // details and notes about the effect of error codes on dialogs and // usages within dialog, such as subscriptions). If the subscriber // wishes to re-subscribe to the state, he does so by composing an // unrelated initial SUBSCRIBE request with a freshly generated Call-ID // and a new, unique "From" tag (see Section 4.1.2.1). // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 const errorCodes = [404, 405, 410, 416, 480, 481, 482, 483, 484, 485, 489, 501, 604]; if (errorCodes.indexOf(message.statusCode) !== -1) { this.dialog.terminate(); } // If a SUBSCRIBE request to refresh a subscription fails with any error // code other than those listed above, the original subscription is // still considered valid for the duration of the most recently known // "Expires" value as negotiated by the most recent successful SUBSCRIBE // transaction, or as communicated by a NOTIFY request in its // "Subscription-State" header field "expires" parameter. // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 } super.receiveResponse(message); } } /** * Subscription Dialog. * @remarks * SIP-Specific Event Notification * * Abstract * * This document describes an extension to the Session Initiation * Protocol (SIP) defined by RFC 3261. The purpose of this extension is * to provide an extensible framework by which SIP nodes can request * notification from remote nodes indicating that certain events have * occurred. * * Note that the event notification mechanisms defined herein are NOT * intended to be a general-purpose infrastructure for all classes of * event subscription and notification. * * This document represents a backwards-compatible improvement on the * original mechanism described by RFC 3265, taking into account several * years of implementation experience. Accordingly, this document * obsoletes RFC 3265. This document also updates RFC 4660 slightly to * accommodate some small changes to the mechanism that were discussed * in that document. * * https://tools.ietf.org/html/rfc6665 * @public */ class SubscriptionDialog extends Dialog { constructor(subscriptionEvent, subscriptionExpires, subscriptionState, core, state, delegate) { super(core, state); this.delegate = delegate; this._autoRefresh = false; this._subscriptionEvent = subscriptionEvent; this._subscriptionExpires = subscriptionExpires; this._subscriptionExpiresInitial = subscriptionExpires; this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); this._subscriptionRefresh = undefined; this._subscriptionRefreshLastSet = undefined; this._subscriptionState = subscriptionState; this.logger = core.loggerFactory.getLogger("sip.subscribe-dialog"); this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`); } /** * When a UAC receives a response that establishes a dialog, it * constructs the state of the dialog. This state MUST be maintained * for the duration of the dialog. * https://tools.ietf.org/html/rfc3261#section-12.1.2 * @param outgoingRequestMessage - Outgoing request message for dialog. * @param incomingResponseMessage - Incoming response message creating dialog. */ static initialDialogStateForSubscription(outgoingSubscribeRequestMessage, incomingNotifyRequestMessage) { // If the request was sent over TLS, and the Request-URI contained a // SIPS URI, the "secure" flag is set to TRUE. // https://tools.ietf.org/html/rfc3261#section-12.1.2 const secure = false; // FIXME: Currently no support for TLS. // The route set MUST be set to the list of URIs in the Record-Route // header field from the response, taken in reverse order and preserving // all URI parameters. If no Record-Route header field is present in // the response, the route set MUST be set to the empty set. This route // set, even if empty, overrides any pre-existing route set for future // requests in this dialog. The remote target MUST be set to the URI // from the Contact header field of the response. // https://tools.ietf.org/html/rfc3261#section-12.1.2 const routeSet = incomingNotifyRequestMessage.getHeaders("record-route"); const contact = incomingNotifyRequestMessage.parseHeader("contact"); if (!contact) { // TODO: Review to make sure this will never happen throw new Error("Contact undefined."); } if (!(contact instanceof NameAddrHeader)) { throw new Error("Contact not instance of NameAddrHeader."); } const remoteTarget = contact.uri; // The local sequence number MUST be set to the value of the sequence // number in the CSeq header field of the request. The remote sequence // number MUST be empty (it is established when the remote UA sends a // request within the dialog). The call identifier component of the // dialog ID MUST be set to the value of the Call-ID in the request. // The local tag component of the dialog ID MUST be set to the tag in // the From field in the request, and the remote tag component of the // dialog ID MUST be set to the tag in the To field of the response. A // UAC MUST be prepared to receive a response without a tag in the To // field, in which case the tag is considered to have a value of null. // // This is to maintain backwards compatibility with RFC 2543, which // did not mandate To tags. // // https://tools.ietf.org/html/rfc3261#section-12.1.2 const localSequenceNumber = outgoingSubscribeRequestMessage.cseq; const remoteSequenceNumber = undefined; const callId = outgoingSubscribeRequestMessage.callId; const localTag = outgoingSubscribeRequestMessage.fromTag; const remoteTag = incomingNotifyRequestMessage.fromTag; if (!callId) { // TODO: Review to make sure this will never happen throw new Error("Call id undefined."); } if (!localTag) { // TODO: Review to make sure this will never happen throw new Error("From tag undefined."); } if (!remoteTag) { // TODO: Review to make sure this will never happen throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 } // The remote URI MUST be set to the URI in the To field, and the local // URI MUST be set to the URI in the From field. // https://tools.ietf.org/html/rfc3261#section-12.1.2 if (!outgoingSubscribeRequestMessage.from) { // TODO: Review to make sure this will never happen throw new Error("From undefined."); } if (!outgoingSubscribeRequestMessage.to) { // TODO: Review to make sure this will never happen throw new Error("To undefined."); } const localURI = outgoingSubscribeRequestMessage.from.uri; const remoteURI = outgoingSubscribeRequestMessage.to.uri; // A dialog can also be in the "early" state, which occurs when it is // created with a provisional response, and then transition to the // "confirmed" state when a 2xx final response arrives. // https://tools.ietf.org/html/rfc3261#section-12 const early = false; const dialogState = { id: callId + localTag + remoteTag, early, callId, localTag, remoteTag, localSequenceNumber, remoteSequenceNumber, localURI, remoteURI, remoteTarget, routeSet, secure }; return dialogState; } dispose() { super.dispose(); if (this.N) { clearTimeout(this.N); this.N = undefined; } this.refreshTimerClear(); this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`); } get autoRefresh() { return this._autoRefresh; } set autoRefresh(autoRefresh) { this._autoRefresh = true; this.refreshTimerSet(); } get subscriptionEvent() { return this._subscriptionEvent; } /** Number of seconds until subscription expires. */ get subscriptionExpires() { const secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionExpiresLastSet; const secondsUntilExpires = this._subscriptionExpires - secondsSinceLastSet; return Math.max(secondsUntilExpires, 0); } set subscriptionExpires(expires) { if (expires < 0) { throw new Error("Expires must be greater than or equal to zero."); } this._subscriptionExpires = expires; this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); if (this.autoRefresh) { const refresh = this.subscriptionRefresh; if (refresh === undefined || refresh >= expires) { this.refreshTimerSet(); } } } get subscriptionExpiresInitial() { return this._subscriptionExpiresInitial; } /** Number of seconds until subscription auto refresh. */ get subscriptionRefresh() { if (this._subscriptionRefresh === undefined || this._subscriptionRefreshLastSet === undefined) { return undefined; } const secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionRefreshLastSet; const secondsUntilExpires = this._subscriptionRefresh - secondsSinceLastSet; return Math.max(secondsUntilExpires, 0); } get subscriptionState() { return this._subscriptionState; } /** * Receive in dialog request message from transport. * @param message - The incoming request message. */ receiveRequest(message) { this.logger.log(`SUBSCRIBE dialog ${this.id} received ${message.method} request`); // Request within a dialog out of sequence guard. // https://tools.ietf.org/html/rfc3261#section-12.2.2 if (!this.sequenceGuard(message)) { this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${message.method} request.`); return; } // Request within a dialog common processing. // https://tools.ietf.org/html/rfc3261#section-12.2.2 super.receiveRequest(message); // Switch on method and then delegate. switch (message.method) { case C.NOTIFY: this.onNotify(message); break; default: this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${message.method} request`); this.core.replyStateless(message, { statusCode: 501 }); break; } } /** * 4.1.2.2. Refreshing of Subscriptions * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 */ refresh() { const allowHeader = "Allow: " + AllowedMethods.toString(); const options = {}; options.extraHeaders = (options.extraHeaders || []).slice(); options.extraHeaders.push(allowHeader); options.extraHeaders.push("Event: " + this.subscriptionEvent); options.extraHeaders.push("Expires: " + this.subscriptionExpiresInitial); options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); return this.subscribe(undefined, options); } /** * 4.1.2.2. Refreshing of Subscriptions * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 * @param delegate - Delegate to handle responses. * @param options - Options bucket. */ subscribe(delegate, options = {}) { if (this.subscriptionState !== SubscriptionState.Pending && this.subscriptionState !== SubscriptionState.Active) { // FIXME: This needs to be a proper exception throw new Error(`Invalid state ${this.subscriptionState}. May only re-subscribe while in state "pending" or "active".`); } this.logger.log(`SUBSCRIBE dialog ${this.id} sending SUBSCRIBE request`); const uac = new ReSubscribeUserAgentClient(this, delegate, options); // When refreshing a subscription, a subscriber starts Timer N, set to // 64*T1, when it sends the SUBSCRIBE request. // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 this.N = setTimeout(() => this.timer_N(), Timers.TIMER_N); return uac; } /** * 4.4.1. Dialog Creation and Termination * A subscription is destroyed after a notifier sends a NOTIFY request * with a "Subscription-State" of "terminated", or in certain error * situations described elsewhere in this document. * https://tools.ietf.org/html/rfc6665#section-4.4.1 */ terminate() { this.stateTransition(SubscriptionState.Terminated); this.onTerminated(); } /** * 4.1.2.3. Unsubscribing * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 */ unsubscribe() { const allowHeader = "Allow: " + AllowedMethods.toString(); const options = {}; options.extraHeaders = (options.extraHeaders || []).slice(); options.extraHeaders.push(allowHeader); options.extraHeaders.push("Event: " + this.subscriptionEvent); options.extraHeaders.push("Expires: 0"); options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); return this.subscribe(undefined, options); } /** * Handle in dialog NOTIFY requests. * This does not include the first NOTIFY which created the dialog. * @param message - The incoming NOTIFY request message. */ onNotify(message) { // If, for some reason, the event package designated in the "Event" // header field of the NOTIFY request is not supported, the subscriber // will respond with a 489 (Bad Event) response. // https://tools.ietf.org/html/rfc6665#section-4.1.3 const event = message.parseHeader("Event").event; if (!event || event !== this.subscriptionEvent) { this.core.replyStateless(message, { statusCode: 489 }); return; } // In the state diagram, "Re-subscription times out" means that an // attempt to refresh or update the subscription using a new SUBSCRIBE // request does not result in a NOTIFY request before the corresponding // Timer N expires. // https://tools.ietf.org/html/rfc6665#section-4.1.2 if (this.N) { clearTimeout(this.N); this.N = undefined; } // NOTIFY requests MUST contain "Subscription-State" header fields that // indicate the status of the subscription. // https://tools.ietf.org/html/rfc6665#section-4.1.3 const subscriptionState = message.parseHeader("Subscription-State"); if (!subscriptionState || !subscriptionState.state) { this.core.replyStateless(message, { statusCode: 489 }); return; } const state = subscriptionState.state; const expires = subscriptionState.expires ? Math.max(subscriptionState.expires, 0) : undefined; // Update our state and expiration. switch (state) { case "pending": this.stateTransition(SubscriptionState.Pending, expires); break; case "active": this.stateTransition(SubscriptionState.Active, expires); break; case "terminated": this.stateTransition(SubscriptionState.Terminated, expires); break; default: this.logger.warn("Unrecognized subscription state."); break; } // Delegate remainder of NOTIFY handling. const uas = new NotifyUserAgentServer(this, message); if (this.delegate && this.delegate.onNotify) { this.delegate.onNotify(uas); } else { uas.accept(); } } onRefresh(request) { if (this.delegate && this.delegate.onRefresh) { this.delegate.onRefresh(request); } } onTerminated() { if (this.delegate && this.delegate.onTerminated) { this.delegate.onTerminated(); } } refreshTimerClear() { if (this.refreshTimer) { clearTimeout(this.refreshTimer); this.refreshTimer = undefined; } } refreshTimerSet() { this.refreshTimerClear(); if (this.autoRefresh && this.subscriptionExpires > 0) { const refresh = this.subscriptionExpires * 900; this._subscriptionRefresh = Math.floor(refresh / 1000); this._subscriptionRefreshLastSet = Math.floor(Date.now() / 1000); this.refreshTimer = setTimeout(() => { this.refreshTimer = undefined; this._subscriptionRefresh = undefined; this._subscriptionRefreshLastSet = undefined; this.onRefresh(this.refresh()); }, refresh); } } stateTransition(newState, newExpires) { // Assert valid state transitions. const invalidStateTransition = () => { this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${newState}`); }; switch (newState) { case SubscriptionState.Initial: invalidStateTransition(); return; case SubscriptionState.NotifyWait: invalidStateTransition(); return; case SubscriptionState.Pending: if (this.subscriptionState !== SubscriptionState.NotifyWait && this.subscriptionState !== SubscriptionState.Pending) { invalidStateTransition(); return; } break; case SubscriptionState.Active: if (this.subscriptionState !== SubscriptionState.NotifyWait && this.subscriptionState !== SubscriptionState.Pending && this.subscriptionState !== SubscriptionState.Active) { invalidStateTransition(); return; } break; case SubscriptionState.Terminated: if (this.subscriptionState !== SubscriptionState.NotifyWait && this.subscriptionState !== SubscriptionState.Pending && this.subscriptionState !== SubscriptionState.Active) { invalidStateTransition(); return; } break; default: invalidStateTransition(); return; } // If the "Subscription-State" value is "pending", the subscription has // been received by the notifier, but there is insufficient policy // information to grant or deny the subscription yet. If the header // field also contains an "expires" parameter, the subscriber SHOULD // take it as the authoritative subscription duration and adjust // accordingly. No further action is necessary on the part of the // subscriber. The "retry-after" and "reason" parameters have no // semantics for "pending". // https://tools.ietf.org/html/rfc6665#section-4.1.3 if (newState === SubscriptionState.Pending) { if (newExpires) { this.subscriptionExpires = newExpires; } } // If the "Subscription-State" header field value is "active", it means // that the subscription has been accepted and (in general) has been // authorized. If the header field also contains an "expires" // parameter, the subscriber SHOULD take it as the authoritative // subscription duration and adjust accordingly. The "retry-after" and // "reason" parameters have no semantics for "active". // https://tools.ietf.org/html/rfc6665#section-4.1.3 if (newState === SubscriptionState.Active) { if (newExpires) { this.subscriptionExpires = newExpires; } } // If the "Subscription-State" value is "terminated", the subscriber // MUST consider the subscription terminated. The "expires" parameter // has no semantics for "terminated" -- notifiers SHOULD NOT include an // "expires" parameter on a "Subscription-State" header field with a // value of "terminated", and subscribers MUST ignore any such // parameter, if present. if (newState === SubscriptionState.Terminated) { this.dispose(); } this._subscriptionState = newState; } /** * When refreshing a subscription, a subscriber starts Timer N, set to * 64*T1, when it sends the SUBSCRIBE request. If this Timer N expires * prior to the receipt of a NOTIFY request, the subscriber considers * the subscription terminated. If the subscriber receives a success * response to the SUBSCRIBE request that indicates that no NOTIFY * request will be generated -- such as the 204 response defined for use * with the optional extension described in [RFC5839] -- then it MUST * cancel Timer N. * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 */ timer_N() { if (this.subscriptionState !== SubscriptionState.Terminated) { this.stateTransition(SubscriptionState.Terminated); this.onTerminated(); } } } /** * Log levels. * @public */ var Levels; (function(Levels) { Levels[Levels["error"] = 0] = "error"; Levels[Levels["warn"] = 1] = "warn"; Levels[Levels["log"] = 2] = "log"; Levels[Levels["debug"] = 3] = "debug"; })(Levels || (Levels = {})); /** * Logger. * @public */ class Logger$1 { constructor(logger, category, label) { this.logger = logger; this.category = category; this.label = label; } error(content) { this.genericLog(Levels.error, content); } warn(content) { this.genericLog(Levels.warn, content); } log(content) { this.genericLog(Levels.log, content); } debug(content) { this.genericLog(Levels.debug, content); } genericLog(level, content) { this.logger.genericLog(level, this.category, this.label, content); } } /** * Logger. * @public */ class LoggerFactory { constructor() { this.builtinEnabled = true; this._level = Levels.log; this.loggers = {}; this.logger = this.getLogger("sip:loggerfactory"); } get level() { return this._level; } set level(newLevel) { if (newLevel >= 0 && newLevel <= 3) { this._level = newLevel; } else if (newLevel > 3) { this._level = 3; } else if (Levels.hasOwnProperty(newLevel)) { this._level = newLevel; } else { this.logger.error("invalid 'level' parameter value: " + JSON.stringify(newLevel)); } } get connector() { return this._connector; } set connector(value) { if (!value) { this._connector = undefined; } else if (typeof value === "function") { this._connector = value; } else { this.logger.error("invalid 'connector' parameter value: " + JSON.stringify(value)); } } getLogger(category, label) { if (label && this.level === 3) { return new Logger$1(this, category, label); } else if (this.loggers[category]) { return this.loggers[category]; } else { const logger = new Logger$1(this, category); this.loggers[category] = logger; return logger; } } genericLog(levelToLog, category, label, content) { if (this.level >= levelToLog) { if (this.builtinEnabled) { this.print(levelToLog, category, label, content); } } if (this.connector) { this.connector(Levels[levelToLog], category, label, content); } } print(levelToLog, category, label, content) { if (typeof content === "string") { const prefix = [new Date(), category]; if (label) { prefix.push(label); } content = prefix.concat(content).join(" | "); } switch (levelToLog) { case Levels.error: // tslint:disable-next-line:no-console console.error(content); break; case Levels.warn: // tslint:disable-next-line:no-console console.warn(content); break; case Levels.log: // tslint:disable-next-line:no-console console.log(content); break; case Levels.debug: // tslint:disable-next-line:no-console console.debug(content); break; default: break; } } } /** * INVITE UAC. * @remarks * 13 Initiating a Session * https://tools.ietf.org/html/rfc3261#section-13 * 13.1 Overview * https://tools.ietf.org/html/rfc3261#section-13.1 * 13.2 UAC Processing * https://tools.ietf.org/html/rfc3261#section-13.2 * @public */ class InviteUserAgentClient extends UserAgentClient { constructor(core, message, delegate) { super(InviteClientTransaction, core, message, delegate); this.confirmedDialogAcks = new Map(); this.confirmedDialogs = new Map(); this.earlyDialogs = new Map(); this.delegate = delegate; } dispose() { // The UAC core considers the INVITE transaction completed 64*T1 seconds // after the reception of the first 2xx response. At this point all the // early dialogs that have not transitioned to established dialogs are // terminated. Once the INVITE transaction is considered completed by // the UAC core, no more new 2xx responses are expected to arrive. // // If, after acknowledging any 2xx response to an INVITE, the UAC does // not want to continue with that dialog, then the UAC MUST terminate // the dialog by sending a BYE request as described in Section 15. // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 this.earlyDialogs.forEach((earlyDialog) => earlyDialog.dispose()); this.earlyDialogs.clear(); super.dispose(); } /** * Special case for transport error while sending ACK. * @param error - Transport error */ onTransportError(error) { if (this.transaction.state === TransactionState.Calling) { return super.onTransportError(error); } // If not in 'calling' state, the transport error occurred while sending an ACK. this.logger.error(error.message); this.logger.error("User agent client request transport error while sending ACK."); } /** * Once the INVITE has been passed to the INVITE client transaction, the * UAC waits for responses for the INVITE. * https://tools.ietf.org/html/rfc3261#section-13.2.2 * @param incomingResponse - Incoming response to INVITE request. */ receiveResponse(message) { if (!this.authenticationGuard(message)) { return; } const statusCode = message.statusCode ? message.statusCode.toString() : ""; if (!statusCode) { throw new Error("Response status code undefined."); } switch (true) { case /^100$/.test(statusCode): if (this.delegate && this.delegate.onTrying) { this.delegate.onTrying({ message }); } return; case /^1[0-9]{2}$/.test(statusCode): // Zero, one or multiple provisional responses may arrive before one or // more final responses are received. Provisional responses for an // INVITE request can create "early dialogs". If a provisional response // has a tag in the To field, and if the dialog ID of the response does // not match an existing dialog, one is constructed using the procedures // defined in Section 12.1.2. // // The early dialog will only be needed if the UAC needs to send a // request to its peer within the dialog before the initial INVITE // transaction completes. Header fields present in a provisional // response are applicable as long as the dialog is in the early state // (for example, an Allow header field in a provisional response // contains the methods that can be used in the dialog while this is in // the early state). // https://tools.ietf.org/html/rfc3261#section-13.2.2.1 { // Provisional without to tag, no dialog to create. if (!message.toTag) { this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping."); return; } // Compute dialog state. const dialogState = Dialog.initialDialogStateForUserAgentClient(this.message, message); // Have existing early dialog or create a new one. let earlyDialog = this.earlyDialogs.get(dialogState.id); if (!earlyDialog) { const transaction = this.transaction; if (!(transaction instanceof InviteClientTransaction)) { throw new Error("Transaction not instance of InviteClientTransaction."); } earlyDialog = new SessionDialog(transaction, this.core, dialogState); this.earlyDialogs.set(earlyDialog.id, earlyDialog); } // Guard against out of order reliable provisional responses. // Note that this is where the rseq tracking is done. if (!earlyDialog.reliableSequenceGuard(message)) { this.logger.warn("1xx INVITE reliable response received out of order, dropping."); return; } // If the initial offer is in an INVITE, the answer MUST be in a // reliable non-failure message from UAS back to UAC which is // correlated to that INVITE. For this specification, that is // only the final 2xx response to that INVITE. That same exact // answer MAY also be placed in any provisional responses sent // prior to the answer. The UAC MUST treat the first session // description it receives as the answer, and MUST ignore any // session descriptions in subsequent responses to the initial // INVITE. // https://tools.ietf.org/html/rfc3261#section-13.2.1 if (earlyDialog.signalingState === SignalingState.Initial || earlyDialog.signalingState === SignalingState.HaveLocalOffer) { earlyDialog.signalingStateTransition(message); } // Pass response to delegate. const session = earlyDialog; if (this.delegate && this.delegate.onProgress) { this.delegate.onProgress({ message, session, prack: (options) => { const outgoingPrackRequest = session.prack(undefined, options); return outgoingPrackRequest; } }); } } return; case /^2[0-9]{2}$/.test(statusCode): // Multiple 2xx responses may arrive at the UAC for a single INVITE // request due to a forking proxy. Each response is distinguished by // the tag parameter in the To header field, and each represents a // distinct dialog, with a distinct dialog identifier. // // If the dialog identifier in the 2xx response matches the dialog // identifier of an existing dialog, the dialog MUST be transitioned to // the "confirmed" state, and the route set for the dialog MUST be // recomputed based on the 2xx response using the procedures of Section // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be // constructed using the procedures of Section 12.1.2. // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 { // Compute dialog state. const dialogState = Dialog.initialDialogStateForUserAgentClient(this.message, message); // NOTE: Currently our transaction layer is caching the 2xx ACKs and // handling retransmissions of the ACK which is an approach which is // not to spec. In any event, this block is intended to provide a to // spec implementation of ACK retransmissions, but it should not be // hit currently. let dialog = this.confirmedDialogs.get(dialogState.id); if (dialog) { // Once the ACK has been constructed, the procedures of [4] are used to // determine the destination address, port and transport. However, the // request is passed to the transport layer directly for transmission, // rather than a client transaction. This is because the UAC core // handles retransmissions of the ACK, not the transaction layer. The // ACK MUST be passed to the client transport every time a // retransmission of the 2xx final response that triggered the ACK // arrives. // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 const outgoingAckRequest = this.confirmedDialogAcks.get(dialogState.id); if (outgoingAckRequest) { const transaction = this.transaction; if (!(transaction instanceof InviteClientTransaction)) { throw new Error("Client transaction not instance of InviteClientTransaction."); } transaction.ackResponse(outgoingAckRequest.message); } return; } // If the dialog identifier in the 2xx response matches the dialog // identifier of an existing dialog, the dialog MUST be transitioned to // the "confirmed" state, and the route set for the dialog MUST be // recomputed based on the 2xx response using the procedures of Section // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be // constructed using the procedures of Section 12.1.2. // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 dialog = this.earlyDialogs.get(dialogState.id); if (dialog) { dialog.confirm(); dialog.recomputeRouteSet(message); this.earlyDialogs.delete(dialog.id); this.confirmedDialogs.set(dialog.id, dialog); } else { const transaction = this.transaction; if (!(transaction instanceof InviteClientTransaction)) { throw new Error("Transaction not instance of InviteClientTransaction."); } dialog = new SessionDialog(transaction, this.core, dialogState); this.confirmedDialogs.set(dialog.id, dialog); } // If the initial offer is in an INVITE, the answer MUST be in a // reliable non-failure message from UAS back to UAC which is // correlated to that INVITE. For this specification, that is // only the final 2xx response to that INVITE. That same exact // answer MAY also be placed in any provisional responses sent // prior to the answer. The UAC MUST treat the first session // description it receives as the answer, and MUST ignore any // session descriptions in subsequent responses to the initial // INVITE. // https://tools.ietf.org/html/rfc3261#section-13.2.1 if (dialog.signalingState === SignalingState.Initial || dialog.signalingState === SignalingState.HaveLocalOffer) { dialog.signalingStateTransition(message); } // Session Initiated! :) const session = dialog; // The UAC core MUST generate an ACK request for each 2xx received from // the transaction layer. The header fields of the ACK are constructed // in the same way as for any request sent within a dialog (see Section // 12) with the exception of the CSeq and the header fields related to // authentication. The sequence number of the CSeq header field MUST be // the same as the INVITE being acknowledged, but the CSeq method MUST // be ACK. The ACK MUST contain the same credentials as the INVITE. If // the 2xx contains an offer (based on the rules above), the ACK MUST // carry an answer in its body. If the offer in the 2xx response is not // acceptable, the UAC core MUST generate a valid answer in the ACK and // then send a BYE immediately. // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 if (this.delegate && this.delegate.onAccept) { this.delegate.onAccept({ message, session, ack: (options) => { const outgoingAckRequest = session.ack(options); this.confirmedDialogAcks.set(session.id, outgoingAckRequest); return outgoingAckRequest; } }); } else { const outgoingAckRequest = session.ack(); this.confirmedDialogAcks.set(session.id, outgoingAckRequest); } } return; case /^3[0-9]{2}$/.test(statusCode): // 12.3 Termination of a Dialog // // Independent of the method, if a request outside of a dialog generates // a non-2xx final response, any early dialogs created through // provisional responses to that request are terminated. The mechanism // for terminating confirmed dialogs is method specific. In this // specification, the BYE method terminates a session and the dialog // associated with it. See Section 15 for details. // https://tools.ietf.org/html/rfc3261#section-12.3 // All early dialogs are considered terminated upon reception of the // non-2xx final response. // // After having received the non-2xx final response the UAC core // considers the INVITE transaction completed. The INVITE client // transaction handles the generation of ACKs for the response (see // Section 17). // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 this.earlyDialogs.forEach((earlyDialog) => earlyDialog.dispose()); this.earlyDialogs.clear(); // A 3xx response may contain one or more Contact header field values // providing new addresses where the callee might be reachable. // Depending on the status code of the 3xx response (see Section 21.3), // the UAC MAY choose to try those new addresses. // https://tools.ietf.org/html/rfc3261#section-13.2.2.2 if (this.delegate && this.delegate.onRedirect) { this.delegate.onRedirect({ message }); } return; case /^[4-6][0-9]{2}$/.test(statusCode): // 12.3 Termination of a Dialog // // Independent of the method, if a request outside of a dialog generates // a non-2xx final response, any early dialogs created through // provisional responses to that request are terminated. The mechanism // for terminating confirmed dialogs is method specific. In this // specification, the BYE method terminates a session and the dialog // associated with it. See Section 15 for details. // https://tools.ietf.org/html/rfc3261#section-12.3 // All early dialogs are considered terminated upon reception of the // non-2xx final response. // // After having received the non-2xx final response the UAC core // considers the INVITE transaction completed. The INVITE client // transaction handles the generation of ACKs for the response (see // Section 17). // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 this.earlyDialogs.forEach((earlyDialog) => earlyDialog.dispose()); this.earlyDialogs.clear(); // A single non-2xx final response may be received for the INVITE. 4xx, // 5xx and 6xx responses may contain a Contact header field value // indicating the location where additional information about the error // can be found. Subsequent final responses (which would only arrive // under error conditions) MUST be ignored. // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 if (this.delegate && this.delegate.onReject) { this.delegate.onReject({ message }); } return; default: throw new Error(`Invalid status code ${statusCode}`); } } } /** * INVITE UAS. * @remarks * 13 Initiating a Session * https://tools.ietf.org/html/rfc3261#section-13 * 13.1 Overview * https://tools.ietf.org/html/rfc3261#section-13.1 * 13.3 UAS Processing * https://tools.ietf.org/html/rfc3261#section-13.3 * @public */ class InviteUserAgentServer extends UserAgentServer { constructor(core, message, delegate) { super(InviteServerTransaction, core, message, delegate); this.core = core; } dispose() { if (this.earlyDialog) { this.earlyDialog.dispose(); } super.dispose(); } /** * 13.3.1.4 The INVITE is Accepted * The UAS core generates a 2xx response. This response establishes a * dialog, and therefore follows the procedures of Section 12.1.1 in * addition to those of Section 8.2.6. * https://tools.ietf.org/html/rfc3261#section-13.3.1.4 * @param options - Accept options bucket. */ accept(options = { statusCode: 200 }) { if (!this.acceptable) { throw new TransactionStateError(`${this.message.method} not acceptable in state ${this.transaction.state}.`); } // This response establishes a dialog... // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 if (!this.confirmedDialog) { if (this.earlyDialog) { this.earlyDialog.confirm(); this.confirmedDialog = this.earlyDialog; this.earlyDialog = undefined; } else { const transaction = this.transaction; if (!(transaction instanceof InviteServerTransaction)) { throw new Error("Transaction not instance of InviteClientTransaction."); } const state = Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag); this.confirmedDialog = new SessionDialog(transaction, this.core, state); } } // When a UAS responds to a request with a response that establishes a // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route // header field values from the request into the response (including the // URIs, URI parameters, and any Record-Route header field parameters, // whether they are known or unknown to the UAS) and MUST maintain the // order of those values. The UAS MUST add a Contact header field to // the response. The Contact header field contains an address where the // UAS would like to be contacted for subsequent requests in the dialog // (which includes the ACK for a 2xx response in the case of an INVITE). // Generally, the host portion of this URI is the IP address or FQDN of // the host. The URI provided in the Contact header field MUST be a SIP // or SIPS URI. If the request that initiated the dialog contained a // SIPS URI in the Request-URI or in the top Record-Route header field // value, if there was any, or the Contact header field if there was no // Record-Route header field, the Contact header field in the response // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the // same URI can be used in messages outside this dialog). The same way, // the scope of the URI in the Contact header field of the INVITE is not // limited to this dialog either. It can therefore be used in messages // to the UAC even outside this dialog. // https://tools.ietf.org/html/rfc3261#section-12.1.1 const recordRouteHeader = this.message .getHeaders("record-route") .map((header) => `Record-Route: ${header}`); const contactHeader = `Contact: ${this.core.configuration.contact.toString()}`; // A 2xx response to an INVITE SHOULD contain the Allow header field and // the Supported header field, and MAY contain the Accept header field. // Including these header fields allows the UAC to determine the // features and extensions supported by the UAS for the duration of the // call, without probing. // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 // FIXME: TODO: This should not be hard coded. const allowHeader = "Allow: " + AllowedMethods.toString(); // FIXME: TODO: Supported header (see reply()) // FIXME: TODO: Accept header // If the INVITE request contained an offer, and the UAS had not yet // sent an answer, the 2xx MUST contain an answer. If the INVITE did // not contain an offer, the 2xx MUST contain an offer if the UAS had // not yet sent an offer. // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 if (!options.body) { if (this.confirmedDialog.signalingState === SignalingState.Stable) { options.body = this.confirmedDialog.answer; // resend the answer sent in provisional response } else if (this.confirmedDialog.signalingState === SignalingState.Initial || this.confirmedDialog.signalingState === SignalingState.HaveRemoteOffer) { throw new Error("Response must have a body."); } } options.statusCode = options.statusCode || 200; options.extraHeaders = options.extraHeaders || []; options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); options.extraHeaders.push(allowHeader); options.extraHeaders.push(contactHeader); const response = super.accept(options); const session = this.confirmedDialog; const result = Object.assign(Object.assign({}, response), { session }); // Update dialog signaling state if (options.body) { // Once the UAS has sent or received an answer to the initial // offer, it MUST NOT generate subsequent offers in any responses // to the initial INVITE. This means that a UAS based on this // specification alone can never generate subsequent offers until // completion of the initial transaction. // https://tools.ietf.org/html/rfc3261#section-13.2.1 if (this.confirmedDialog.signalingState !== SignalingState.Stable) { this.confirmedDialog.signalingStateTransition(options.body); } } return result; } /** * 13.3.1.1 Progress * If the UAS is not able to answer the invitation immediately, it can * choose to indicate some kind of progress to the UAC (for example, an * indication that a phone is ringing). This is accomplished with a * provisional response between 101 and 199. These provisional * responses establish early dialogs and therefore follow the procedures * of Section 12.1.1 in addition to those of Section 8.2.6. A UAS MAY * send as many provisional responses as it likes. Each of these MUST * indicate the same dialog ID. However, these will not be delivered * reliably. * * If the UAS desires an extended period of time to answer the INVITE, * it will need to ask for an "extension" in order to prevent proxies * from canceling the transaction. A proxy has the option of canceling * a transaction when there is a gap of 3 minutes between responses in a * transaction. To prevent cancellation, the UAS MUST send a non-100 * provisional response at every minute, to handle the possibility of * lost provisional responses. * https://tools.ietf.org/html/rfc3261#section-13.3.1.1 * @param options - Progress options bucket. */ progress(options = { statusCode: 180 }) { if (!this.progressable) { throw new TransactionStateError(`${this.message.method} not progressable in state ${this.transaction.state}.`); } // This response establishes a dialog... // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 if (!this.earlyDialog) { const transaction = this.transaction; if (!(transaction instanceof InviteServerTransaction)) { throw new Error("Transaction not instance of InviteClientTransaction."); } const state = Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag, true); this.earlyDialog = new SessionDialog(transaction, this.core, state); } // When a UAS responds to a request with a response that establishes a // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route // header field values from the request into the response (including the // URIs, URI parameters, and any Record-Route header field parameters, // whether they are known or unknown to the UAS) and MUST maintain the // order of those values. The UAS MUST add a Contact header field to // the response. The Contact header field contains an address where the // UAS would like to be contacted for subsequent requests in the dialog // (which includes the ACK for a 2xx response in the case of an INVITE). // Generally, the host portion of this URI is the IP address or FQDN of // the host. The URI provided in the Contact header field MUST be a SIP // or SIPS URI. If the request that initiated the dialog contained a // SIPS URI in the Request-URI or in the top Record-Route header field // value, if there was any, or the Contact header field if there was no // Record-Route header field, the Contact header field in the response // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the // same URI can be used in messages outside this dialog). The same way, // the scope of the URI in the Contact header field of the INVITE is not // limited to this dialog either. It can therefore be used in messages // to the UAC even outside this dialog. // https://tools.ietf.org/html/rfc3261#section-12.1.1 const recordRouteHeader = this.message .getHeaders("record-route") .map((header) => `Record-Route: ${header}`); const contactHeader = `Contact: ${this.core.configuration.contact}`; options.extraHeaders = options.extraHeaders || []; options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); options.extraHeaders.push(contactHeader); const response = super.progress(options); const session = this.earlyDialog; const result = Object.assign(Object.assign({}, response), { session }); // Update dialog signaling state if (options.body) { // Once the UAS has sent or received an answer to the initial // offer, it MUST NOT generate subsequent offers in any responses // to the initial INVITE. This means that a UAS based on this // specification alone can never generate subsequent offers until // completion of the initial transaction. // https://tools.ietf.org/html/rfc3261#section-13.2.1 if (this.earlyDialog.signalingState !== SignalingState.Stable) { this.earlyDialog.signalingStateTransition(options.body); } } return result; } /** * 13.3.1.2 The INVITE is Redirected * If the UAS decides to redirect the call, a 3xx response is sent. A * 300 (Multiple Choices), 301 (Moved Permanently) or 302 (Moved * Temporarily) response SHOULD contain a Contact header field * containing one or more URIs of new addresses to be tried. The * response is passed to the INVITE server transaction, which will deal * with its retransmissions. * https://tools.ietf.org/html/rfc3261#section-13.3.1.2 * @param contacts - Contacts to redirect to. * @param options - Redirect options bucket. */ redirect(contacts, options = { statusCode: 302 }) { return super.redirect(contacts, options); } /** * 13.3.1.3 The INVITE is Rejected * A common scenario occurs when the callee is currently not willing or * able to take additional calls at this end system. A 486 (Busy Here) * SHOULD be returned in such a scenario. * https://tools.ietf.org/html/rfc3261#section-13.3.1.3 * @param options - Reject options bucket. */ reject(options = { statusCode: 486 }) { return super.reject(options); } } /** * MESSAGE UAS. * @public */ class MessageUserAgentClient extends UserAgentClient { constructor(core, message, delegate) { super(NonInviteClientTransaction, core, message, delegate); } } /** * MESSAGE UAS. * @public */ class MessageUserAgentServer extends UserAgentServer { constructor(core, message, delegate) { super(NonInviteServerTransaction, core, message, delegate); this.core = core; } } /** * PUBLISH UAC. * @public */ class PublishUserAgentClient extends UserAgentClient { constructor(core, message, delegate) { super(NonInviteClientTransaction, core, message, delegate); } } /** * REGISTER UAC. * @public */ class RegisterUserAgentClient extends UserAgentClient { constructor(core, message, delegate) { super(NonInviteClientTransaction, core, message, delegate); } } /** * REGISTER UAS. * @public */ class RegisterUserAgentServer extends UserAgentServer { constructor(core, message, delegate) { super(NonInviteServerTransaction, core, message, delegate); this.core = core; } } /** * SUBSCRIBE UAC. * @remarks * 4.1. Subscriber Behavior * https://tools.ietf.org/html/rfc6665#section-4.1 * * User agent client for installation of a single subscription per SUBSCRIBE request. * TODO: Support for installation of multiple subscriptions on forked SUBSCRIBE reqeuests. * @public */ class SubscribeUserAgentClient extends UserAgentClient { constructor(core, message, delegate) { // Get event from request message. const event = message.getHeader("Event"); if (!event) { throw new Error("Event undefined"); } // Get expires from reqeust message. const expires = message.getHeader("Expires"); if (!expires) { throw new Error("Expires undefined"); } super(NonInviteClientTransaction, core, message, delegate); this.delegate = delegate; // FIXME: Subscriber id should also be matching on event id. this.subscriberId = message.callId + message.fromTag + event; this.subscriptionExpiresRequested = this.subscriptionExpires = Number(expires); this.subscriptionEvent = event; this.subscriptionState = SubscriptionState.NotifyWait; // Start waiting for a NOTIFY we can use to create a subscription. this.waitNotifyStart(); } /** * Destructor. * Note that Timer N may live on waiting for an initial NOTIFY and * the delegate may still receive that NOTIFY. If you don't want * that behavior then either clear the delegate so the delegate * doesn't get called (a 200 will be sent in response to the NOTIFY) * or call `waitNotifyStop` which will clear Timer N and remove this * UAC from the core (a 481 will be sent in response to the NOTIFY). */ dispose() { super.dispose(); } /** * Handle out of dialog NOTIFY assoicated with SUBSCRIBE request. * This is the first NOTIFY received after the SUBSCRIBE request. * @param uas - User agent server handling the subscription creating NOTIFY. */ onNotify(uas) { // NOTIFY requests are matched to such SUBSCRIBE requests if they // contain the same "Call-ID", a "To" header field "tag" parameter that // matches the "From" header field "tag" parameter of the SUBSCRIBE // request, and the same "Event" header field. Rules for comparisons of // the "Event" header fields are described in Section 8.2.1. // https://tools.ietf.org/html/rfc6665#section-4.4.1 const event = uas.message.parseHeader("Event").event; if (!event || event !== this.subscriptionEvent) { this.logger.warn(`Failed to parse event.`); uas.reject({ statusCode: 489 }); return; } // NOTIFY requests MUST contain "Subscription-State" header fields that // indicate the status of the subscription. // https://tools.ietf.org/html/rfc6665#section-4.1.3 const subscriptionState = uas.message.parseHeader("Subscription-State"); if (!subscriptionState || !subscriptionState.state) { this.logger.warn("Failed to parse subscription state."); uas.reject({ statusCode: 489 }); return; } // Validate subscription state. const state = subscriptionState.state; switch (state) { case "pending": break; case "active": break; case "terminated": break; default: this.logger.warn(`Invalid subscription state ${state}`); uas.reject({ statusCode: 489 }); return; } // Dialogs usages are created upon completion of a NOTIFY transaction // for a new subscription, unless the NOTIFY request contains a // "Subscription-State" of "terminated." // https://tools.ietf.org/html/rfc6665#section-4.4.1 if (state !== "terminated") { // The Contact header field MUST be present and contain exactly one SIP // or SIPS URI in any request that can result in the establishment of a // dialog. // https://tools.ietf.org/html/rfc3261#section-8.1.1.8 const contact = uas.message.parseHeader("contact"); if (!contact) { this.logger.warn("Failed to parse contact."); uas.reject({ statusCode: 489 }); return; } } // In accordance with the rules for proxying non-INVITE requests as // defined in [RFC3261], successful SUBSCRIBE requests will receive only // one 200-class response; however, due to forking, the subscription may // have been accepted by multiple nodes. The subscriber MUST therefore // be prepared to receive NOTIFY requests with "From:" tags that differ // from the "To:" tag received in the SUBSCRIBE 200-class response. // // If multiple NOTIFY requests are received in different dialogs in // response to a single SUBSCRIBE request, each dialog represents a // different destination to which the SUBSCRIBE request was forked. // Subscriber handling in such situations varies by event package; see // Section 5.4.9 for details. // https://tools.ietf.org/html/rfc6665#section-4.1.4 // Each event package MUST specify whether forked SUBSCRIBE requests are // allowed to install multiple subscriptions. // // If such behavior is not allowed, the first potential dialog- // establishing message will create a dialog. All subsequent NOTIFY // requests that correspond to the SUBSCRIBE request (i.e., have // matching "To", "From", "Call-ID", and "Event" header fields, as well // as "From" header field "tag" parameter and "Event" header field "id" // parameter) but that do not match the dialog would be rejected with a // 481 response. Note that the 200-class response to the SUBSCRIBE // request can arrive after a matching NOTIFY request has been received; // such responses might not correlate to the same dialog established by // the NOTIFY request. Except as required to complete the SUBSCRIBE // transaction, such non-matching 200-class responses are ignored. // // If installing of multiple subscriptions by way of a single forked // SUBSCRIBE request is allowed, the subscriber establishes a new dialog // towards each notifier by returning a 200-class response to each // NOTIFY request. Each dialog is then handled as its own entity and is // refreshed independently of the other dialogs. // // In the case that multiple subscriptions are allowed, the event // package MUST specify whether merging of the notifications to form a // single state is required, and how such merging is to be performed. // Note that it is possible that some event packages may be defined in // such a way that each dialog is tied to a mutually exclusive state // that is unaffected by the other dialogs; this MUST be clearly stated // if it is the case. // https://tools.ietf.org/html/rfc6665#section-5.4.9 // *** NOTE: This implementation is only for event packages which // do not allow forked requests to install muliple subscriptions. // As such and in accordance with the specificaiton, we stop waiting // and any future NOTIFY requests will be rejected with a 481. if (this.dialog) { throw new Error("Dialog already created. This implementation only supports install of single subscriptions."); } this.waitNotifyStop(); // Update expires. this.subscriptionExpires = subscriptionState.expires ? Math.min(this.subscriptionExpires, Math.max(subscriptionState.expires, 0)) : this.subscriptionExpires; // Update subscriptoin state. switch (state) { case "pending": this.subscriptionState = SubscriptionState.Pending; break; case "active": this.subscriptionState = SubscriptionState.Active; break; case "terminated": this.subscriptionState = SubscriptionState.Terminated; break; default: throw new Error(`Unrecognized state ${state}.`); } // Dialogs usages are created upon completion of a NOTIFY transaction // for a new subscription, unless the NOTIFY request contains a // "Subscription-State" of "terminated." // https://tools.ietf.org/html/rfc6665#section-4.4.1 if (this.subscriptionState !== SubscriptionState.Terminated) { // Because the dialog usage is established by the NOTIFY request, the // route set at the subscriber is taken from the NOTIFY request itself, // as opposed to the route set present in the 200-class response to the // SUBSCRIBE request. // https://tools.ietf.org/html/rfc6665#section-4.4.1 const dialogState = SubscriptionDialog.initialDialogStateForSubscription(this.message, uas.message); // Subscription Initiated! :) this.dialog = new SubscriptionDialog(this.subscriptionEvent, this.subscriptionExpires, this.subscriptionState, this.core, dialogState); } // Delegate. if (this.delegate && this.delegate.onNotify) { const request = uas; const subscription = this.dialog; this.delegate.onNotify({ request, subscription }); } else { uas.accept(); } } waitNotifyStart() { if (!this.N) { // Add ourselves to the core's subscriber map. // This allows the core to route out of dialog NOTIFY messages to us. this.core.subscribers.set(this.subscriberId, this); this.N = setTimeout(() => this.timer_N(), Timers.TIMER_N); } } waitNotifyStop() { if (this.N) { // Remove ourselves to the core's subscriber map. // Any future out of dialog NOTIFY messages will be rejected with a 481. this.core.subscribers.delete(this.subscriberId); clearTimeout(this.N); this.N = undefined; } } /** * Receive a response from the transaction layer. * @param message - Incoming response message. */ receiveResponse(message) { if (!this.authenticationGuard(message)) { return; } if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { // The "Expires" header field in a 200-class response to SUBSCRIBE // request indicates the actual duration for which the subscription will // remain active (unless refreshed). The received value might be // smaller than the value indicated in the SUBSCRIBE request but cannot // be larger; see Section 4.2.1 for details. // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 // The "Expires" values present in SUBSCRIBE 200-class responses behave // in the same way as they do in REGISTER responses: the server MAY // shorten the interval but MUST NOT lengthen it. // // If the duration specified in a SUBSCRIBE request is unacceptably // short, the notifier may be able to send a 423 response, as // described earlier in this section. // // 200-class responses to SUBSCRIBE requests will not generally contain // any useful information beyond subscription duration; their primary // purpose is to serve as a reliability mechanism. State information // will be communicated via a subsequent NOTIFY request from the // notifier. // https://tools.ietf.org/html/rfc6665#section-4.2.1.1 const expires = message.getHeader("Expires"); if (!expires) { this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); } else { const subscriptionExpiresReceived = Number(expires); if (subscriptionExpiresReceived > this.subscriptionExpiresRequested) { this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"); } if (subscriptionExpiresReceived < this.subscriptionExpires) { this.subscriptionExpires = subscriptionExpiresReceived; } } // If a NOTIFY arrived before 200-class response a dialog may have been created. // Updated the dialogs expiration only if this indicates earlier expiration. if (this.dialog) { if (this.dialog.subscriptionExpires > this.subscriptionExpires) { this.dialog.subscriptionExpires = this.subscriptionExpires; } } } if (message.statusCode && message.statusCode >= 300 && message.statusCode < 700) { this.waitNotifyStop(); // No NOTIFY will be sent after a negative final response. } super.receiveResponse(message); } /** * To ensure that subscribers do not wait indefinitely for a * subscription to be established, a subscriber starts a Timer N, set to * 64*T1, when it sends a SUBSCRIBE request. If this Timer N expires * prior to the receipt of a NOTIFY request, the subscriber considers * the subscription failed, and cleans up any state associated with the * subscription attempt. * https://tools.ietf.org/html/rfc6665#section-4.1.2.4 */ timer_N() { this.logger.warn(`Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY.`); this.waitNotifyStop(); if (this.delegate && this.delegate.onNotifyTimeout) { this.delegate.onNotifyTimeout(); } } } /** * SUBSCRIBE UAS. * @public */ class SubscribeUserAgentServer extends UserAgentServer { constructor(core, message, delegate) { super(NonInviteServerTransaction, core, message, delegate); this.core = core; } } /** * This is ported from UA.C.ACCEPTED_BODY_TYPES. * FIXME: TODO: Should be configurable/variable. */ const acceptedBodyTypes = [ "application/sdp", "application/dtmf-relay" ]; /** * User Agent Core. * @remarks * Core designates the functions specific to a particular type * of SIP entity, i.e., specific to either a stateful or stateless * proxy, a user agent or registrar. All cores, except those for * the stateless proxy, are transaction users. * https://tools.ietf.org/html/rfc3261#section-6 * * UAC Core: The set of processing functions required of a UAC that * reside above the transaction and transport layers. * https://tools.ietf.org/html/rfc3261#section-6 * * UAS Core: The set of processing functions required at a UAS that * resides above the transaction and transport layers. * https://tools.ietf.org/html/rfc3261#section-6 * @public */ class UserAgentCore { /** * Constructor. * @param configuration - Configuration. * @param delegate - Delegate. */ constructor(configuration, delegate = {}) { /** UACs. */ this.userAgentClients = new Map(); /** UASs. */ this.userAgentServers = new Map(); this.configuration = configuration; this.delegate = delegate; this.dialogs = new Map(); this.subscribers = new Map(); this.logger = configuration.loggerFactory.getLogger("sip.user-agent-core"); } /** Destructor. */ dispose() { this.reset(); } /** Reset. */ reset() { this.dialogs.forEach((dialog) => dialog.dispose()); this.dialogs.clear(); this.subscribers.forEach((subscriber) => subscriber.dispose()); this.subscribers.clear(); this.userAgentClients.forEach((uac) => uac.dispose()); this.userAgentClients.clear(); this.userAgentServers.forEach((uac) => uac.dispose()); this.userAgentServers.clear(); } /** Logger factory. */ get loggerFactory() { return this.configuration.loggerFactory; } /** Transport. */ get transport() { const transport = this.configuration.transportAccessor(); if (!transport) { throw new Error("Transport undefined."); } return transport; } /** * Send INVITE. * @param request - Outgoing request. * @param delegate - Request delegate. */ invite(request, delegate) { return new InviteUserAgentClient(this, request, delegate); } /** * Send MESSAGE. * @param request - Outgoing request. * @param delegate - Request delegate. */ message(request, delegate) { return new MessageUserAgentClient(this, request, delegate); } /** * Send PUBLISH. * @param request - Outgoing request. * @param delegate - Request delegate. */ publish(request, delegate) { return new PublishUserAgentClient(this, request, delegate); } /** * Send REGISTER. * @param request - Outgoing request. * @param delegate - Request delegate. */ register(request, delegate) { return new RegisterUserAgentClient(this, request, delegate); } /** * Send SUBSCRIBE. * @param request - Outgoing request. * @param delegate - Request delegate. */ subscribe(request, delegate) { return new SubscribeUserAgentClient(this, request, delegate); } /** * Send a request. * @param request - Outgoing request. * @param delegate - Request delegate. */ request(request, delegate) { return new UserAgentClient(NonInviteClientTransaction, this, request, delegate); } /** * Outgoing request message factory function. * @param method - Method. * @param requestURI - Request-URI. * @param fromURI - From URI. * @param toURI - To URI. * @param options - Request options. * @param extraHeaders - Extra headers to add. * @param body - Message body. */ makeOutgoingRequestMessage(method, requestURI, fromURI, toURI, options, extraHeaders, body) { // default values from user agent configuration const callIdPrefix = this.configuration.sipjsId; const fromDisplayName = this.configuration.displayName; const forceRport = this.configuration.viaForceRport; const hackViaTcp = this.configuration.hackViaTcp; const optionTags = this.configuration.supportedOptionTags.slice(); if (method === C.REGISTER) { optionTags.push("path", "gruu"); } if (method === C.INVITE && (this.configuration.contact.pubGruu || this.configuration.contact.tempGruu)) { optionTags.push("gruu"); } const routeSet = this.configuration.routeSet; const userAgentString = this.configuration.userAgentHeaderFieldValue; const viaHost = this.configuration.viaHost; const defaultOptions = { callIdPrefix, forceRport, fromDisplayName, hackViaTcp, optionTags, routeSet, userAgentString, viaHost, }; // merge provided options with default options const requestOptions = Object.assign(Object.assign({}, defaultOptions), options); return new OutgoingRequestMessage(method, requestURI, fromURI, toURI, requestOptions, extraHeaders, body); } /** * Handle an incoming request message from the transport. * @param message - Incoming request message from transport layer. */ receiveIncomingRequestFromTransport(message) { this.receiveRequestFromTransport(message); } /** * Handle an incoming response message from the transport. * @param message - Incoming response message from transport layer. */ receiveIncomingResponseFromTransport(message) { this.receiveResponseFromTransport(message); } /** * A stateless UAS is a UAS that does not maintain transaction state. * It replies to requests normally, but discards any state that would * ordinarily be retained by a UAS after a response has been sent. If a * stateless UAS receives a retransmission of a request, it regenerates * the response and re-sends it, just as if it were replying to the first * instance of the request. A UAS cannot be stateless unless the request * processing for that method would always result in the same response * if the requests are identical. This rules out stateless registrars, * for example. Stateless UASs do not use a transaction layer; they * receive requests directly from the transport layer and send responses * directly to the transport layer. * https://tools.ietf.org/html/rfc3261#section-8.2.7 * @param message - Incoming request message to reply to. * @param statusCode - Status code to reply with. */ replyStateless(message, options) { const userAgent = this.configuration.userAgentHeaderFieldValue; const supported = this.configuration.supportedOptionTagsResponse; options = Object.assign(Object.assign({}, options), { userAgent, supported }); const response = constructOutgoingResponse(message, options); this.transport.send(response.message).catch((error) => { // If the transport rejects, it SHOULD reject with a TransportError. // But the transport may be external code, so we are careful... if (error instanceof Error) { this.logger.error(error.message); } this.logger.error(`Transport error occurred sending stateless reply to ${message.method} request.`); // TODO: Currently there is no hook to provide notification that a transport error occurred // and throwing would result in an uncaught error (in promise), so we siliently eat the error. // Furthermore, silienty eating stateless reply transport errors is arguably what we want to do here. }); return response; } /** * In Section 18.2.1, replace the last paragraph with: * * Next, the server transport attempts to match the request to a * server transaction. It does so using the matching rules described * in Section 17.2.3. If a matching server transaction is found, the * request is passed to that transaction for processing. If no match * is found, the request is passed to the core, which may decide to * construct a new server transaction for that request. * https://tools.ietf.org/html/rfc6026#section-8.10 * @param message - Incoming request message from transport layer. */ receiveRequestFromTransport(message) { // When a request is received from the network by the server, it has to // be matched to an existing transaction. This is accomplished in the // following manner. // // The branch parameter in the topmost Via header field of the request // is examined. If it is present and begins with the magic cookie // "z9hG4bK", the request was generated by a client transaction // compliant to this specification. Therefore, the branch parameter // will be unique across all transactions sent by that client. The // request matches a transaction if: // // 1. the branch parameter in the request is equal to the one in the // top Via header field of the request that created the // transaction, and // // 2. the sent-by value in the top Via of the request is equal to the // one in the request that created the transaction, and // // 3. the method of the request matches the one that created the // transaction, except for ACK, where the method of the request // that created the transaction is INVITE. // // This matching rule applies to both INVITE and non-INVITE transactions // alike. // // The sent-by value is used as part of the matching process because // there could be accidental or malicious duplication of branch // parameters from different clients. // https://tools.ietf.org/html/rfc3261#section-17.2.3 const transactionId = message.viaBranch; // FIXME: Currently only using rule 1... const uas = this.userAgentServers.get(transactionId); // When receiving an ACK that matches an existing INVITE server // transaction and that does not contain a branch parameter containing // the magic cookie defined in RFC 3261, the matching transaction MUST // be checked to see if it is in the "Accepted" state. If it is, then // the ACK must be passed directly to the transaction user instead of // being absorbed by the transaction state machine. This is necessary // as requests from RFC 2543 clients will not include a unique branch // parameter, and the mechanisms for calculating the transaction ID from // such a request will be the same for both INVITE and ACKs. // https://tools.ietf.org/html/rfc6026#section-6 // Any ACKs received from the network while in the "Accepted" state MUST be // passed directly to the TU and not absorbed. // https://tools.ietf.org/html/rfc6026#section-7.1 if (message.method === C.ACK) { if (uas && uas.transaction.state === TransactionState.Accepted) { if (uas instanceof InviteUserAgentServer) { // These are ACKs matching an INVITE server transaction. // These should never happen with RFC 3261 compliant user agents // (would be a broken ACK to negative final response or something) // but is apparently how RFC 2543 user agents do things. // We are not currently supporting this case. // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${transactionId}.`); return; } } } // The CANCEL method requests that the TU at the server side cancel a // pending transaction. The TU determines the transaction to be // cancelled by taking the CANCEL request, and then assuming that the // request method is anything but CANCEL or ACK and applying the // transaction matching procedures of Section 17.2.3. The matching // transaction is the one to be cancelled. // https://tools.ietf.org/html/rfc3261#section-9.2 if (message.method === C.CANCEL) { if (uas) { // Regardless of the method of the original request, as long as the // CANCEL matched an existing transaction, the UAS answers the CANCEL // request itself with a 200 (OK) response. // https://tools.ietf.org/html/rfc3261#section-9.2 this.replyStateless(message, { statusCode: 200 }); // If the transaction for the original request still exists, the behavior // of the UAS on receiving a CANCEL request depends on whether it has already // sent a final response for the original request. If it has, the CANCEL // request has no effect on the processing of the original request, no // effect on any session state, and no effect on the responses generated // for the original request. If the UAS has not issued a final response // for the original request, its behavior depends on the method of the // original request. If the original request was an INVITE, the UAS // SHOULD immediately respond to the INVITE with a 487 (Request // Terminated). // https://tools.ietf.org/html/rfc3261#section-9.2 if (uas.transaction instanceof InviteServerTransaction && uas.transaction.state === TransactionState.Proceeding) { if (uas instanceof InviteUserAgentServer) { uas.receiveCancel(message); } // A CANCEL request has no impact on the processing of // transactions with any other method defined in this specification. // https://tools.ietf.org/html/rfc3261#section-9.2 } } else { // If the UAS did not find a matching transaction for the CANCEL // according to the procedure above, it SHOULD respond to the CANCEL // with a 481 (Call Leg/Transaction Does Not Exist). // https://tools.ietf.org/html/rfc3261#section-9.2 this.replyStateless(message, { statusCode: 481 }); } return; } // If a matching server transaction is found, the request is passed to that // transaction for processing. // https://tools.ietf.org/html/rfc6026#section-8.10 if (uas) { uas.transaction.receiveRequest(message); return; } // If no match is found, the request is passed to the core, which may decide to // construct a new server transaction for that request. // https://tools.ietf.org/html/rfc6026#section-8.10 this.receiveRequest(message); return; } /** * UAC and UAS procedures depend strongly on two factors. First, based * on whether the request or response is inside or outside of a dialog, * and second, based on the method of a request. Dialogs are discussed * thoroughly in Section 12; they represent a peer-to-peer relationship * between user agents and are established by specific SIP methods, such * as INVITE. * @param message - Incoming request message. */ receiveRequest(message) { // 8.2 UAS Behavior // UASs SHOULD process the requests in the order of the steps that // follow in this section (that is, starting with authentication, then // inspecting the method, the header fields, and so on throughout the // remainder of this section). // https://tools.ietf.org/html/rfc3261#section-8.2 // 8.2.1 Method Inspection // Once a request is authenticated (or authentication is skipped), the // UAS MUST inspect the method of the request. If the UAS recognizes // but does not support the method of a request, it MUST generate a 405 // (Method Not Allowed) response. Procedures for generating responses // are described in Section 8.2.6. The UAS MUST also add an Allow // header field to the 405 (Method Not Allowed) response. The Allow // header field MUST list the set of methods supported by the UAS // generating the message. // https://tools.ietf.org/html/rfc3261#section-8.2.1 if (AllowedMethods.indexOf(message.method) === -1) { const allowHeader = "Allow: " + AllowedMethods.toString(); this.replyStateless(message, { statusCode: 405, extraHeaders: [allowHeader] }); return; } // 8.2.2 Header Inspection // https://tools.ietf.org/html/rfc3261#section-8.2.2 if (!message.ruri) { // FIXME: A request message should always have an ruri throw new Error("Request-URI undefined."); } // 8.2.2.1 To and Request-URI // If the Request-URI uses a scheme not supported by the UAS, it SHOULD // reject the request with a 416 (Unsupported URI Scheme) response. // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 if (message.ruri.scheme !== "sip") { this.replyStateless(message, { statusCode: 416 }); return; } // 8.2.2.1 To and Request-URI // If the Request-URI does not identify an address that the // UAS is willing to accept requests for, it SHOULD reject // the request with a 404 (Not Found) response. // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 const ruri = message.ruri; const ruriMatches = (uri) => { return !!uri && uri.user === ruri.user; }; if (!ruriMatches(this.configuration.aor) && !(ruriMatches(this.configuration.contact.uri) || ruriMatches(this.configuration.contact.pubGruu) || ruriMatches(this.configuration.contact.tempGruu))) { this.logger.warn("Request-URI does not point to us."); if (message.method !== C.ACK) { this.replyStateless(message, { statusCode: 404 }); } return; } // 8.2.2.1 To and Request-URI // Other potential sources of received Request-URIs include // the Contact header fields of requests and responses sent by the UA // that establish or refresh dialogs. // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 if (message.method === C.INVITE) { if (!message.hasHeader("Contact")) { this.replyStateless(message, { statusCode: 400, reasonPhrase: "Missing Contact Header" }); return; } } // 8.2.2.2 Merged Requests // If the request has no tag in the To header field, the UAS core MUST // check the request against ongoing transactions. If the From tag, // Call-ID, and CSeq exactly match those associated with an ongoing // transaction, but the request does not match that transaction (based // on the matching rules in Section 17.2.3), the UAS core SHOULD // generate a 482 (Loop Detected) response and pass it to the server // transaction. // // The same request has arrived at the UAS more than once, following // different paths, most likely due to forking. The UAS processes // the first such request received and responds with a 482 (Loop // Detected) to the rest of them. // https://tools.ietf.org/html/rfc3261#section-8.2.2.2 if (!message.toTag) { const transactionId = message.viaBranch; if (!this.userAgentServers.has(transactionId)) { const mergedRequest = Array.from(this.userAgentServers.values()) .some((uas) => uas.transaction.request.fromTag === message.fromTag && uas.transaction.request.callId === message.callId && uas.transaction.request.cseq === message.cseq); if (mergedRequest) { this.replyStateless(message, { statusCode: 482 }); return; } } } // 8.2.2.3 Require // https://tools.ietf.org/html/rfc3261#section-8.2.2.3 // TODO // 8.2.3 Content Processing // https://tools.ietf.org/html/rfc3261#section-8.2.3 // TODO // 8.2.4 Applying Extensions // https://tools.ietf.org/html/rfc3261#section-8.2.4 // TODO // 8.2.5 Processing the Request // Assuming all of the checks in the previous subsections are passed, // the UAS processing becomes method-specific. // https://tools.ietf.org/html/rfc3261#section-8.2.5 // The UAS will receive the request from the transaction layer. If the // request has a tag in the To header field, the UAS core computes the // dialog identifier corresponding to the request and compares it with // existing dialogs. If there is a match, this is a mid-dialog request. // In that case, the UAS first applies the same processing rules for // requests outside of a dialog, discussed in Section 8.2. // https://tools.ietf.org/html/rfc3261#section-12.2.2 if (message.toTag) { this.receiveInsideDialogRequest(message); } else { this.receiveOutsideDialogRequest(message); } return; } /** * Once a dialog has been established between two UAs, either of them * MAY initiate new transactions as needed within the dialog. The UA * sending the request will take the UAC role for the transaction. The * UA receiving the request will take the UAS role. Note that these may * be different roles than the UAs held during the transaction that * established the dialog. * https://tools.ietf.org/html/rfc3261#section-12.2 * @param message - Incoming request message. */ receiveInsideDialogRequest(message) { // NOTIFY requests are matched to such SUBSCRIBE requests if they // contain the same "Call-ID", a "To" header field "tag" parameter that // matches the "From" header field "tag" parameter of the SUBSCRIBE // request, and the same "Event" header field. Rules for comparisons of // the "Event" header fields are described in Section 8.2.1. // https://tools.ietf.org/html/rfc6665#section-4.4.1 if (message.method === C.NOTIFY) { const event = message.parseHeader("Event"); if (!event || !event.event) { this.replyStateless(message, { statusCode: 489 }); return; } // FIXME: Subscriber id should also matching on event id. const subscriberId = message.callId + message.toTag + event.event; const subscriber = this.subscribers.get(subscriberId); if (subscriber) { const uas = new NotifyUserAgentServer(this, message); subscriber.onNotify(uas); return; } } // Requests sent within a dialog, as any other requests, are atomic. If // a particular request is accepted by the UAS, all the state changes // associated with it are performed. If the request is rejected, none // of the state changes are performed. // // Note that some requests, such as INVITEs, affect several pieces of // state. // // The UAS will receive the request from the transaction layer. If the // request has a tag in the To header field, the UAS core computes the // dialog identifier corresponding to the request and compares it with // existing dialogs. If there is a match, this is a mid-dialog request. // https://tools.ietf.org/html/rfc3261#section-12.2.2 const dialogId = message.callId + message.toTag + message.fromTag; const dialog = this.dialogs.get(dialogId); if (dialog) { // [Sip-implementors] Reg. SIP reinvite, UPDATE and OPTIONS // You got the question right. // // And you got the right answer too. :-) // // Thanks, // Paul // // Robert Sparks wrote: // > So I've lost track of the question during the musing. // > // > I _think_ the fundamental question being asked is this: // > // > Is an endpoint required to reject (with a 481) an OPTIONS request that // > arrives with at to-tag but does not match any existing dialog state. // > (Assuming some earlier requirement hasn't forced another error code). Or // > is it OK if it just sends // > a 200 OK anyhow. // > // > My take on the collection of specs is that its _not_ ok for it to send // > the 200 OK anyhow and that it is required to send // > the 481. I base this primarily on these sentences from 11.2 in 3261: // > // > The response to an OPTIONS is constructed using the standard rules // > for a SIP response as discussed in Section 8.2.6. The response code // > chosen MUST be the same that would have been chosen had the request // > been an INVITE. // > // > Did I miss the point of the question? // > // > On May 15, 2008, at 12:48 PM, Paul Kyzivat wrote: // > // >> [Including Robert in hopes of getting his insight on this.] // https://lists.cs.columbia.edu/pipermail/sip-implementors/2008-May/019178.html // // Requests that do not change in any way the state of a dialog may be // received within a dialog (for example, an OPTIONS request). They are // processed as if they had been received outside the dialog. // https://tools.ietf.org/html/rfc3261#section-12.2.2 if (message.method === C.OPTIONS) { const allowHeader = "Allow: " + AllowedMethods.toString(); const acceptHeader = "Accept: " + acceptedBodyTypes.toString(); this.replyStateless(message, { statusCode: 200, extraHeaders: [allowHeader, acceptHeader] }); return; } // Pass the incoming request to the dialog for further handling. dialog.receiveRequest(message); return; } // The most important behaviors of a stateless UAS are the following: // ... // o A stateless UAS MUST ignore ACK requests. // ... // https://tools.ietf.org/html/rfc3261#section-8.2.7 if (message.method === C.ACK) { // If a final response to an INVITE was sent statelessly, // the corresponding ACK: // - will not match an existing transaction // - may have tag in the To header field // - not not match any existing dialogs // Absorb unmatched ACKs. return; } // If the request has a tag in the To header field, but the dialog // identifier does not match any existing dialogs, the UAS may have // crashed and restarted, or it may have received a request for a // different (possibly failed) UAS (the UASs can construct the To tags // so that a UAS can identify that the tag was for a UAS for which it is // providing recovery). Another possibility is that the incoming // request has been simply mis-routed. Based on the To tag, the UAS MAY // either accept or reject the request. Accepting the request for // acceptable To tags provides robustness, so that dialogs can persist // even through crashes. UAs wishing to support this capability must // take into consideration some issues such as choosing monotonically // increasing CSeq sequence numbers even across reboots, reconstructing // the route set, and accepting out-of-range RTP timestamps and sequence // numbers. // // If the UAS wishes to reject the request because it does not wish to // recreate the dialog, it MUST respond to the request with a 481 // (Call/Transaction Does Not Exist) status code and pass that to the // server transaction. // https://tools.ietf.org/html/rfc3261#section-12.2.2 this.replyStateless(message, { statusCode: 481 }); return; } /** * Assuming all of the checks in the previous subsections are passed, * the UAS processing becomes method-specific. * https://tools.ietf.org/html/rfc3261#section-8.2.5 * @param message - Incoming request message. */ receiveOutsideDialogRequest(message) { switch (message.method) { case C.ACK: // Absorb stray out of dialog ACKs break; case C.BYE: // If the BYE does not match an existing dialog, the UAS core SHOULD // generate a 481 (Call/Transaction Does Not Exist) response and pass // that to the server transaction. This rule means that a BYE sent // without tags by a UAC will be rejected. // https://tools.ietf.org/html/rfc3261#section-15.1.2 this.replyStateless(message, { statusCode: 481 }); break; case C.CANCEL: throw new Error(`Unexpected out of dialog request method ${message.method}.`); case C.INFO: // Use of the INFO method does not constitute a separate dialog usage. // INFO messages are always part of, and share the fate of, an invite // dialog usage [RFC5057]. INFO messages cannot be sent as part of // other dialog usages, or outside an existing dialog. // https://tools.ietf.org/html/rfc6086#section-1 this.replyStateless(message, { statusCode: 405 }); // Should never happen break; case C.INVITE: // https://tools.ietf.org/html/rfc3261#section-13.3.1 { const uas = new InviteUserAgentServer(this, message); this.delegate.onInvite ? this.delegate.onInvite(uas) : uas.reject(); } break; case C.MESSAGE: // MESSAGE requests are discouraged inside a dialog. Implementations // are restricted from creating a usage for the purpose of carrying a // sequence of MESSAGE requests (though some implementations use it that // way, against the standard recommendation). // https://tools.ietf.org/html/rfc5057#section-5.3 { const uas = new MessageUserAgentServer(this, message); this.delegate.onMessage ? this.delegate.onMessage(uas) : uas.accept(); } break; case C.NOTIFY: // Obsoleted by: RFC 6665 // If any non-SUBSCRIBE mechanisms are defined to create subscriptions, // it is the responsibility of the parties defining those mechanisms to // ensure that correlation of a NOTIFY message to the corresponding // subscription is possible. Designers of such mechanisms are also // warned to make a distinction between sending a NOTIFY message to a // subscriber who is aware of the subscription, and sending a NOTIFY // message to an unsuspecting node. The latter behavior is invalid, and // MUST receive a "481 Subscription does not exist" response (unless // some other 400- or 500-class error code is more applicable), as // described in section 3.2.4. In other words, knowledge of a // subscription must exist in both the subscriber and the notifier to be // valid, even if installed via a non-SUBSCRIBE mechanism. // https://tools.ietf.org/html/rfc3265#section-3.2 // // NOTIFY requests are sent to inform subscribers of changes in state to // which the subscriber has a subscription. Subscriptions are created // using the SUBSCRIBE method. In legacy implementations, it is // possible that other means of subscription creation have been used. // However, this specification does not allow the creation of // subscriptions except through SUBSCRIBE requests and (for backwards- // compatibility) REFER requests [RFC3515]. // https://tools.ietf.org/html/rfc6665#section-3.2 { const uas = new NotifyUserAgentServer(this, message); this.delegate.onNotify ? this.delegate.onNotify(uas) : uas.reject({ statusCode: 405 }); } break; case C.OPTIONS: // https://tools.ietf.org/html/rfc3261#section-11.2 { const allowHeader = "Allow: " + AllowedMethods.toString(); const acceptHeader = "Accept: " + acceptedBodyTypes.toString(); this.replyStateless(message, { statusCode: 200, extraHeaders: [allowHeader, acceptHeader] }); } break; case C.REFER: // https://tools.ietf.org/html/rfc3515#section-2.4.2 { const uas = new ReferUserAgentServer(this, message); this.delegate.onRefer ? this.delegate.onRefer(uas) : uas.reject({ statusCode: 405 }); } break; case C.REGISTER: // https://tools.ietf.org/html/rfc3261#section-10.3 { const uas = new RegisterUserAgentServer(this, message); this.delegate.onRegister ? this.delegate.onRegister(uas) : uas.reject({ statusCode: 405 }); } break; case C.SUBSCRIBE: // https://tools.ietf.org/html/rfc6665#section-4.2 { const uas = new SubscribeUserAgentServer(this, message); this.delegate.onSubscribe ? this.delegate.onSubscribe(uas) : uas.reject({ statusCode: 480 }); } break; default: throw new Error(`Unexpected out of dialog request method ${message.method}.`); } return; } /** * Responses are first processed by the transport layer and then passed * up to the transaction layer. The transaction layer performs its * processing and then passes the response up to the TU. The majority * of response processing in the TU is method specific. However, there * are some general behaviors independent of the method. * https://tools.ietf.org/html/rfc3261#section-8.1.3 * @param message - Incoming response message from transport layer. */ receiveResponseFromTransport(message) { // 8.1.3.1 Transaction Layer Errors // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 // Handled by transaction layer callbacks. // 8.1.3.2 Unrecognized Responses // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 // TODO // 8.1.3.3 Vias // https://tools.ietf.org/html/rfc3261#section-8.1.3.3 if (message.getHeaders("via").length > 1) { this.logger.warn("More than one Via header field present in the response, dropping"); return; } // 8.1.3.4 Processing 3xx Responses // https://tools.ietf.org/html/rfc3261#section-8.1.3.4 // TODO // 8.1.3.5 Processing 4xx Responses // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 // TODO // When the transport layer in the client receives a response, it has to // determine which client transaction will handle the response, so that // the processing of Sections 17.1.1 and 17.1.2 can take place. The // branch parameter in the top Via header field is used for this // purpose. A response matches a client transaction under two // conditions: // // 1. If the response has the same value of the branch parameter in // the top Via header field as the branch parameter in the top // Via header field of the request that created the transaction. // // 2. If the method parameter in the CSeq header field matches the // method of the request that created the transaction. The // method is needed since a CANCEL request constitutes a // different transaction, but shares the same value of the branch // parameter. // https://tools.ietf.org/html/rfc3261#section-17.1.3 const userAgentClientId = message.viaBranch + message.method; const userAgentClient = this.userAgentClients.get(userAgentClientId); // The client transport uses the matching procedures of Section // 17.1.3 to attempt to match the response to an existing // transaction. If there is a match, the response MUST be passed to // that transaction. Otherwise, any element other than a stateless // proxy MUST silently discard the response. // https://tools.ietf.org/html/rfc6026#section-8.9 if (userAgentClient) { userAgentClient.transaction.receiveResponse(message); } else { this.logger.warn(`Discarding unmatched ${message.statusCode} response to ${message.method} ${userAgentClientId}.`); } } } /** * Transport. * @remarks * Abstract transport layer base class. * @public */ class Transport extends EventEmitter { /** * Constructor * @param logger - Logger. * @param options - Options bucket. Deprecated. */ constructor(logger, options) { super(); this.logger = logger; } /** * Returns the promise designated by the child layer then emits a connected event. * Automatically emits an event upon resolution, unless overrideEvent is set. If you * override the event in this fashion, you should emit it in your implementation of connectPromise * @param options - Options bucket. */ connect(options = {}) { return this.connectPromise(options).then((data) => { if (!data.overrideEvent) { this.emit("connected"); } }); } /** * Sends a message then emits a 'messageSent' event. Automatically emits an * event upon resolution, unless data.overrideEvent is set. If you override * the event in this fashion, you should emit it in your implementation of sendPromise * Rejects with an Error if message fails to send. * @param message - Message. * @param options - Options bucket. */ send(message, options = {}) { // Error handling is independent of whether the message was a request or // response. // // If the transport user asks for a message to be sent over an // unreliable transport, and the result is an ICMP error, the behavior // depends on the type of ICMP error. Host, network, port or protocol // unreachable errors, or parameter problem errors SHOULD cause the // transport layer to inform the transport user of a failure in sending. // Source quench and TTL exceeded ICMP errors SHOULD be ignored. // // If the transport user asks for a request to be sent over a reliable // transport, and the result is a connection failure, the transport // layer SHOULD inform the transport user of a failure in sending. // https://tools.ietf.org/html/rfc3261#section-18.4 return this.sendPromise(message).then((result) => { if (!result.overrideEvent) { this.emit("messageSent", result.msg); } }); } /** * Returns the promise designated by the child layer then emits a * disconnected event. Automatically emits an event upon resolution, * unless overrideEvent is set. If you override the event in this fashion, * you should emit it in your implementation of disconnectPromise * @param options - Options bucket */ disconnect(options = {}) { return this.disconnectPromise(options).then((data) => { if (!data.overrideEvent) { this.emit("disconnected"); } }); } afterConnected(callback) { if (this.isConnected()) { callback(); } else { this.once("connected", callback); } } /** * Returns a promise which resolves once the UA is connected. DEPRECATION WARNING: just use afterConnected() */ waitForConnected() { // tslint:disable-next-line:no-console console.warn("DEPRECATION WARNING Transport.waitForConnected(): use afterConnected() instead"); return new Promise((resolve) => { this.afterConnected(resolve); }); } } /** * An exception indicating an unsupported content type prevented execution. * @public */ class ContentTypeUnsupportedError extends Exception { constructor(message) { super(message ? message : "Unsupported content type."); } } /** * An exception indicating an outstanding prior request prevented execution. * @public */ class RequestPendingError extends Exception { /** @internal */ constructor(message) { super(message ? message : "Request pending."); } } /** * An exception indicating a session description handler error occured. * @public */ class SessionDescriptionHandlerError extends Exception { constructor(message) { super(message ? message : "Unspecified session description handler error."); } } /** * An exception indicating the session terminated before the action completed. * @public */ class SessionTerminatedError extends Exception { constructor() { super("The session has terminated."); } } function defer() { const deferred = {}; deferred.promise = new Promise((resolve, reject) => { deferred.resolve = resolve; deferred.reject = reject; }); return deferred; } function reducePromises(arr, val) { return arr.reduce((acc, fn) => { acc = acc.then(fn); return acc; }, Promise.resolve(val)); } class SessionDescriptionHandler extends EventEmitter { constructor(logger, options) { super(); // private senderpara: RTCRtpSendParameters; this._methodStr = ""; // TODO: Validate the options this.options = options || {}; this.logger = logger; this.dtmfSender = undefined; this.shouldAcquireMedia = true; this.CONTENT_TYPE = "application/sdp"; this.C = { DIRECTION: { NULL: null, SENDRECV: "sendrecv", SENDONLY: "sendonly", RECVONLY: "recvonly", INACTIVE: "inactive" } }; this.logger.log("SessionDescriptionHandlerOptions: " + JSON.stringify(this.options)); this.direction = this.C.DIRECTION.NULL; this.modifiers = this.options.modifiers || []; if (!Array.isArray(this.modifiers)) { this.modifiers = [this.modifiers]; } this.iceGatheringTimeout = false; this.initPeerConnection(this.options.peerConnectionOptions); this.constraints = this.checkAndDefaultConstraints(this.options.constraints); } static defaultFactory(session, options) { const logger = session.userAgent.getLogger("sip.SessionDescriptionHandler", session.id); return new SessionDescriptionHandler(logger, options); } /** * Destructor */ close() { this.logger.log("closing PeerConnection"); // have to check signalingState since this.close() gets called multiple times if (this.peerConnection && this.peerConnection.signalingState !== "closed") { if (this.peerConnection.getSenders) { this.peerConnection.getSenders().forEach((sender) => { if (sender.track) { sender.track.stop(); } }); } else { this.logger.warn("Using getLocalStreams which is deprecated"); this.peerConnection.getLocalStreams().forEach((stream) => { stream.getTracks().forEach((track) => { track.stop(); }); }); } if (this.peerConnection.getReceivers) { this.peerConnection.getReceivers().forEach((receiver) => { if (receiver.track) { receiver.track.stop(); } }); } else { this.logger.warn("Using getRemoteStreams which is deprecated"); this.peerConnection.getRemoteStreams().forEach((stream) => { stream.getTracks().forEach((track) => { track.stop(); }); }); } this.resetIceGatheringComplete(); this.peerConnection.close(); } } /** * Gets the local description from the underlying media implementation * @param {Object} [options] Options object to be used by getDescription * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer * connection with the new options * @param {Array} [modifiers] Array with one time use description modifiers * @returns {Promise} Promise that resolves with the local description to be used for the session */ getDescription(options = {}, modifiers = []) { if (options.peerConnectionOptions) { this.initPeerConnection(options.peerConnectionOptions); } // Merge passed constraints with saved constraints and save let newConstraints = Object.assign({}, this.constraints, options.constraints); newConstraints = this.checkAndDefaultConstraints(newConstraints); if (JSON.stringify(newConstraints) !== JSON.stringify(this.constraints)) { this.constraints = newConstraints; this.shouldAcquireMedia = true; } if (options.RTCOfferOptions == null) { options.RTCOfferOptions = { iceRestart: false, offerToReceiveAudio: true, offerToReceiveVideo: true }; } if (options.RTCOfferOptions.offerToReceiveVideo == false) { // this.constraints.video = false; // options.constraints.video = false; this.shouldAcquireMedia = false; } if (!Array.isArray(modifiers)) { modifiers = [modifiers]; } modifiers = modifiers.concat(this.modifiers); // options.RTCOfferOptions = { // offerToReceiveAudio: false, // offerToReceiveVideo: false // }; return Promise.resolve().then(() => { // const methodName: string = this.hasOffer("remote") ? "createAnswer" : "createOffer"; // this._methodStr = methodName; // if (methodName == "createOffer") { // this.shouldAcquireMedia = true; // } if (this.shouldAcquireMedia) { return this.acquire(this.constraints).then(() => { this.shouldAcquireMedia = false; }); } }).then(() => this.createOfferOrAnswer(options.RTCOfferOptions, modifiers)) .then((description) => { if (description.sdp === undefined) { throw new SessionDescriptionHandlerError("SDP undefined."); } if (this.constraints.video == false) { let videoIndex = description.sdp.indexOf("m=video"); if (videoIndex > 0) { description.sdp = description.sdp.substring(0, videoIndex); } } // description.sdp = description.sdp.replace("sendrecv", "recvonly"); // description.sdp = description.sdp.replace("sendrecv", "recvonly"); // description.sdp = description.sdp.replace("recvonly", "sendrecv"); // description.sdp = description.sdp.replace("recvonly", "sendrecv"); this.emit("getDescription", description); return { body: description.sdp, contentType: this.CONTENT_TYPE }; }); } /** * Check if the Session Description Handler can handle the Content-Type described by a SIP Message * @param {String} contentType The content type that is in the SIP Message * @returns {boolean} */ hasDescription(contentType) { return contentType === this.CONTENT_TYPE; } /** * The modifier that should be used when the session would like to place the call on hold * @param {String} [sdp] The description that will be modified * @returns {Promise} Promise that resolves with modified SDP */ holdModifier(description) { if (!description.sdp) { return Promise.resolve(description); } if (!(/a=(sendrecv|sendonly|recvonly|inactive)/).test(description.sdp)) { description.sdp = description.sdp.replace(/(m=[^\r]*\r\n)/g, "$1a=sendonly\r\n"); } else { description.sdp = description.sdp.replace(/a=sendrecv\r\n/g, "a=sendonly\r\n"); description.sdp = description.sdp.replace(/a=recvonly\r\n/g, "a=inactive\r\n"); } return Promise.resolve(description); } /** * Set the remote description to the underlying media implementation * @param {String} sessionDescription The description provided by a SIP message to be set on the media implementation * @param {Object} [options] Options object to be used by getDescription * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer * connection with the new options * @param {Array} [modifiers] Array with one time use description modifiers * @returns {Promise} Promise that resolves once the description is set */ setDescription(sessionDescription, options = {}, modifiers = []) { if (options.peerConnectionOptions) { this.initPeerConnection(options.peerConnectionOptions); } if (!Array.isArray(modifiers)) { modifiers = [modifiers]; } modifiers = modifiers.concat(this.modifiers); const description = { type: this.hasOffer("local") ? "answer" : "offer", sdp: sessionDescription }; return Promise.resolve().then(() => { // Media should be acquired in getDescription unless we need to do it sooner for some reason (FF61+) if (this.shouldAcquireMedia && this.options.alwaysAcquireMediaFirst) { return this.acquire(this.constraints).then(() => { this.shouldAcquireMedia = false; }); } }).then(() => reducePromises(modifiers, description)) .catch((e) => { if (e instanceof SessionDescriptionHandlerError) { throw e; } let message = "The modifiers did not resolve successfully."; if (e.name) { message += " " + e.name; } if (e.message) { message += " " + e.message; } const error = new SessionDescriptionHandlerError(message); this.logger.error(message); this.emit("peerConnection-setRemoteDescriptionFailed", error); throw error; }).then((modifiedDescription) => { this.emit("setDescription", modifiedDescription); // modifiedDescription.sdp = modifiedDescription.sdp.replace("packetization-mode=1", "packetization-mode=1;x-google-start-bitrate=2000") return this.peerConnection.setRemoteDescription(modifiedDescription); }).catch((e) => { // Check the original SDP for video, and ensure that we have want to do audio fallback if ((/^m=video.+$/gm).test(sessionDescription) && !options.disableAudioFallback) { // Do not try to audio fallback again options.disableAudioFallback = true; // Remove video first, then do the other modifiers return this.setDescription(sessionDescription, options, [stripVideo].concat(modifiers)); } if (e instanceof SessionDescriptionHandlerError) { throw e; } let message = "The modifiers did not resolve successfully."; if (e.name) { message += " " + e.name; } if (e.message) { message += " " + e.message; } const error = new SessionDescriptionHandlerError(message); this.logger.error(message); this.emit("peerConnection-setRemoteDescriptionFailed", error); throw error; }).then(() => { if (this.peerConnection.getReceivers) { this.emit("setRemoteDescription", this.peerConnection.getReceivers()); } else { this.emit("setRemoteDescription", this.peerConnection.getRemoteStreams()); } this.emit("confirmed", this); }); } /** * Send DTMF via RTP (RFC 4733) * @param {String} tones A string containing DTMF digits * @param {Object} [options] Options object to be used by sendDtmf * @returns {boolean} true if DTMF send is successful, false otherwise */ sendDtmf(tones, options = {}) { if (!this.dtmfSender && this.hasBrowserGetSenderSupport()) { const senders = this.peerConnection.getSenders(); if (senders.length > 0) { this.dtmfSender = senders[0].dtmf; } } if (!this.dtmfSender && this.hasBrowserTrackSupport()) { const streams = this.peerConnection.getLocalStreams(); if (streams.length > 0) { const audioTracks = streams[0].getAudioTracks(); if (audioTracks.length > 0) { this.dtmfSender = this.peerConnection.createDTMFSender(audioTracks[0]); } } } if (!this.dtmfSender) { return false; } try { this.dtmfSender.insertDTMF(tones, options.duration, options.interToneGap); } catch (e) { if (e.type === "InvalidStateError" || e.type === "InvalidCharacterError") { this.logger.error(e); return false; } else { throw e; } } this.logger.log("DTMF sent via RTP: " + tones.toString()); return true; } /** * Get the direction of the session description * @returns {String} direction of the description */ getDirection() { return this.direction; } on(name, callback) { return super.on(name, callback); } getMediaStream(constraints) { // constraints = { // audio: {deviceId: {exact: "default"} }, // video: {deviceId: {exact: "c8e23370c8134f8523ee727948873c7d2a1010b298aa62364ab1bf394fec4ecc"}} // // video: {deviceId: {exact: "dcd54561d46e08074964cedf19fa4a0bfb0344532a34df3ef2db019ebac97f9d"}} // }; // if (this._methodStr == "createOffer") { // const mediaDevice = navigator.mediaDevices as any; // return mediaDevice.getDisplayMedia({video: true, audio: true}); // }else{ return navigator.mediaDevices.getUserMedia(constraints); // const mediaDevice = navigator.mediaDevices as any; // return mediaDevice.getDisplayMedia({video: true, audio: true}); // } } // Internal functions createOfferOrAnswer( // RTCOfferOptions: any = {}, RTCOfferOptions = { iceRestart: false, offerToReceiveAudio: true, offerToReceiveVideo: false }, modifiers = []) { const methodName = this.hasOffer("remote") ? "createAnswer" : "createOffer"; // this._methodStr = methodName; const pc = this.peerConnection; this.logger.log(methodName); const method = this.hasOffer("remote") ? pc.createAnswer : pc.createOffer; // RTCOfferOptions.offerToReceiveVideo = false; return method.apply(pc, RTCOfferOptions).catch((e) => { if (e instanceof SessionDescriptionHandlerError) { throw e; } let message = "peerConnection-" + methodName + " failed."; if (e.name) { message += " " + e.name; } if (e.message) { message += " " + e.message; } const error = new SessionDescriptionHandlerError(message); this.logger.error(message); this.emit("peerConnection-" + methodName + "Failed", error); throw error; }).then((sdp) => reducePromises(modifiers, this.createRTCSessionDescriptionInit(sdp))).then((sdp) => { // this.peerConnection.getSenders().forEach((sender: RTCRtpSender) => { // var para22 = sender.getParameters(); // para22.encodings[0] // sender.setParameters(para22); // }); this.resetIceGatheringComplete(); if (RTCOfferOptions.offerToReceiveVideo == false) { sdp.sdp = (sdp.sdp || "").replace("sendrecv", "recvonly"); sdp.sdp = (sdp.sdp || "").replace(/a=sendrecv\r\n/g, "a=recvonly\r\n"); } this.logger.log("Setting local sdp."); this.logger.log("sdp is " + sdp.sdp || "undefined"); return pc.setLocalDescription(sdp); }).catch((e) => { if (e instanceof SessionDescriptionHandlerError) { throw e; } let message = "peerConnection-" + methodName + " failed."; if (e.name) { message += " " + e.name; } if (e.message) { message += " " + e.message; } const error = new SessionDescriptionHandlerError(message); this.logger.error(message); this.emit("peerConnection-SetLocalDescriptionFailed", error); throw error; }).then(() => this.waitForIceGatheringComplete()) .then(() => { if (!this.peerConnection.localDescription) { throw new SessionDescriptionHandlerError("Missing local description."); } const localDescription = this.createRTCSessionDescriptionInit(this.peerConnection.localDescription); return reducePromises(modifiers, localDescription); }).then((localDescription) => { this.setDirection(localDescription.sdp || ""); return localDescription; }).catch((e) => { if (e instanceof SessionDescriptionHandlerError) { throw e; } let message = "Error."; if (e.name) { message += " " + e.name; } if (e.message) { message += " " + e.message; } const error = new SessionDescriptionHandlerError(message); this.logger.error(message); throw error; }); } // Creates an RTCSessionDescriptionInit from an RTCSessionDescription createRTCSessionDescriptionInit(RTCSessionDescription) { return { type: RTCSessionDescription.type, sdp: RTCSessionDescription.sdp }; } addDefaultIceCheckingTimeout(peerConnectionOptions) { if (peerConnectionOptions.iceCheckingTimeout === undefined) { peerConnectionOptions.iceCheckingTimeout = 1000; } return peerConnectionOptions; } addDefaultIceServers(rtcConfiguration) { if (!rtcConfiguration.iceServers) { rtcConfiguration.iceServers = [{ urls: "stun:stun.l.google.com:19302" }]; } return rtcConfiguration; } checkAndDefaultConstraints(constraints) { const defaultConstraints = { audio: true, video: !this.options.alwaysAcquireMediaFirst }; constraints = constraints || defaultConstraints; // Empty object check if (Object.keys(constraints).length === 0 && constraints.constructor === Object) { return defaultConstraints; } return constraints; } hasBrowserTrackSupport() { return Boolean(this.peerConnection.addTrack); } hasBrowserGetSenderSupport() { return Boolean(this.peerConnection.getSenders); } initPeerConnection(options = {}) { options = this.addDefaultIceCheckingTimeout(options); options.rtcConfiguration = options.rtcConfiguration || {}; options.rtcConfiguration = this.addDefaultIceServers(options.rtcConfiguration); this.logger.log("initPeerConnection"); if (this.peerConnection) { this.logger.log("Already have a peer connection for this session. Tearing down."); this.resetIceGatheringComplete(); this.peerConnection.close(); } this.peerConnection = new RTCPeerConnection(options.rtcConfiguration); this.logger.log("New peer connection created"); if ("ontrack" in this.peerConnection) { this.peerConnection.addEventListener("track", (e) => { this.logger.log("track added"); this.emit("addTrack", e); }); } else { this.logger.warn("Using onaddstream which is deprecated"); this.peerConnection.onaddstream = (e) => { this.logger.log("stream added"); this.emit("addStream", e); }; } this.peerConnection.onicecandidate = (e) => { this.emit("iceCandidate", e); if (e.candidate) { this.logger.log("ICE candidate received: " + (e.candidate.candidate === null ? null : e.candidate.candidate.trim())); } else if (e.candidate === null) { // indicates the end of candidate gathering this.logger.log("ICE candidate gathering complete"); this.triggerIceGatheringComplete(); } }; this.peerConnection.onicegatheringstatechange = () => { this.logger.log("RTCIceGatheringState changed: " + this.peerConnection.iceGatheringState); switch (this.peerConnection.iceGatheringState) { case "gathering": this.emit("iceGathering", this); if (!this.iceGatheringTimer && options.iceCheckingTimeout) { this.iceGatheringTimeout = false; this.iceGatheringTimer = setTimeout(() => { this.logger.log("RTCIceChecking Timeout Triggered after " + options.iceCheckingTimeout + " milliseconds"); this.iceGatheringTimeout = true; this.triggerIceGatheringComplete(); }, options.iceCheckingTimeout); } break; case "complete": this.triggerIceGatheringComplete(); break; } }; this.peerConnection.oniceconnectionstatechange = () => { let stateEvent; switch (this.peerConnection.iceConnectionState) { case "new": stateEvent = "iceConnection"; break; case "checking": stateEvent = "iceConnectionChecking"; break; case "connected": stateEvent = "iceConnectionConnected"; break; case "completed": stateEvent = "iceConnectionCompleted"; break; case "failed": stateEvent = "iceConnectionFailed"; break; case "disconnected": stateEvent = "iceConnectionDisconnected"; break; case "closed": stateEvent = "iceConnectionClosed"; break; default: this.logger.warn("Unknown iceConnection state: " + this.peerConnection.iceConnectionState); return; } this.logger.log("ICE Connection State changed to " + stateEvent); this.emit(stateEvent, this); }; } acquire(constraints) { // Default audio & video to true constraints = this.checkAndDefaultConstraints(constraints); return new Promise((resolve, reject) => { /* * Make the call asynchronous, so that ICCs have a chance * to define callbacks to `userMediaRequest` */ this.logger.log("acquiring local media"); this.emit("userMediaRequest", constraints); if (constraints.audio || constraints.video) { this.getMediaStream(constraints).then((streams) => { this.emit("addTrack"); this.emit("userMedia", streams); resolve(streams); }).catch((e) => { this.emit("userMediaFailed", e); reject(e); }); } else { // Local streams were explicitly excluded. resolve([]); } }).catch((e /* DOMException */ ) => { if (e instanceof SessionDescriptionHandlerError) { throw e; } let message = "Unable to acquire streams."; if (e.name) { message += " " + e.name; } if (e.message) { message += " " + e.message; } const error = new SessionDescriptionHandlerError(message); this.logger.error(message); // throw error; return []; //发起视频呼叫,如果没有摄像头,返回空,会自动协商成reconly }).then((streams) => { this.logger.log("acquired local media streams"); // if( constraints.video && this._methodStr == "createOffer" ) { // let screentrack = streams[0].getVideoTracks()[0]; // this.peerConnection.getSenders().forEach((sender) => { // if (sender.track && sender.track.kind == "video") { // sender.replaceTrack(screentrack) // } // }); // return [] // } // Remove old tracks if (this.peerConnection.removeTrack) { this.peerConnection.getSenders().forEach((sender) => { // if (sender.track && sender.track.kind == "video") { // sender.track.stop(); // } console.log("remove track " + sender.track); this.peerConnection.removeTrack(sender); }); } return streams; }).catch((e) => { if (e instanceof SessionDescriptionHandlerError) { throw e; } let message = "Error removing streams."; if (e.name) { message += " " + e.name; } if (e.message) { message += " " + e.message; } const error = new SessionDescriptionHandlerError(message); this.logger.error(message); throw error; }).then((streams) => { const streamsArr = [].concat(streams); streamsArr.forEach((stream) => { if (this.peerConnection.addTrack) { stream.getTracks().forEach((track) => { // console.log("add track " + track); this.peerConnection.addTrack(track, stream); }); } else { // Chrome 59 does not support addTrack this.peerConnection.addStream(stream); } }); return Promise.resolve(); }).catch((e) => { if (e instanceof SessionDescriptionHandlerError) { throw e; } let message = "Error adding streams."; if (e.name) { message += " " + e.name; } if (e.message) { message += " " + e.message; } const error = new SessionDescriptionHandlerError(message); this.logger.error(message); throw error; }); } hasOffer(where) { const offerState = "have-" + where + "-offer"; return this.peerConnection.signalingState === offerState; } // ICE gathering state handling isIceGatheringComplete() { return this.peerConnection.iceGatheringState === "complete" || this.iceGatheringTimeout; } resetIceGatheringComplete() { this.iceGatheringTimeout = false; this.logger.log("resetIceGatheringComplete"); if (this.iceGatheringTimer) { clearTimeout(this.iceGatheringTimer); this.iceGatheringTimer = undefined; } if (this.iceGatheringDeferred) { this.iceGatheringDeferred.reject(); this.iceGatheringDeferred = undefined; } } setDirection(sdp) { const match = sdp.match(/a=(sendrecv|sendonly|recvonly|inactive)/); if (match === null) { this.direction = this.C.DIRECTION.NULL; this.emit("directionChanged"); return; } const direction = match[1]; switch (direction) { case this.C.DIRECTION.SENDRECV: case this.C.DIRECTION.SENDONLY: case this.C.DIRECTION.RECVONLY: case this.C.DIRECTION.INACTIVE: this.direction = direction; break; default: this.direction = this.C.DIRECTION.NULL; break; } // this.direction = this.C.DIRECTION.SENDONLY; this.emit("directionChanged"); } triggerIceGatheringComplete() { if (this.isIceGatheringComplete()) { this.emit("iceGatheringComplete", this); if (this.iceGatheringTimer) { clearTimeout(this.iceGatheringTimer); this.iceGatheringTimer = undefined; } if (this.iceGatheringDeferred) { this.iceGatheringDeferred.resolve(); this.iceGatheringDeferred = undefined; } } } waitForIceGatheringComplete() { this.logger.log("waitForIceGatheringComplete"); if (this.isIceGatheringComplete()) { this.logger.log("ICE is already complete. Return resolved."); return Promise.resolve(); } else if (!this.iceGatheringDeferred) { this.iceGatheringDeferred = defer(); } this.logger.log("ICE is not complete. Returning promise"); return this.iceGatheringDeferred ? this.iceGatheringDeferred.promise : Promise.resolve(); } } /** * Creates an {@link Emitter}. * @param eventEmitter - An event emitter. * @param eventName - Event name. * @internal */ function makeEmitter(eventEmitter, eventName = "event") { return { on: (listener) => { eventEmitter.on(eventName, listener); }, off: (listener) => { eventEmitter.removeListener(eventName, listener); }, once: (listener) => { eventEmitter.once(eventName, listener); } }; } /** * An exchange of information (incoming INFO). * @public */ class Info { /** @internal */ constructor(incomingInfoRequest) { this.incomingInfoRequest = incomingInfoRequest; } /** Incoming MESSAGE request message. */ get request() { return this.incomingInfoRequest.message; } /** Accept the request. */ accept(options) { this.incomingInfoRequest.accept(options); return Promise.resolve(); } /** Reject the request. */ reject(options) { this.incomingInfoRequest.reject(options); return Promise.resolve(); } } /** * A notification of an event (incoming NOTIFY). * @public */ class Notification { /** @internal */ constructor(incomingNotifyRequest) { this.incomingNotifyRequest = incomingNotifyRequest; } /** Incoming NOTIFY request message. */ get request() { return this.incomingNotifyRequest.message; } /** Accept the request. */ accept(options) { this.incomingNotifyRequest.accept(options); return Promise.resolve(); } /** Reject the request. */ reject(options) { this.incomingNotifyRequest.reject(options); return Promise.resolve(); } } /** * A request to establish a {@link Session} elsewhere (incoming REFER). * @public */ class Referral { /** @internal */ constructor(incomingReferRequest, session) { this.incomingReferRequest = incomingReferRequest; this.session = session; } get referTo() { const referTo = this.incomingReferRequest.message.parseHeader("refer-to"); if (!(referTo instanceof NameAddrHeader)) { throw new Error("Failed to parse Refer-To header."); } return referTo; } get referredBy() { return this.incomingReferRequest.message.getHeader("referred-by"); } get replaces() { return this.referTo.uri.getHeader("replaces"); } /** Incoming REFER request message. */ get request() { return this.incomingReferRequest.message; } /** Accept the request. */ accept(options = { statusCode: 202 }) { this.incomingReferRequest.accept(options); return Promise.resolve(); } /** Reject the request. */ reject(options) { this.incomingReferRequest.reject(options); return Promise.resolve(); } /** * Creates an inviter which may be used to send an out of dialog INVITE request. * * @remarks * This a helper method to create an Inviter which will execute the referral * of the `Session` which was referred. The appropriate headers are set and * the referred `Session` is linked to the new `Session`. Note that only a * single instance of the `Inviter` will be created and returned (if called * more than once a reference to the same `Inviter` will be returned every time). * * @param options - Options bucket. * @param modifiers - Session description handler modifiers. */ makeInviter(options) { if (this.inviter) { return this.inviter; } const targetURI = this.referTo.uri.clone(); targetURI.clearHeaders(); options = options || {}; const extraHeaders = (options.extraHeaders || []).slice(); const replaces = this.replaces; if (replaces) { // decodeURIComponent is a holdover from 2c086eb4. Not sure that it is actually necessary extraHeaders.push("Replaces: " + decodeURIComponent(replaces)); } const referredBy = this.referredBy; if (referredBy) { extraHeaders.push("Referred-By: " + referredBy); } options.extraHeaders = extraHeaders; this.inviter = this.session.userAgent.makeInviter(targetURI, options); this.inviter.referred = this.session; this.session.referral = this.inviter; return this.inviter; } } /** * {@link Session} state. * @remarks * Valid state transitions: * ``` * 1. "initial" --> "establishing" (before INVITE sent on outgoing, before OK sent on incoming) * 2. "initial" --> "established" (after ACK is sent on outgoing, after OK sent on incoming) * 4. "initial" --> "terminating" * 4. "initial" --> "terminated" * 5. "establishing" --> "established" * 6. "establishing" --> "terminating" * 7. "establishing" --> "terminated" * 8. "established" --> "terminating" * 9. "established" --> "terminated" * 10. "terminating" --> "terminated" * ``` * @public */ var SessionState$1; (function(SessionState) { SessionState["Initial"] = "Initial"; SessionState["Establishing"] = "Establishing"; SessionState["Established"] = "Established"; SessionState["Terminating"] = "Terminating"; SessionState["Terminated"] = "Terminated"; })(SessionState$1 || (SessionState$1 = {})); /** * Deprecated * @internal */ var _SessionStatus; (function(_SessionStatus) { // Session states _SessionStatus[_SessionStatus["STATUS_NULL"] = 0] = "STATUS_NULL"; _SessionStatus[_SessionStatus["STATUS_INVITE_SENT"] = 1] = "STATUS_INVITE_SENT"; _SessionStatus[_SessionStatus["STATUS_1XX_RECEIVED"] = 2] = "STATUS_1XX_RECEIVED"; _SessionStatus[_SessionStatus["STATUS_INVITE_RECEIVED"] = 3] = "STATUS_INVITE_RECEIVED"; _SessionStatus[_SessionStatus["STATUS_WAITING_FOR_ANSWER"] = 4] = "STATUS_WAITING_FOR_ANSWER"; _SessionStatus[_SessionStatus["STATUS_ANSWERED"] = 5] = "STATUS_ANSWERED"; _SessionStatus[_SessionStatus["STATUS_WAITING_FOR_PRACK"] = 6] = "STATUS_WAITING_FOR_PRACK"; _SessionStatus[_SessionStatus["STATUS_WAITING_FOR_ACK"] = 7] = "STATUS_WAITING_FOR_ACK"; _SessionStatus[_SessionStatus["STATUS_CANCELED"] = 8] = "STATUS_CANCELED"; _SessionStatus[_SessionStatus["STATUS_TERMINATED"] = 9] = "STATUS_TERMINATED"; _SessionStatus[_SessionStatus["STATUS_ANSWERED_WAITING_FOR_PRACK"] = 10] = "STATUS_ANSWERED_WAITING_FOR_PRACK"; _SessionStatus[_SessionStatus["STATUS_EARLY_MEDIA"] = 11] = "STATUS_EARLY_MEDIA"; _SessionStatus[_SessionStatus["STATUS_CONFIRMED"] = 12] = "STATUS_CONFIRMED"; })(_SessionStatus || (_SessionStatus = {})); /** * A session provides real time communication between one or more participants. * @public */ class Session { /** * Constructor. * @param userAgent - User agent. See {@link UserAgent} for details. * @internal */ constructor(userAgent, options = {}) { /** @internal */ this.localHold = false; /** True if an error caused session termination. */ /** @internal */ this.isFailed = false; /** @internal */ this.rel100 = "none"; /** @internal */ this.status = _SessionStatus.STATUS_NULL; /** @internal */ this.expiresTimer = undefined; /** @internal */ this.userNoAnswerTimer = undefined; this._state = SessionState$1.Initial; this._stateEventEmitter = new EventEmitter(); this.pendingReinvite = false; this.userAgent = userAgent; this.delegate = options.delegate; this.logger = userAgent.getLogger("sip.session"); } /** * Session description handler. * @remarks * If `this` is an instance of `Invitation`, * `sessionDescriptionHandler` will be defined when the session state changes to "established". * If `this` is an instance of `Inviter` and an offer was sent in the INVITE, * `sessionDescriptionHandler` will be defined when the session state changes to "establishing". * If `this` is an instance of `Inviter` and an offer was not sent in the INVITE, * `sessionDescriptionHandler` will be defined when the session state changes to "established". * Otherwise `undefined`. */ get sessionDescriptionHandler() { return this._sessionDescriptionHandler; } /** * Session description handler factory. */ get sessionDescriptionHandlerFactory() { return this.userAgent.configuration.sessionDescriptionHandlerFactory; } /** * Session state. */ get state() { return this._state; } /** * Session state change emitter. */ get stateChange() { return makeEmitter(this._stateEventEmitter); } /** * Renegotiate the session. Sends a re-INVITE. * @param options - Options bucket. */ invite(options = {}) { this.logger.log("Session.invite"); if (this.state !== SessionState$1.Established) { return Promise.reject(new Error(`Invalid session state ${this.state}`)); } if (this.pendingReinvite) { return Promise.reject(new Error("Reinvite in progress. Please wait until complete, then try again.")); } if (!this._sessionDescriptionHandler) { throw new Error("Session description handler undefined."); } this.pendingReinvite = true; const delegate = { onAccept: (response) => { // A re-INVITE transaction has an offer/answer [RFC3264] exchange // associated with it. The UAC (User Agent Client) generating a given // re-INVITE can act as the offerer or as the answerer. A UAC willing // to act as the offerer includes an offer in the re-INVITE. The UAS // (User Agent Server) then provides an answer in a response to the // re-INVITE. A UAC willing to act as answerer does not include an // offer in the re-INVITE. The UAS then provides an offer in a response // to the re-INVITE becoming, thus, the offerer. // https://tools.ietf.org/html/rfc6141#section-1 const body = getBody(response.message); if (!body) { // No way to recover, so terminate session and mark as failed. this.logger.error("Received 2xx response to re-INVITE without a session description"); this.ackAndBye(response, 400, "Missing session description"); this.stateTransition(SessionState$1.Terminated); this.isFailed = true; this.pendingReinvite = false; return; } if (options.withoutSdp) { // INVITE without SDP - set remote offer and send an answer in the ACK // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously // This behavior was ported from legacy code and the issue punted down the road. const answerOptions = { sessionDescriptionHandlerOptions: options.sessionDescriptionHandlerOptions, sessionDescriptionHandlerModifiers: options.sessionDescriptionHandlerModifiers }; this.setOfferAndGetAnswer(body, answerOptions) .then((answerBody) => { response.ack({ body: answerBody }); }) .catch((error) => { // No way to recover, so terminate session and mark as failed. this.logger.error("Failed to handle offer in 2xx response to re-INVITE"); this.logger.error(error.message); if (this.state === SessionState$1.Terminated) { // A BYE should not be sent if alreadly terminated. // For example, a BYE may be sent/received while re-INVITE is outstanding. response.ack(); } else { this.ackAndBye(response, 488, "Bad Media Description"); this.stateTransition(SessionState$1.Terminated); this.isFailed = true; } }) .then(() => { this.pendingReinvite = false; if (options.requestDelegate && options.requestDelegate.onAccept) { options.requestDelegate.onAccept(response); } }); } else { // INVITE with SDP - set remote answer and send an ACK // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously // This behavior was ported from legacy code and the issue punted down the road. const answerOptions = { sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers }; this.setAnswer(body, answerOptions) .then(() => { response.ack(); }) .catch((error) => { // No way to recover, so terminate session and mark as failed. this.logger.error("Failed to handle answer in 2xx response to re-INVITE"); this.logger.error(error.message); // A BYE should only be sent if session is not alreadly terminated. // For example, a BYE may be sent/received while re-INVITE is outstanding. // The ACK needs to be sent regardless as it was not handled by the transaction. if (this.state !== SessionState$1.Terminated) { this.ackAndBye(response, 488, "Bad Media Description"); this.stateTransition(SessionState$1.Terminated); this.isFailed = true; } else { response.ack(); } }) .then(() => { this.pendingReinvite = false; if (options.requestDelegate && options.requestDelegate.onAccept) { options.requestDelegate.onAccept(response); } }); } }, onProgress: (response) => { return; }, onRedirect: (response) => { return; }, onReject: (response) => { this.logger.warn("Received a non-2xx response to re-INVITE"); this.pendingReinvite = false; if (options.withoutSdp) { if (options.requestDelegate && options.requestDelegate.onReject) { options.requestDelegate.onReject(response); } } else { this.rollbackOffer() .catch((error) => { // No way to recover, so terminate session and mark as failed. this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"); this.logger.error(error.message); // A BYE should only be sent if session is not alreadly terminated. // For example, a BYE may be sent/received while re-INVITE is outstanding. // Note that the ACK was already sent by the transaction, so just need to send BYE. if (this.state !== SessionState$1.Terminated) { if (!this.dialog) { throw new Error("Dialog undefined."); } const extraHeaders = []; extraHeaders.push("Reason: " + this.getReasonHeaderValue(500, "Internal Server Error")); this.dialog.bye(undefined, { extraHeaders }); this.stateTransition(SessionState$1.Terminated); this.isFailed = true; } }) .then(() => { if (options.requestDelegate && options.requestDelegate.onReject) { options.requestDelegate.onReject(response); } }); } }, onTrying: (response) => { return; } }; const requestOptions = options.requestOptions || {}; requestOptions.extraHeaders = (requestOptions.extraHeaders || []).slice(); requestOptions.extraHeaders.push("Allow: " + AllowedMethods.toString()); requestOptions.extraHeaders.push("Contact: " + this.contact); // Just send an INVITE with no sdp... if (options.withoutSdp) { if (!this.dialog) { this.pendingReinvite = false; return Promise.reject(new Error("Dialog undefined.")); } return Promise.resolve(this.dialog.invite(delegate, requestOptions)); } // Get an offer and send it in an INVITE // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously // This behavior was ported from legacy code and the issue punted down the road. const offerOptions = { sessionDescriptionHandlerOptions: options.sessionDescriptionHandlerOptions, sessionDescriptionHandlerModifiers: options.sessionDescriptionHandlerModifiers }; return this.getOffer(offerOptions) .then((offerBody) => { if (!this.dialog) { this.pendingReinvite = false; throw new Error("Dialog undefined."); } requestOptions.body = offerBody; return this.dialog.invite(delegate, requestOptions); }) .catch((error) => { this.logger.error(error.message); this.logger.error("Failed to send re-INVITE"); this.pendingReinvite = false; throw error; }); } /** * Send BYE. * @param delegate - Request delegate. * @param options - Request options bucket. * @internal */ _bye(delegate, options) { // Using core session dialog if (!this.dialog) { return Promise.reject(new Error("Session dialog undefined.")); } const dialog = this.dialog; // The caller's UA MAY send a BYE for either confirmed or early dialogs, // and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT // send a BYE on early dialogs. However, the callee's UA MUST NOT send a // BYE on a confirmed dialog until it has received an ACK for its 2xx // response or until the server transaction times out. // https://tools.ietf.org/html/rfc3261#section-15 switch (dialog.sessionState) { case SessionState.Initial: throw new Error(`Invalid dialog state ${dialog.sessionState}`); case SessionState.Early: // Implementation choice - not sending BYE for early dialogs. throw new Error(`Invalid dialog state ${dialog.sessionState}`); case SessionState.AckWait: { // This state only occurs if we are the callee. this.stateTransition(SessionState$1.Terminating); // We're terminating return new Promise((resolve, reject) => { dialog.delegate = { // When ACK shows up, say BYE. onAck: () => { const request = dialog.bye(delegate, options); this.stateTransition(SessionState$1.Terminated); resolve(request); }, // Or the server transaction times out before the ACK arrives. onAckTimeout: () => { const request = dialog.bye(delegate, options); this.stateTransition(SessionState$1.Terminated); resolve(request); } }; }); } case SessionState.Confirmed: { const request = dialog.bye(delegate, options); this.stateTransition(SessionState$1.Terminated); return Promise.resolve(request); } case SessionState.Terminated: throw new Error(`Invalid dialog state ${dialog.sessionState}`); default: throw new Error("Unrecognized state."); } } /** * Called to cleanup session after terminated. * @internal */ _close() { this.logger.log(`Session[${this.id}]._close`); if (this.status === _SessionStatus.STATUS_TERMINATED) { return; } // 1st Step. Terminate media. if (this._sessionDescriptionHandler) { this._sessionDescriptionHandler.close(); } // 2nd Step. Terminate signaling. // Clear session timers if (this.expiresTimer) { clearTimeout(this.expiresTimer); } if (this.userNoAnswerTimer) { clearTimeout(this.userNoAnswerTimer); } this.status = _SessionStatus.STATUS_TERMINATED; if (!this.id) { throw new Error("Session id undefined."); } delete this.userAgent.sessions[this.id]; return; } /** * Send INFO. * @param delegate - Request delegate. * @param options - Request options bucket. * @internal */ _info(delegate, options) { // Using core session dialog if (!this.dialog) { return Promise.reject(new Error("Session dialog undefined.")); } return Promise.resolve(this.dialog.info(delegate, options)); } /** * Send REFER. * @param referrer - Referrer. * @param delegate - Request delegate. * @param options - Request options bucket. * @internal */ refer(referrer, delegate, options) { // Using core session dialog if (!this.dialog) { return Promise.reject(new Error("Session dialog undefined.")); } // If the session has a referrer, it will receive any in-dialog NOTIFY requests. this.referrer = referrer; return Promise.resolve(this.dialog.refer(delegate, options)); } /** * Send ACK and then BYE. There are unrecoverable errors which can occur * while handling dialog forming and in-dialog INVITE responses and when * they occur we ACK the response and send a BYE. * Note that the BYE is sent in the dialog associated with the response * which is not necessarily `this.dialog`. And, accordingly, the * session state is not transitioned to terminated and session is not closed. * @param inviteResponse - The response causing the error. * @param statusCode - Status code for he reason phrase. * @param reasonPhrase - Reason phrase for the BYE. * @internal */ ackAndBye(response, statusCode, reasonPhrase) { response.ack(); const extraHeaders = []; if (statusCode) { extraHeaders.push("Reason: " + this.getReasonHeaderValue(statusCode, reasonPhrase)); } // Using the dialog session associate with the response (which might not be this.dialog) response.session.bye(undefined, { extraHeaders }); } /** * Handle in dialog ACK request. * @internal */ onAckRequest(request) { this.logger.log("Session.onAckRequest"); if (this.state !== SessionState$1.Established && this.state !== SessionState$1.Terminating) { this.logger.error(`ACK received while in state ${this.state}, dropping request`); return; } const dialog = this.dialog; if (!dialog) { throw new Error("Dialog undefined."); } switch (dialog.signalingState) { case SignalingState.Initial: { // State should never be reached as first reliable response must have answer/offer. // So we must have never has sent an offer. this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); this.isFailed = true; const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; dialog.bye(undefined, { extraHeaders }); this.stateTransition(SessionState$1.Terminated); return; } case SignalingState.Stable: { // State we should be in. // Either the ACK has the answer that got us here, or we were in this state prior to the ACK. const body = getBody(request.message); // If the ACK doesn't have an answer, nothing to be done. if (!body) { this.status = _SessionStatus.STATUS_CONFIRMED; return; } if (body.contentDisposition === "render") { this.renderbody = body.content; this.rendertype = body.contentType; this.status = _SessionStatus.STATUS_CONFIRMED; return; } if (body.contentDisposition !== "session") { this.status = _SessionStatus.STATUS_CONFIRMED; return; } // Receved answer in ACK. const options = { sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers }; this.setAnswer(body, options) .then(() => { this.status = _SessionStatus.STATUS_CONFIRMED; }) .catch((error) => { this.logger.error(error.message); this.isFailed = true; const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; dialog.bye(undefined, { extraHeaders }); this.stateTransition(SessionState$1.Terminated); }); return; } case SignalingState.HaveLocalOffer: { // State should never be reached as local offer would be answered by this ACK. // So we must have received an ACK without an answer. this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); this.isFailed = true; const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; dialog.bye(undefined, { extraHeaders }); this.stateTransition(SessionState$1.Terminated); return; } case SignalingState.HaveRemoteOffer: { // State should never be reached as remote offer would be answered in first reliable response. // So we must have never has sent an answer. this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); this.isFailed = true; const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; dialog.bye(undefined, { extraHeaders }); this.stateTransition(SessionState$1.Terminated); return; } case SignalingState.Closed: throw new Error(`Invalid signaling state ${dialog.signalingState}.`); default: throw new Error(`Invalid signaling state ${dialog.signalingState}.`); } } /** * Handle in dialog BYE request. * @internal */ onByeRequest(request) { this.logger.log("Session.onByeRequest"); if (this.state !== SessionState$1.Established) { this.logger.error(`BYE received while in state ${this.state}, dropping request`); return; } request.accept(); this.stateTransition(SessionState$1.Terminated); } /** * Handle in dialog INFO request. * @internal */ onInfoRequest(request) { this.logger.log("Session.onInfoRequest"); if (this.state !== SessionState$1.Established) { this.logger.error(`INFO received while in state ${this.state}, dropping request`); return; } if (this.delegate && this.delegate.onInfo) { const info = new Info(request); this.delegate.onInfo(info); } else { request.accept(); } } /** * Handle in dialog INVITE request. * @internal */ onInviteRequest(request) { this.logger.log("Session.onInviteRequest"); if (this.state !== SessionState$1.Established) { this.logger.error(`INVITE received while in state ${this.state}, dropping request`); return; } // TODO: would be nice to have core track and set the Contact header, // but currently the session which is setting it is holding onto it. const extraHeaders = ["Contact: " + this.contact]; // Handle P-Asserted-Identity if (request.message.hasHeader("P-Asserted-Identity")) { const header = request.message.getHeader("P-Asserted-Identity"); if (!header) { throw new Error("Header undefined."); } this.assertedIdentity = Grammar.nameAddrHeaderParse(header); } // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously // This behavior was ported from legacy code and the issue punted down the road. const options = { sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers }; this.generateResponseOfferAnswerInDialog(options) .then((body) => { const outgoingResponse = request.accept({ statusCode: 200, extraHeaders, body }); if (this.delegate && this.delegate.onInvite) { this.delegate.onInvite(request.message, outgoingResponse.message, 200); } }) .catch((error) => { this.logger.error(error.message); this.logger.error("Failed to handle to re-INVITE request"); if (!this.dialog) { throw new Error("Dialog undefined."); } this.logger.error(this.dialog.signalingState); // If we don't have a local/remote offer... if (this.dialog.signalingState === SignalingState.Stable) { const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here if (this.delegate && this.delegate.onInvite) { this.delegate.onInvite(request.message, outgoingResponse.message, 488); } return; } // Otherwise rollback this.rollbackOffer() .then(() => { const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here if (this.delegate && this.delegate.onInvite) { this.delegate.onInvite(request.message, outgoingResponse.message, 488); } }) .catch((errorRollback) => { // No way to recover, so terminate session and mark as failed. this.logger.error(errorRollback.message); this.logger.error("Failed to rollback offer on re-INVITE request"); const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here // A BYE should only be sent if session is not alreadly terminated. // For example, a BYE may be sent/received while re-INVITE is outstanding. // Note that the ACK was already sent by the transaction, so just need to send BYE. if (this.state !== SessionState$1.Terminated) { if (!this.dialog) { throw new Error("Dialog undefined."); } const extraHeadersBye = []; extraHeadersBye.push("Reason: " + this.getReasonHeaderValue(500, "Internal Server Error")); this.dialog.bye(undefined, { extraHeaders }); this.stateTransition(SessionState$1.Terminated); this.isFailed = true; } if (this.delegate && this.delegate.onInvite) { this.delegate.onInvite(request.message, outgoingResponse.message, 488); } }); }); } /** * Handle in dialog NOTIFY request. * @internal */ onNotifyRequest(request) { this.logger.log("Session.onNotifyRequest"); if (this.state !== SessionState$1.Established) { this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`); return; } // If this a NOTIFY associated with the progress of a REFER, // look to delegate handling to the associated Referrer. if (this.referrer && this.referrer.delegate && this.referrer.delegate.onNotify) { const notification = new Notification(request); this.referrer.delegate.onNotify(notification); return; } // Otherwise accept the NOTIFY. if (this.delegate && this.delegate.onNotify) { const notification = new Notification(request); this.delegate.onNotify(notification); } else { request.accept(); } } /** * Handle in dialog PRACK request. * @internal */ onPrackRequest(request) { this.logger.log("Session.onPrackRequest"); if (this.state !== SessionState$1.Established) { this.logger.error(`PRACK received while in state ${this.state}, dropping request`); return; } throw new Error("Unimplemented."); } /** * Handle in dialog REFER request. * @internal */ onReferRequest(request) { this.logger.log("Session.onReferRequest"); if (this.state !== SessionState$1.Established) { this.logger.error(`REFER received while in state ${this.state}, dropping request`); return; } if (this.status === _SessionStatus.STATUS_CONFIRMED) { // RFC 3515 2.4.1 if (!request.message.hasHeader("refer-to")) { this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."); request.reject(); return; } const referral = new Referral(request, this); if (this.delegate && this.delegate.onRefer) { this.delegate.onRefer(referral); } else { this.logger.log("No delegate available to handle REFER, automatically accepting and following."); referral .accept() .then(() => referral .makeInviter(this.passedOptions) .invite()) .catch((error) => { // FIXME: logging and eating error... this.logger.error(error.message); }); } } } /** * Generate an offer or answer for a response to an INVITE request. * If a remote offer was provided in the request, set the remote * description and get a local answer. If a remote offer was not * provided, generates a local offer. * @internal */ generateResponseOfferAnswer(request, options) { if (this.dialog) { return this.generateResponseOfferAnswerInDialog(options); } const body = getBody(request.message); if (!body || body.contentDisposition !== "session") { return this.getOffer(options); } else { return this.setOfferAndGetAnswer(body, options); } } /** * Generate an offer or answer for a response to an INVITE request * when a dialog (early or otherwise) has already been established. * This method may NOT be called if a dialog has yet to be established. * @internal */ generateResponseOfferAnswerInDialog(options) { if (!this.dialog) { throw new Error("Dialog undefined."); } switch (this.dialog.signalingState) { case SignalingState.Initial: return this.getOffer(options); case SignalingState.HaveLocalOffer: // o Once the UAS has sent or received an answer to the initial // offer, it MUST NOT generate subsequent offers in any responses // to the initial INVITE. This means that a UAS based on this // specification alone can never generate subsequent offers until // completion of the initial transaction. // https://tools.ietf.org/html/rfc3261#section-13.2.1 return Promise.resolve(undefined); case SignalingState.HaveRemoteOffer: if (!this.dialog.offer) { throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`); } return this.setOfferAndGetAnswer(this.dialog.offer, options); case SignalingState.Stable: // o Once the UAS has sent or received an answer to the initial // offer, it MUST NOT generate subsequent offers in any responses // to the initial INVITE. This means that a UAS based on this // specification alone can never generate subsequent offers until // completion of the initial transaction. // https://tools.ietf.org/html/rfc3261#section-13.2.1 if (this.state !== SessionState$1.Established) { return Promise.resolve(undefined); } // In dialog INVITE without offer, get an offer for the response. return this.getOffer(options); case SignalingState.Closed: throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); default: throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); } } /** * Get local offer. * @internal */ getOffer(options) { const sdh = this.setupSessionDescriptionHandler(); const sdhOptions = options.sessionDescriptionHandlerOptions; const sdhModifiers = options.sessionDescriptionHandlerModifiers; // This is intentionally written very defensively. Don't trust SDH to behave. try { return sdh.getDescription(sdhOptions, sdhModifiers) .then((bodyAndContentType) => fromBodyLegacy(bodyAndContentType)) .catch((error) => { this.logger.error("Session.getOffer: SDH getDescription rejected..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); throw e; }); } catch (error) { // don't trust SDH to throw an Error this.logger.error("Session.getOffer: SDH getDescription threw..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); return Promise.reject(e); } } /** * Rollback local/remote offer. * @internal */ rollbackOffer() { const sdh = this.setupSessionDescriptionHandler(); if (!sdh.rollbackDescription) { return Promise.resolve(); } // This is intentionally written very defensively. Don't trust SDH to behave. try { return sdh.rollbackDescription() .catch((error) => { this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); throw e; }); } catch (error) { // don't trust SDH to throw an Error this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); return Promise.reject(e); } } /** * Set remote answer. * @internal */ setAnswer(answer, options) { const sdh = this.setupSessionDescriptionHandler(); const sdhOptions = options.sessionDescriptionHandlerOptions; const sdhModifiers = options.sessionDescriptionHandlerModifiers; // This is intentionally written very defensively. Don't trust SDH to behave. try { if (!sdh.hasDescription(answer.contentType)) { return Promise.reject(new ContentTypeUnsupportedError()); } } catch (error) { this.logger.error("Session.setAnswer: SDH hasDescription threw..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); return Promise.reject(e); } try { return sdh.setDescription(answer.content, sdhOptions, sdhModifiers) .catch((error) => { this.logger.error("Session.setAnswer: SDH setDescription rejected..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); throw e; }); } catch (error) { // don't trust SDH to throw an Error this.logger.error("Session.setAnswer: SDH setDescription threw..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); return Promise.reject(e); } } /** * Set remote offer and get local answer. * @internal */ setOfferAndGetAnswer(offer, options) { const sdh = this.setupSessionDescriptionHandler(); const sdhOptions = options.sessionDescriptionHandlerOptions; const sdhModifiers = options.sessionDescriptionHandlerModifiers; // This is intentionally written very defensively. Don't trust SDH to behave. try { if (!sdh.hasDescription(offer.contentType)) { return Promise.reject(new ContentTypeUnsupportedError()); } } catch (error) { this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); return Promise.reject(e); } try { return sdh.setDescription(offer.content, sdhOptions, sdhModifiers) .then(() => sdh.getDescription(sdhOptions, sdhModifiers)) .then((bodyAndContentType) => fromBodyLegacy(bodyAndContentType)) .catch((error) => { this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); throw e; }); } catch (error) { // don't trust SDH to throw an Error this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); return Promise.reject(e); } } /** * SDH for confirmed dialog. * @internal */ setSessionDescriptionHandler(sdh) { if (this._sessionDescriptionHandler) { throw new Error("Sessionn description handler defined."); } this._sessionDescriptionHandler = sdh; } /** * SDH for confirmed dialog. * @internal */ setupSessionDescriptionHandler() { if (this._sessionDescriptionHandler) { return this._sessionDescriptionHandler; } this._sessionDescriptionHandler = this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions); return this._sessionDescriptionHandler; } /** * Transition session state. * @internal */ stateTransition(newState) { const invalidTransition = () => { throw new Error(`Invalid state transition from ${this._state} to ${newState}`); }; // Validate transition switch (this._state) { case SessionState$1.Initial: if (newState !== SessionState$1.Establishing && newState !== SessionState$1.Established && newState !== SessionState$1.Terminating && newState !== SessionState$1.Terminated) { invalidTransition(); } break; case SessionState$1.Establishing: if (newState !== SessionState$1.Established && newState !== SessionState$1.Terminating && newState !== SessionState$1.Terminated) { invalidTransition(); } break; case SessionState$1.Established: if (newState !== SessionState$1.Terminating && newState !== SessionState$1.Terminated) { invalidTransition(); } break; case SessionState$1.Terminating: if (newState !== SessionState$1.Terminated) { invalidTransition(); } break; case SessionState$1.Terminated: invalidTransition(); break; default: throw new Error("Unrecognized state."); } if (newState === SessionState$1.Established) { this.startTime = new Date(); // Deprecated legacy ported behavior } if (newState === SessionState$1.Terminated) { this.endTime = new Date(); // Deprecated legacy ported behavior this._close(); } // Transition this._state = newState; this.logger.log(`Session ${this.id} transitioned to state ${this._state}`); this._stateEventEmitter.emit("event", this._state); } getReasonHeaderValue(code, reason) { const cause = code; let text = getReasonPhrase(code); if (!text && reason) { text = reason; } return "SIP;cause=" + cause + ';text="' + text + '"'; } } /** * SIP extension support level. * @public */ var SIPExtension; (function(SIPExtension) { SIPExtension["Required"] = "Required"; SIPExtension["Supported"] = "Supported"; SIPExtension["Unsupported"] = "Unsupported"; })(SIPExtension || (SIPExtension = {})); /** * SIP Option Tags * @remarks * http://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml#sip-parameters-4 * @public */ const UserAgentRegisteredOptionTags = { "100rel": true, "199": true, "answermode": true, "early-session": true, "eventlist": true, "explicitsub": true, "from-change": true, "geolocation-http": true, "geolocation-sip": true, "gin": true, "gruu": true, "histinfo": true, "ice": true, "join": true, "multiple-refer": true, "norefersub": true, "nosub": true, "outbound": true, "path": true, "policy": true, "precondition": true, "pref": true, "privacy": true, "recipient-list-invite": true, "recipient-list-message": true, "recipient-list-subscribe": true, "replaces": true, "resource-priority": true, "sdp-anat": true, "sec-agree": true, "tdialog": true, "timer": true, "uui": true // RFC 7433 }; class Call extends Session { get isVideo() { switch (this.state) { case SessionState$1.Initial: // if (this.localVideoTrack != null || this.remoteVideoTrack != null) { // return true; // } break; case SessionState$1.Established: if (this.localVideoTrack != null && this.remoteVideoTrack != null) { return true; } else { return false; } default: break; } if (this instanceof Invitation) { let invitation = this; let isVideo = invitation.request.body.indexOf("m=video"); if (isVideo > 0) { return true; } else { return false; } } else if (this instanceof Inviter) { let inviter = this; let isVideo = inviter.body.body.indexOf("m=video"); if (isVideo > 0) { return true; } else { return false; } } } // public id: number | undefined; // private logger: Logger; setDelegate(delegate) { this.delegatePhone = delegate; // Setup session state change handler this.stateChange.on((state) => { this.logger.log(`[${this.id}] session state changed to ${state}`); switch (state) { case SessionState$1.Initial: break; case SessionState$1.Establishing: break; case SessionState$1.Established: this.setupLocalMedia(); this.setupRemoteMedia(); if (this.delegate && this.delegatePhone.onCallAnswered) { this.delegatePhone.onCallAnswered(this.id); } break; case SessionState$1.Terminating: break; case SessionState$1.Terminated: // this.session = undefined; this.logger.warn("call terminated: " + this.id); this.cleanupMedia(); if (this.delegatePhone && this.delegatePhone.onCallHangup) { this.delegatePhone.onCallHangup(this.id, this.remoteIdentity.uri.user); } break; default: throw new Error("Unknown session state."); } }); } setupCall(localVideoControalPara, remoteVideoControalPara, logger, remoteAudioControl) { // this.session = sessionPara; this.localVideoControal = localVideoControalPara; this.remoteVideoControal = remoteVideoControalPara; this.remoteAudioControl = remoteAudioControl; this.logger = logger; } /** Helper function to attach local media to html elements. */ setupLocalMedia() { if (this.localAudioTrack) { const localAudioTrack = this.localAudioTrack; this.LocalAudioStream = new MediaStream([localAudioTrack]); } if (this.localVideoControal && this.remoteVideoControal) { const localVideoTrack = this.localVideoTrack; if (localVideoTrack) { const localStream = new MediaStream([localVideoTrack]); this.localVideoControal.srcObject = localStream; this.localVideoControal.volume = 0; this.localVideoControal.play(); } } } /** Helper function to attach remote media to html elements. */ setupRemoteMedia() { if (this.remoteVideoControal) { const remoteAudioTrack = this.remoteAudioTrack; const remoteVideoTrack = this.remoteVideoTrack; const remoteStream = new MediaStream(); // If there is a video element, both audio and video will be attached that element. if (this.remoteVideoControal) { if (remoteAudioTrack) { remoteStream.addTrack(remoteAudioTrack); } if (remoteVideoTrack) { // if (this.localVideoTrack ) { // 视频来电语音接听的时候,此时remoteVideoTrack不为空,但是如果把空的remoteVideoTrack //加入videoElement之后语音也播放处理了 if (this._mediaConstraints.video != false) { remoteStream.addTrack(remoteVideoTrack); } } this.remoteVideoControal.srcObject = remoteStream; this.remoteVideoControal.play() .catch((error) => { this.logger.error(`[${this.id}] error playing video`); this.logger.error(error.message); }); } if (this.remoteAudioControl) { if (remoteAudioTrack) { remoteStream.addTrack(remoteAudioTrack); this.remoteAudioControl.srcObject = remoteStream; this.remoteAudioControl.play() .catch((error) => { this.logger.error(`[${this.id}] error playing audio`); this.logger.error(error.message); }); } } } let sd = this.sessionDescriptionHandler; sd.on("addTrack", (track) => { console.log("addTrackincall", track); }); } /** Helper function to remove media from html elements. */ cleanupMedia() { if (this.localVideoControal) { this.localVideoControal.srcObject = null; this.localVideoControal.pause(); } if (this.remoteVideoControal) { this.remoteVideoControal.srcObject = null; this.remoteVideoControal.pause(); } } /** The receiver media track, if available. */ getReceiverTrack(kind) { const sessionDescriptionHandler = this.sessionDescriptionHandler; if (!sessionDescriptionHandler) { this.logger.warn(`[${this.id}] getReceiverTrack - session description handler undefined`); return undefined; } if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) { throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); } const peerConnection = sessionDescriptionHandler.peerConnection; const rtpReceiver = peerConnection.getReceivers().find((receiver) => { return receiver.track.kind === kind ? true : false; }); return rtpReceiver ? rtpReceiver.track : undefined; } /** The sender media track, if available. */ getSenderTrack(kind) { const sessionDescriptionHandler = this.sessionDescriptionHandler; if (!sessionDescriptionHandler) { this.logger.warn(`[${this.id}] getSenderTrack - session description handler undefined`); return undefined; } if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) { throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); } const peerConnection = sessionDescriptionHandler.peerConnection; const rtpSender = peerConnection.getSenders().find((sender) => { return sender.track && sender.track.kind === kind ? true : false; }); return rtpSender && rtpSender.track ? rtpSender.track : undefined; } /** The remote audio track, if available. */ get remoteAudioTrack() { return this.getReceiverTrack("audio"); } /** The remote video track, if available. */ get remoteVideoTrack() { return this.getReceiverTrack("video"); } /** The local audio track, if available. */ get localAudioTrack() { return this.getSenderTrack("audio"); } /** The local video track, if available. */ get localVideoTrack() { return this.getSenderTrack("video"); } changeVideoElement(videoContro) { videoContro.srcObject = this.remoteVideoControal.srcObject; this.remoteVideoControal.srcObject = null; this.remoteVideoControal = videoContro; this.remoteVideoControal.play(); } get peerConnection() { let sdh = this.sessionDescriptionHandler; return sdh.peerConnection; } } /** * An invitation is an offer to establish a {@link Session} (incoming INVITE). * @public */ class Invitation extends Call { /** @internal */ constructor(userAgent, incomingInviteRequest) { super(userAgent); this.incomingInviteRequest = incomingInviteRequest; /** @internal */ this.body = undefined; /** * FIXME: TODO: * Used to squelch throwing of errors due to async race condition. * We have an internal race between calling `accept()` and handling * an incoming CANCEL request. As there is no good way currently to * delegate the handling of this async errors to the caller of * `accept()`, we are squelching the throwing ALL errors when * they occur after receiving a CANCEL to catch the ONE we know * is a "normal" exceptional condition. While this is a completely * reasonable appraoch, the decision should be left up to the library user. */ this._canceled = false; this.rseq = Math.floor(Math.random() * 10000); // ServerContext properties this.logger = userAgent.getLogger("sip.invitation", this.id); if (this.request.body) { this.body = this.request.body; } if (this.request.hasHeader("Content-Type")) { this.contentType = this.request.getHeader("Content-Type"); } if (this.request.hasHeader("ifc")) { this._ifcContent = this.request.getHeader("ifc"); } this.localIdentity = this.request.to; this.remoteIdentity = this.request.from; const hasAssertedIdentity = this.request.hasHeader("P-Asserted-Identity"); if (hasAssertedIdentity) { const assertedIdentity = this.request.getHeader("P-Asserted-Identity"); if (assertedIdentity) { this.assertedIdentity = Grammar.nameAddrHeaderParse(assertedIdentity); } } // Session properties this.contact = this.userAgent.contact.toString(); this.fromTag = this.request.fromTag; this.id = this.request.callId + this.fromTag; // this.modifiers = // this.onInfo = // this.passedOptions = const contentDisposition = this.request.parseHeader("Content-Disposition"); if (contentDisposition && contentDisposition.type === "render") { this.renderbody = this.request.body; this.rendertype = this.request.getHeader("Content-Type"); } // FIXME: This is being done twice... // Update logger this.logger = userAgent.getLogger("sip.invitation", this.id); // Update status this.status = _SessionStatus.STATUS_INVITE_RECEIVED; // Save the session into the ua sessions collection. this.userAgent.sessions[this.id] = this; // Set 100rel if necessary const request = this.request; const requireHeader = request.getHeader("require"); if (requireHeader && requireHeader.toLowerCase().indexOf("100rel") >= 0) { this.rel100 = "required"; } const supportedHeader = request.getHeader("supported"); if (supportedHeader && supportedHeader.toLowerCase().indexOf("100rel") >= 0) { this.rel100 = "supported"; } // Set the toTag on the incoming request to the toTag which // will be used in the response to the incoming request!!! // FIXME: HACK: This is a hack to port an existing behavior. // The behavior being ported appears to be a hack itself, // so this is a hack to port a hack. At least one test spec // relies on it (which is yet another hack). this.request.toTag = incomingInviteRequest.toTag; // Update status again - sigh this.status = _SessionStatus.STATUS_WAITING_FOR_ANSWER; // The following mapping values are RECOMMENDED: // ... // 19 no answer from the user 480 Temporarily unavailable // https://tools.ietf.org/html/rfc3398#section-7.2.4.1 this.userNoAnswerTimer = setTimeout(() => { incomingInviteRequest.reject({ statusCode: 480 }); this.stateTransition(SessionState$1.Terminated); }, this.userAgent.configuration.noAnswerTimeout ? this.userAgent.configuration.noAnswerTimeout * 1000 : 60000); // 1. If the request is an INVITE that contains an Expires header // field, the UAS core sets a timer for the number of seconds // indicated in the header field value. When the timer fires, the // invitation is considered to be expired. If the invitation // expires before the UAS has generated a final response, a 487 // (Request Terminated) response SHOULD be generated. // https://tools.ietf.org/html/rfc3261#section-13.3.1 if (request.hasHeader("expires")) { const expires = Number(request.getHeader("expires") || 0) * 1000; this.expiresTimer = setTimeout(() => { if (this.status === _SessionStatus.STATUS_WAITING_FOR_ANSWER) { incomingInviteRequest.reject({ statusCode: 487 }); this.stateTransition(SessionState$1.Terminated); } }, expires); } } /** * If true, a first provisional response after the 100 Trying * will be sent automatically. This is false it the UAC required * reliable provisional responses (100rel in Require header), * otherwise it is true. The provisional is sent by calling * `progress()` without any options. * * FIXME: TODO: It seems reasonable that the ISC user should * be able to optionally disable this behavior. As the provisional * is sent prior to the "invite" event being emitted, it's a known * issue that the ISC user cannot register listeners or do any other * setup prior to the call to `progress()`. As an example why this is * an issue, setting `ua.configuration.rel100` to REQUIRED will result * in an attempt by `progress()` to send a 183 with SDP produced by * calling `getDescription()` on a session description handler, but * the ISC user cannot perform any potentially required session description * handler initialization (thus preventing the utilization of setting * `ua.configuration.rel100` to REQUIRED). That begs the question of * why this behavior is disabled when the UAC requires 100rel but not * when the UAS requires 100rel? But ignoring that, it's just one example * of a class of cases where the ISC user needs to do something prior * to the first call to `progress()` and is unable to do so. * @internal */ get autoSendAnInitialProvisionalResponse() { return this.rel100 === "required" ? false : true; } /** Incoming INVITE request message. */ get request() { return this.incomingInviteRequest.message; } /** * Accept the invitation. * @remarks * Accept the incoming INVITE request to start a Session. * Replies to the INVITE request with a 200 Ok response. * @param options - Options bucket. */ accept(options = {}) { this.logger.log("Invitation.accept"); // validate state if (this.state !== SessionState$1.Initial) { const error = new Error(`Invalid session state ${this.state}`); this.logger.error(error.message); return Promise.reject(error); } this._mediaConstraints = options.sessionDescriptionHandlerOptions.constraints; // transition state this.stateTransition(SessionState$1.Establishing); return this._accept(options) .then(({ message, session }) => { session.delegate = { onAck: (ackRequest) => this.onAckRequest(ackRequest), onAckTimeout: () => this.onAckTimeout(), onBye: (byeRequest) => this.onByeRequest(byeRequest), onInfo: (infoRequest) => this.onInfoRequest(infoRequest), onInvite: (inviteRequest) => this.onInviteRequest(inviteRequest), onNotify: (notifyRequest) => this.onNotifyRequest(notifyRequest), onPrack: (prackRequest) => this.onPrackRequest(prackRequest), onRefer: (referRequest) => this.onReferRequest(referRequest) }; this.dialog = session; this.stateTransition(SessionState$1.Established); // TODO: Reconsider this "automagic" send of a BYE to replacee behavior. // This behavoir has been ported forward from legacy versions. if (this.replacee) { this.replacee._bye(); } }) .catch((error) => { this.onContextError(error); // FIXME: Assuming error due to async race on CANCEL and eating error. if (!this._canceled) { throw error; } }); } /** * Indicate progress processing the invitation. * @remarks * Report progress to the the caller. * Replies to the INVITE request with a 1xx provisional response. * @param options - Options bucket. */ progress(options = {}) { this.logger.log("Invitation.progress"); // validate state if (this.state !== SessionState$1.Initial) { const error = new Error(`Invalid session state ${this.state}`); this.logger.error(error.message); return Promise.reject(error); } // Ported const statusCode = options.statusCode || 180; if (statusCode < 100 || statusCode > 199) { throw new TypeError("Invalid statusCode: " + statusCode); } // Ported if (this.status === _SessionStatus.STATUS_TERMINATED) { this.logger.warn("Unexpected call for progress while terminated, ignoring"); return Promise.resolve(); } // Added if (this.status === _SessionStatus.STATUS_ANSWERED) { this.logger.warn("Unexpected call for progress while answered, ignoring"); return Promise.resolve(); } // Added if (this.status === _SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { this.logger.warn("Unexpected call for progress while answered (waiting for prack), ignoring"); return Promise.resolve(); } // After the first reliable provisional response for a request has been // acknowledged, the UAS MAY send additional reliable provisional // responses. The UAS MUST NOT send a second reliable provisional // response until the first is acknowledged. After the first, it is // RECOMMENDED that the UAS not send an additional reliable provisional // response until the previous is acknowledged. The first reliable // provisional response receives special treatment because it conveys // the initial sequence number. If additional reliable provisional // responses were sent before the first was acknowledged, the UAS could // not be certain these were received in order. // https://tools.ietf.org/html/rfc3262#section-3 if (this.status === _SessionStatus.STATUS_WAITING_FOR_PRACK) { this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"); return Promise.resolve(); } // Ported if (options.statusCode === 100) { try { this.incomingInviteRequest.trying(); } catch (error) { this.onContextError(error); // FIXME: Assuming error due to async race on CANCEL and eating error. if (!this._canceled) { return Promise.reject(error); } } return Promise.resolve(); } // Standard provisional response. if (!(this.rel100 === "required") && !(this.rel100 === "supported" && options.rel100) && !(this.rel100 === "supported" && this.userAgent.configuration.sipExtension100rel === SIPExtension.Required)) { return this._progress(options) .then((response) => { return; }) .catch((error) => { this.onContextError(error); // FIXME: Assuming error due to async race on CANCEL and eating error. if (!this._canceled) { throw error; } }); } // Reliable provisional response. return this._progressReliableWaitForPrack(options) .then((response) => { return; }) .catch((error) => { this.onContextError(error); // FIXME: Assuming error due to async race on CANCEL and eating error. if (!this._canceled) { throw error; } }); } /** * Reject the invitation. * @param options - Options bucket. */ reject(options = {}) { this.logger.log("Invitation.reject"); // validate state if (this.state !== SessionState$1.Initial) { const error = new Error(`Invalid session state ${this.state}`); this.logger.error(error.message); return Promise.reject(error); } // Check Session Status if (this.status === _SessionStatus.STATUS_TERMINATED) { throw new Error(`Invalid status ${this.status}`); } this.logger.log("rejecting RTCSession"); const statusCode = options.statusCode || 480; const reasonPhrase = options.reasonPhrase ? options.reasonPhrase : getReasonPhrase(statusCode); const extraHeaders = options.extraHeaders || []; if (statusCode < 300 || statusCode > 699) { throw new TypeError("Invalid statusCode: " + statusCode); } const body = options.body ? fromBodyLegacy(options.body) : undefined; // FIXME: Need to redirect to someplae const response = statusCode < 400 ? this.incomingInviteRequest.redirect([], { statusCode, reasonPhrase, extraHeaders, body }) : this.incomingInviteRequest.reject({ statusCode, reasonPhrase, extraHeaders, body }); this.stateTransition(SessionState$1.Terminated); return Promise.resolve(); } /** * Called to cleanup session after terminated. * Using it here just for the PRACK timeout. * @internal */ _close() { this.prackNeverArrived(); super._close(); } /** * Handle CANCEL request. * @param message - CANCEL message. * @internal */ _onCancel(message) { this.logger.log("Invitation._onCancel"); // validate state if (this.state !== SessionState$1.Initial && this.state !== SessionState$1.Establishing) { this.logger.error(`CANCEL received while in state ${this.state}, dropping request`); return; } // flag canceled this._canceled = true; // reject INVITE with 487 status code this.incomingInviteRequest.reject({ statusCode: 487 }); this.stateTransition(SessionState$1.Terminated); } /** * A version of `accept` which resolves a session when the 200 Ok response is sent. * @param options - Options bucket. */ _accept(options = {}) { // FIXME: Ported - callback for in dialog INFO requests. // Turns out accept() can be called more than once if we are waiting // for a PRACK in which case "options" get completely tossed away. // So this is broken in that case (and potentially other uses of options). // Tempted to just try to fix it now, but leaving it broken for the moment. this.onInfo = options.onInfo; // The UAS MAY send a final response to the initial request before // having received PRACKs for all unacknowledged reliable provisional // responses, unless the final response is 2xx and any of the // unacknowledged reliable provisional responses contained a session // description. In that case, it MUST NOT send a final response until // those provisional responses are acknowledged. If the UAS does send a // final response when reliable responses are still unacknowledged, it // SHOULD NOT continue to retransmit the unacknowledged reliable // provisional responses, but it MUST be prepared to process PRACK // requests for those outstanding responses. A UAS MUST NOT send new // reliable provisional responses (as opposed to retransmissions of // unacknowledged ones) after sending a final response to a request. // https://tools.ietf.org/html/rfc3262#section-3 if (this.status === _SessionStatus.STATUS_WAITING_FOR_PRACK) { this.status = _SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK; return this.waitForArrivalOfPrack() .then(() => { this.status = _SessionStatus.STATUS_ANSWERED; clearTimeout(this.userNoAnswerTimer); // Ported }) .then(() => this.generateResponseOfferAnswer(this.incomingInviteRequest, options)) .then((body) => this.incomingInviteRequest.accept({ statusCode: 200, body })); } // Ported if (this.status === _SessionStatus.STATUS_WAITING_FOR_ANSWER) { this.status = _SessionStatus.STATUS_ANSWERED; } else { return Promise.reject(new Error(`Invalid status ${this.status}`)); } this.status = _SessionStatus.STATUS_ANSWERED; clearTimeout(this.userNoAnswerTimer); // Ported return this.generateResponseOfferAnswer(this.incomingInviteRequest, options) .then((body) => this.incomingInviteRequest.accept({ statusCode: 200, body })); } /** * A version of `progress` which resolves when the provisional response is sent. * @param options - Options bucket. */ _progress(options = {}) { // Ported const statusCode = options.statusCode || 180; const reasonPhrase = options.reasonPhrase; const extraHeaders = (options.extraHeaders || []).slice(); const body = options.body ? fromBodyLegacy(options.body) : undefined; // The 183 (Session Progress) response is used to convey information // about the progress of the call that is not otherwise classified. The // Reason-Phrase, header fields, or message body MAY be used to convey // more details about the call progress. // https://tools.ietf.org/html/rfc3261#section-21.1.5 // It is the de facto industry standard to utilize 183 with SDP to provide "early media". // While it is unlikely someone would want to send a 183 without SDP, so it should be an option. if (statusCode === 183 && !body) { return this._progressWithSDP(options); } try { const progressResponse = this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); this.dialog = progressResponse.session; return Promise.resolve(progressResponse); } catch (error) { return Promise.reject(error); } } /** * A version of `progress` which resolves when the provisional response with sdp is sent. * @param options - Options bucket. */ _progressWithSDP(options = {}) { const statusCode = options.statusCode || 183; const reasonPhrase = options.reasonPhrase; const extraHeaders = (options.extraHeaders || []).slice(); // Get an offer/answer and send a reply. return this.generateResponseOfferAnswer(this.incomingInviteRequest, options) .then((body) => this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body })) .then((progressResponse) => { this.dialog = progressResponse.session; return progressResponse; }); } /** * A version of `progress` which resolves when the reliable provisional response is sent. * @param options - Options bucket. */ _progressReliable(options = {}) { options.extraHeaders = (options.extraHeaders || []).slice(); options.extraHeaders.push("Require: 100rel"); options.extraHeaders.push("RSeq: " + Math.floor(Math.random() * 10000)); return this._progressWithSDP(options); } /** * A version of `progress` which resolves when the reliable provisional response is acknowledged. * @param options - Options bucket. */ _progressReliableWaitForPrack(options = {}) { const statusCode = options.statusCode || 183; const reasonPhrase = options.reasonPhrase; const extraHeaders = (options.extraHeaders || []).slice(); extraHeaders.push("Require: 100rel"); extraHeaders.push("RSeq: " + this.rseq++); let body; // Ported - set status. this.status = _SessionStatus.STATUS_WAITING_FOR_PRACK; return new Promise((resolve, reject) => { let waitingForPrack = true; return this.generateResponseOfferAnswer(this.incomingInviteRequest, options) .then((offerAnswer) => { body = offerAnswer; return this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); }) .then((progressResponse) => { this.dialog = progressResponse.session; let prackRequest; let prackResponse; progressResponse.session.delegate = { onPrack: (request) => { prackRequest = request; clearTimeout(prackWaitTimeoutTimer); clearTimeout(rel1xxRetransmissionTimer); if (!waitingForPrack) { return; } waitingForPrack = false; this.handlePrackOfferAnswer(prackRequest, options) .then((prackResponseBody) => { try { prackResponse = prackRequest.accept({ statusCode: 200, body: prackResponseBody }); // Ported - set status. if (this.status === _SessionStatus.STATUS_WAITING_FOR_PRACK) { this.status = _SessionStatus.STATUS_WAITING_FOR_ANSWER; } this.prackArrived(); resolve({ prackRequest, prackResponse, progressResponse }); } catch (error) { reject(error); } }); } }; // https://tools.ietf.org/html/rfc3262#section-3 const prackWaitTimeout = () => { if (!waitingForPrack) { return; } waitingForPrack = false; this.logger.warn("No PRACK received, rejecting INVITE."); clearTimeout(rel1xxRetransmissionTimer); try { this.incomingInviteRequest.reject({ statusCode: 504 }); this.stateTransition(SessionState$1.Terminated); reject(new SessionTerminatedError()); } catch (error) { reject(error); } }; const prackWaitTimeoutTimer = setTimeout(prackWaitTimeout, Timers.T1 * 64); // https://tools.ietf.org/html/rfc3262#section-3 const rel1xxRetransmission = () => { try { this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); } catch (error) { waitingForPrack = false; reject(error); return; } rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout *= 2); }; let timeout = Timers.T1; let rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout); }); }); } handlePrackOfferAnswer(request, options) { if (!this.dialog) { throw new Error("Dialog undefined."); } // If the PRACK doesn't have an offer/answer, nothing to be done. const body = getBody(request.message); if (!body || body.contentDisposition !== "session") { return Promise.resolve(undefined); } // If the UAC receives a reliable provisional response with an offer // (this would occur if the UAC sent an INVITE without an offer, in // which case the first reliable provisional response will contain the // offer), it MUST generate an answer in the PRACK. If the UAC receives // a reliable provisional response with an answer, it MAY generate an // additional offer in the PRACK. If the UAS receives a PRACK with an // offer, it MUST place the answer in the 2xx to the PRACK. // https://tools.ietf.org/html/rfc3262#section-5 switch (this.dialog.signalingState) { case SignalingState.Initial: // State should never be reached as first reliable provisional response must have answer/offer. throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); case SignalingState.Stable: // Receved answer. return this.setAnswer(body, options).then(() => undefined); case SignalingState.HaveLocalOffer: // State should never be reached as local offer would be answered by this PRACK throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); case SignalingState.HaveRemoteOffer: // Received offer, generate answer. return this.setOfferAndGetAnswer(body, options); case SignalingState.Closed: throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); default: throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); } } /** * Callback for when ACK for a 2xx response is never received. * @param session - Session the ACK never arrived for. */ onAckTimeout() { this.logger.log("Invitation.onAckTimeout"); if (!this.dialog) { throw new Error("Dialog undefined."); } this.logger.log("No ACK received for an extended period of time, terminating session"); this.dialog.bye(); this.stateTransition(SessionState$1.Terminated); } /** * FIXME: TODO: The current library interface presents async methods without a * proper async error handling mechanism. Arguably a promise based interface * would be an improvement over the pattern of returning `this`. The approach has * been generally along the lines of log a error and terminate. */ onContextError(error) { let statusCode = 480; if (error instanceof Exception) { // There might be interest in catching these Exceptions. if (error instanceof SessionDescriptionHandlerError) { this.logger.error(error.message); } else if (error instanceof SessionTerminatedError) { // PRACK never arrived, so we timed out waiting for it. this.logger.warn("Incoming session terminated while waiting for PRACK."); } else if (error instanceof ContentTypeUnsupportedError) { statusCode = 415; } else if (error instanceof Exception) { this.logger.error(error.message); } } else if (error instanceof Error) { // Other Errors hould go uncaught. this.logger.error(error.message); } else { // We don't actually know what a session description handler implementation might throw // our way, so as a last resort, just assume we are getting an "any" and log it. this.logger.error("An error occurred in the session description handler."); this.logger.error(error); } try { this.incomingInviteRequest.reject({ statusCode }); // "Temporarily Unavailable" this.stateTransition(SessionState$1.Terminated); } catch (error) { return; } } prackArrived() { if (this.waitingForPrackResolve) { this.waitingForPrackResolve(); } this.waitingForPrackPromise = undefined; this.waitingForPrackResolve = undefined; this.waitingForPrackReject = undefined; } prackNeverArrived() { if (this.waitingForPrackReject) { this.waitingForPrackReject(new SessionTerminatedError()); } this.waitingForPrackPromise = undefined; this.waitingForPrackResolve = undefined; this.waitingForPrackReject = undefined; } waitForArrivalOfPrack() { if (this.waitingForPrackPromise) { throw new Error("Already waiting for PRACK"); } this.waitingForPrackPromise = new Promise((resolve, reject) => { this.waitingForPrackResolve = resolve; this.waitingForPrackReject = reject; }); return this.waitingForPrackPromise; } } /** * A byer ends a {@link Session} (outgoing BYE). * @remarks * Sends an outgoing in dialog BYE request. * @public */ class Byer { /** * Constructs a new instance of the `Byer` class. * @param session - The session the BYE will be sent from. See {@link Session} for details. * @param options - An options bucket. See {@link ByerOptions} for details. */ constructor(session, options) { this._session = session; } /** The byer session. */ get session() { return this._session; } /** * Sends the BYE request. * @param options - {@link ByerByeOptions} options bucket. */ bye(options = {}) { // guard session state if (this.session.state !== SessionState$1.Established && this.session.state !== SessionState$1.Terminating) { let message = "Byer.bye() may only be called if established session."; if (this.session.state === SessionState$1.Terminated) { message += " However this session is already terminated."; } else { if (this.session instanceof Invitation) { message += " However Invitation.accept() has not yet been called."; message += " Perhaps you should have called Invitation.reject()?"; } else { message += " However a dialog does not yet exist."; message += " Perhaps you should have called Inviter.cancel()?"; } } this.session.logger.error(message); return Promise.reject(new Error(`Invalid session state ${this.session.state}`)); } return this.session._bye(options.requestDelegate, options.requestOptions); } } /** * An Infoer sends {@link Info} (outgoing INFO). * @remarks * Sends an outgoing in dialog INFO request. * @public */ class Infoer { /** * Constructs a new instance of the `Infoer` class. * @param session - The session the INFO will be sent from. See {@link Session} for details. * @param options - An options bucket. */ constructor(session, options) { this._session = session; } /** The Infoer session. */ get session() { return this._session; } /** * Sends the INFO request. * @param options - {@link InfoerInfoOptions} options bucket. */ info(options = {}) { // guard session state if (this.session.state !== SessionState$1.Established) { const message = "Infoer.info() may only be called if established session."; this.session.logger.error(message); return Promise.reject(new Error(`Invalid session state ${this.session.state}`)); } return this.session._info(options.requestDelegate, options.requestOptions); } } /** * An inviter offers to establish a {@link Session} (outgoing INVITE). * @public */ class Inviter extends Call { /** * Constructs a new instance of the `Inviter` class. * @param userAgent - User agent. See {@link UserAgent} for details. * @param targetURI - Request URI identifying the target of the message. * @param options - Options bucket. See {@link InviterOptions} for details. */ constructor(userAgent, targetURI, options = {}) { super(userAgent, options); /** @internal */ this.body = undefined; this.earlyMediaSessionDescriptionHandlers = new Map(); // Default options params options.params = options.params || {}; // Check Session Status if (this.status !== _SessionStatus.STATUS_NULL) { throw new Error(`Invalid status ${this.status}`); } // ClientContext properties this.logger = userAgent.getLogger("sip.inviter"); if (options.body) { this.body = { body: options.body, contentType: options.contentType ? options.contentType : "application/sdp" }; } // Anonymous call const anonymous = options.anonymous || false; if (anonymous && userAgent.configuration.uri) { options.params.fromDisplayName = "Anonymous"; options.params.fromUri = "sip:anonymous@anonymous.invalid"; } // From Tag const fromTag = newTag(); // Contact // Do not add ;ob in initial forming dialog requests if the registration over // the current connection got a GRUU URI. const contact = userAgent.contact.toString({ anonymous, outbound: anonymous ? !userAgent.contact.tempGruu : !userAgent.contact.pubGruu }); // Params const params = options.params || {}; params.fromTag = fromTag; // URIs let fromURI = userAgent.userAgentCore.configuration.aor; if (options.params.fromUri) { fromURI = (typeof options.params.fromUri === "string") ? Grammar.URIParse(options.params.fromUri) : options.params.fromUri; } if (!fromURI) { throw new TypeError("Invalid from URI: " + options.params.fromUri); } let toURI = targetURI; if (options.params.toUri) { toURI = (typeof options.params.toUri === "string") ? Grammar.URIParse(options.params.toUri) : options.params.toUri; } if (!toURI) { throw new TypeError("Invalid to URI: " + options.params.toUri); } // Extra headers const extraHeaders = (options.extraHeaders || []).slice(); if (anonymous && userAgent.configuration.uri) { extraHeaders.push("P-Preferred-Identity: " + userAgent.configuration.uri.toString()); extraHeaders.push("Privacy: id"); } extraHeaders.push("Contact: " + contact); // extraHeaders.push("User-Agent: " + "xyplat"); extraHeaders.push("Allow: " + [ "ACK", "CANCEL", "INVITE", "MESSAGE", "BYE", "OPTIONS", "INFO", "NOTIFY", "REFER" ].toString()); if (userAgent.configuration.sipExtension100rel === SIPExtension.Required) { extraHeaders.push("Require: 100rel"); } if (userAgent.configuration.sipExtensionReplaces === SIPExtension.Required) { extraHeaders.push("Require: replaces"); } let body; if (this.body) { body = fromBodyLegacy(this.body); } // Request this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(C.INVITE, targetURI, fromURI, toURI, params, extraHeaders, body); if (!this.request.from) { throw new Error("From undefined."); } if (!this.request.to) { throw new Error("From undefined."); } this.localIdentity = this.request.from; this.remoteIdentity = this.request.to; // Options options.params = params; options.extraHeaders = extraHeaders; // Session properties this.contact = contact; this.fromTag = fromTag; this.id = this.request.callId + this.fromTag; this.onInfo = options.onInfo; this.passedOptions = options; // Save for later to use with refer this.renderbody = options.renderbody || undefined; this.rendertype = options.rendertype || "text/plain"; this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers || []; this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions || {}; // InviteClientContext properties this.inviteWithoutSdp = options.inviteWithoutSdp || false; this.isCanceled = false; this.earlyMedia = options.earlyMedia || false; userAgent.applicants[this.toString()] = this; } /** * Cancels the INVITE request. * @param options - Options bucket. */ cancel(options = {}) { this.logger.log("Inviter.cancel"); // validate state if (this.state !== SessionState$1.Initial && this.state !== SessionState$1.Establishing) { const error = new Error(`Invalid session state ${this.state}`); this.logger.error(error.message); return Promise.reject(error); } // canceled has some special cases if (this.isCanceled) { throw new Error("Already canceled."); } this.isCanceled = true; // transition state this.stateTransition(SessionState$1.Terminating); // cleanup media as needed this.disposeEarlyMedia(); if (this.sessionDescriptionHandler) { this.sessionDescriptionHandler.close(); } // helper function function getCancelReason(code, reason) { if (code && code < 200 || code > 699) { throw new TypeError("Invalid statusCode: " + code); } else if (code) { const cause = code; const text = getReasonPhrase(code) || reason; return "SIP;cause=" + cause + ';text="' + text + '"'; } } if (this.outgoingInviteRequest) { // the CANCEL may not be respected by peer(s), so don't transition to terminated let cancelReason; if (options.statusCode && options.reasonPhrase) { cancelReason = getCancelReason(options.statusCode, options.reasonPhrase); } this.outgoingInviteRequest.cancel(cancelReason, options); } else { this.logger.warn("Canceled session before INVITE was sent"); this.stateTransition(SessionState$1.Terminated); } return Promise.resolve(); } /** * Sends the INVITE request. * @remarks * TLDR... * 1) Only one offer/answer exchange permitted during initial INVITE. * 2) No "early media" if the initial offer is in an INVITE (default behavior). * 3) If "early media" and the initial offer is in an INVITE, no INVITE forking. * * 1) Only one offer/answer exchange permitted during initial INVITE. * * Our implementation replaces the following bullet point... * * o After having sent or received an answer to the first offer, the * UAC MAY generate subsequent offers in requests based on rules * specified for that method, but only if it has received answers * to any previous offers, and has not sent any offers to which it * hasn't gotten an answer. * https://tools.ietf.org/html/rfc3261#section-13.2.1 * * ...with... * * o After having sent or received an answer to the first offer, the * UAC MUST NOT generate subsequent offers in requests based on rules * specified for that method. * * ...which in combination with this bullet point... * * o Once the UAS has sent or received an answer to the initial * offer, it MUST NOT generate subsequent offers in any responses * to the initial INVITE. This means that a UAS based on this * specification alone can never generate subsequent offers until * completion of the initial transaction. * https://tools.ietf.org/html/rfc3261#section-13.2.1 * * ...ensures that EXACTLY ONE offer/answer exchange will occur * during an initial out of dialog INVITE request made by our UAC. * * * 2) No "early media" if the initial offer is in an INVITE (default behavior). * * While our implementation adheres to the following bullet point... * * o If the initial offer is in an INVITE, the answer MUST be in a * reliable non-failure message from UAS back to UAC which is * correlated to that INVITE. For this specification, that is * only the final 2xx response to that INVITE. That same exact * answer MAY also be placed in any provisional responses sent * prior to the answer. The UAC MUST treat the first session * description it receives as the answer, and MUST ignore any * session descriptions in subsequent responses to the initial * INVITE. * https://tools.ietf.org/html/rfc3261#section-13.2.1 * * We have made the following implementation decision with regard to early media... * * o If the initial offer is in the INVITE, the answer from the * UAS back to the UAC will establish a media session only * only after the final 2xx response to that INVITE is received. * * The reason for this decision is rooted in a restriction currently * inherent in WebRTC. Specifically, while a SIP INVITE request with an * initial offer may fork resulting in more than one provisional answer, * there is currently no easy/good way to to "fork" an offer generated * by a peer connection. In particular, a WebRTC offer currently may only * be matched with one answer and we have no good way to know which * "provisional answer" is going to be the "final answer". So we have * decided to punt and not create any "early media" sessions in this case. * * The upshot is that if you want "early media", you must not put the * initial offer in the INVITE. Instead, force the UAS to provide the * initial offer by sending an INVITE without an offer. In the WebRTC * case this allows us to create a unique peer connection with a unique * answer for every provisional offer with "early media" on all of them. * * * 3) If "early media" and the initial offer is in an INVITE, no INVITE forking. * * The default behaviour may be altered and "early media" utilized if the * initial offer is in the an INVITE by setting the `earlyMedia` options. * However in that case the INVITE request MUST NOT fork. This allows for * "early media" in environments where the forking behaviour of the SIP * servers being utilized is configured to disallow forking. */ invite(options = {}) { this.logger.log("Inviter.invite"); // validate state if (this.state !== SessionState$1.Initial) { // re-invite return super.invite(options); } if (!this.id) { throw new Error("Session id undefined."); } // save the session into the user agent sessions collection. this.userAgent.sessions[this.id] = this; // just send an INVITE with no sdp... if (options.withoutSdp || this.inviteWithoutSdp) { if (this.renderbody && this.rendertype) { this.request.body = { contentType: this.rendertype, body: this.renderbody }; } // transition state this.stateTransition(SessionState$1.Establishing); this.status = _SessionStatus.STATUS_INVITE_SENT; return Promise.resolve(this.sendInvite(options)); } // get an offer and send it in an INVITE const offerOptions = { sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers }; return this.getOffer(offerOptions) .then((body) => { // TODO: Review error handling... // There are some race conditions which can occur, all of which will cause stateTransition() to throw. // - invite() can be called (a)synchronously after invite() is called (second call to invite() fails) // - cancel() or terminate()) can be called (a)synchronously after invite() (invite() fails) // The caller should avoid the first case, but the second one is common. // For now we are just letting the state transition fail in all cases. // transition state this.stateTransition(SessionState$1.Establishing); this.status = _SessionStatus.STATUS_INVITE_SENT; this.request.body = { body: body.content, contentType: body.contentType }; return this.sendInvite(options); }) .catch((error) => { this.logger.log(error.message); this.stateTransition(SessionState$1.Terminated); throw error; }); } /** * Called to cleanup session after terminated. * Using it here just to dispose of early media. * @internal */ _close() { this.disposeEarlyMedia(); super._close(); } /** * 13.2.1 Creating the Initial INVITE * * Since the initial INVITE represents a request outside of a dialog, * its construction follows the procedures of Section 8.1.1. Additional * processing is required for the specific case of INVITE. * * An Allow header field (Section 20.5) SHOULD be present in the INVITE. * It indicates what methods can be invoked within a dialog, on the UA * sending the INVITE, for the duration of the dialog. For example, a * UA capable of receiving INFO requests within a dialog [34] SHOULD * include an Allow header field listing the INFO method. * * A Supported header field (Section 20.37) SHOULD be present in the * INVITE. It enumerates all the extensions understood by the UAC. * * An Accept (Section 20.1) header field MAY be present in the INVITE. * It indicates which Content-Types are acceptable to the UA, in both * the response received by it, and in any subsequent requests sent to * it within dialogs established by the INVITE. The Accept header field * is especially useful for indicating support of various session * description formats. * * The UAC MAY add an Expires header field (Section 20.19) to limit the * validity of the invitation. If the time indicated in the Expires * header field is reached and no final answer for the INVITE has been * received, the UAC core SHOULD generate a CANCEL request for the * INVITE, as per Section 9. * * A UAC MAY also find it useful to add, among others, Subject (Section * 20.36), Organization (Section 20.25) and User-Agent (Section 20.41) * header fields. They all contain information related to the INVITE. * * The UAC MAY choose to add a message body to the INVITE. Section * 8.1.1.10 deals with how to construct the header fields -- Content- * Type among others -- needed to describe the message body. * * https://tools.ietf.org/html/rfc3261#section-13.2.1 */ sendInvite(options = {}) { // There are special rules for message bodies that contain a session // description - their corresponding Content-Disposition is "session". // SIP uses an offer/answer model where one UA sends a session // description, called the offer, which contains a proposed description // of the session. The offer indicates the desired communications means // (audio, video, games), parameters of those means (such as codec // types) and addresses for receiving media from the answerer. The // other UA responds with another session description, called the // answer, which indicates which communications means are accepted, the // parameters that apply to those means, and addresses for receiving // media from the offerer. An offer/answer exchange is within the // context of a dialog, so that if a SIP INVITE results in multiple // dialogs, each is a separate offer/answer exchange. The offer/answer // model defines restrictions on when offers and answers can be made // (for example, you cannot make a new offer while one is in progress). // This results in restrictions on where the offers and answers can // appear in SIP messages. In this specification, offers and answers // can only appear in INVITE requests and responses, and ACK. The usage // of offers and answers is further restricted. For the initial INVITE // transaction, the rules are: // // o The initial offer MUST be in either an INVITE or, if not there, // in the first reliable non-failure message from the UAS back to // the UAC. In this specification, that is the final 2xx // response. // // o If the initial offer is in an INVITE, the answer MUST be in a // reliable non-failure message from UAS back to UAC which is // correlated to that INVITE. For this specification, that is // only the final 2xx response to that INVITE. That same exact // answer MAY also be placed in any provisional responses sent // prior to the answer. The UAC MUST treat the first session // description it receives as the answer, and MUST ignore any // session descriptions in subsequent responses to the initial // INVITE. // // o If the initial offer is in the first reliable non-failure // message from the UAS back to UAC, the answer MUST be in the // acknowledgement for that message (in this specification, ACK // for a 2xx response). // // o After having sent or received an answer to the first offer, the // UAC MAY generate subsequent offers in requests based on rules // specified for that method, but only if it has received answers // to any previous offers, and has not sent any offers to which it // hasn't gotten an answer. // // o Once the UAS has sent or received an answer to the initial // offer, it MUST NOT generate subsequent offers in any responses // to the initial INVITE. This means that a UAS based on this // specification alone can never generate subsequent offers until // completion of the initial transaction. // // https://tools.ietf.org/html/rfc3261#section-13.2.1 // 5 The Offer/Answer Model and PRACK // // RFC 3261 describes guidelines for the sets of messages in which // offers and answers [3] can appear. Based on those guidelines, this // extension provides additional opportunities for offer/answer // exchanges. // If the INVITE contained an offer, the UAS MAY generate an answer in a // reliable provisional response (assuming these are supported by the // UAC). That results in the establishment of the session before // completion of the call. Similarly, if a reliable provisional // response is the first reliable message sent back to the UAC, and the // INVITE did not contain an offer, one MUST appear in that reliable // provisional response. // If the UAC receives a reliable provisional response with an offer // (this would occur if the UAC sent an INVITE without an offer, in // which case the first reliable provisional response will contain the // offer), it MUST generate an answer in the PRACK. If the UAC receives // a reliable provisional response with an answer, it MAY generate an // additional offer in the PRACK. If the UAS receives a PRACK with an // offer, it MUST place the answer in the 2xx to the PRACK. // Once an answer has been sent or received, the UA SHOULD establish the // session based on the parameters of the offer and answer, even if the // original INVITE itself has not been responded to. // If the UAS had placed a session description in any reliable // provisional response that is unacknowledged when the INVITE is // accepted, the UAS MUST delay sending the 2xx until the provisional // response is acknowledged. Otherwise, the reliability of the 1xx // cannot be guaranteed, and reliability is needed for proper operation // of the offer/answer exchange. // All user agents that support this extension MUST support all // offer/answer exchanges that are possible based on the rules in // Section 13.2 of RFC 3261, based on the existence of INVITE and PRACK // as requests, and 2xx and reliable 1xx as non-failure reliable // responses. // // https://tools.ietf.org/html/rfc3262#section-5 //// // The Offer/Answer Model Implementation // // The offer/answer model is straight forward, but one MUST READ the specifications... // // 13.2.1 Creating the Initial INVITE (paragraph 8 in particular) // https://tools.ietf.org/html/rfc3261#section-13.2.1 // // 5 The Offer/Answer Model and PRACK // https://tools.ietf.org/html/rfc3262#section-5 // // Session Initiation Protocol (SIP) Usage of the Offer/Answer Model // https://tools.ietf.org/html/rfc6337 //// //// // TODO: The Offer/Answer Model Implementation // // Currently if `earlyMedia` is enabled and the INVITE request forks, // the session is terminated if the early dialog does not match the // confirmed dialog. This restriction make sense in a WebRTC environment, // but there are other enviroments where this restriction does not hold. // // So while we currently cannot make the offer in INVITE+forking+webrtc // case work, we propose doing the following... // // OPTION 1 // - add a `earlyMediaForking` option and // - require SDH.setDescription() to be callable multiple times. // // OPTION 2 // 1) modify SDH Factory to provide an initial offer without giving us the SDH, and then... // 2) stick that offer in the initial INVITE, and when 183 with initial answer is received... // 3) ask SDH Factory if it supports "earlyRemoteAnswer" // a) if true, ask SDH Factory to createSDH(localOffer).then((sdh) => sdh.setDescription(remoteAnswer) // b) if false, defer getting a SDH until 2xx response is received // // Our supplied WebRTC SDH will default to behavior 3b which works in forking environment (without) // early media if initial offer is in the INVITE). We will, however, provide an "inviteWillNotFork" // option which if set to "true" will have our supplied WebRTC SDH behave in the 3a manner. // That will result in // - early media working with initial offer in the INVITE, and... // - if the INVITE forks, the session terminating with an ERROR that reads like // "You set 'inviteWillNotFork' to true but the INVITE forked. You can't eat your cake, and have it too." // - furthermore, we accept that users will report that error to us as "bug" regardless // // So, SDH Factory is going to end up with a new interface along the lines of... // // interface SessionDescriptionHandlerFactory { // makeLocalOffer(): Promise; // makeSessionDescriptionHandler( // initialOffer: ContentTypeAndBody, offerType: "local" | "remote" // ): Promise; // supportsEarlyRemoteAnswer: boolean; // supportsContentType(contentType: string): boolean; // getDescription(description: ContentTypeAndBody): Promise // setDescription(description: ContentTypeAndBody): Promise // } //// // Send the INVITE request. this.outgoingInviteRequest = this.userAgent.userAgentCore.invite(this.request, { onAccept: (inviteResponse) => { // Our transaction layer is "non-standard" in that it will only // pass us a 2xx response once per branch, so there is no need to // worry about dealing with 2xx retransmissions. However, we can // and do still get 2xx responses for multiple branches (when an // INVITE is forked) which may create multiple confirmed dialogs. // Herein we are acking and sending a bye to any confirmed dialogs // which arrive beyond the first one. This is the desired behavior // for most applications (but certainly not all). // If we already received a confirmed dialog, ack & bye this additional confirmed session. if (this.dialog) { this.logger.log("Additional confirmed dialog, sending ACK and BYE"); this.ackAndBye(inviteResponse); // We do NOT transition state in this case (this is an "extra" dialog) return; } // If the user requested cancellation, ack & bye this session. if (this.isCanceled) { this.logger.log("Canceled session accepted, sending ACK and BYE"); this.ackAndBye(inviteResponse); this.stateTransition(SessionState$1.Terminated); return; } this.notifyReferer(inviteResponse); this.onAccept(inviteResponse) .then(() => { this.disposeEarlyMedia(); }) .catch((error) => { this.disposeEarlyMedia(); }) .then(() => { if (options.requestDelegate && options.requestDelegate.onAccept) { options.requestDelegate.onAccept(inviteResponse); } }); }, onProgress: (inviteResponse) => { // If the user requested cancellation, ignore response. if (this.isCanceled) { return; } this.notifyReferer(inviteResponse); this.onProgress(inviteResponse) .catch((error) => { this.disposeEarlyMedia(); }) .then(() => { if (options.requestDelegate && options.requestDelegate.onProgress) { options.requestDelegate.onProgress(inviteResponse); } }); }, onRedirect: (inviteResponse) => { this.notifyReferer(inviteResponse); this.onRedirect(inviteResponse); if (options.requestDelegate && options.requestDelegate.onRedirect) { options.requestDelegate.onRedirect(inviteResponse); } }, onReject: (inviteResponse) => { this.notifyReferer(inviteResponse); this.onReject(inviteResponse); if (options.requestDelegate && options.requestDelegate.onReject) { options.requestDelegate.onReject(inviteResponse); } }, onTrying: (inviteResponse) => { this.notifyReferer(inviteResponse); this.onTrying(inviteResponse); if (options.requestDelegate && options.requestDelegate.onTrying) { options.requestDelegate.onTrying(inviteResponse); } } }); return this.outgoingInviteRequest; } disposeEarlyMedia() { this.earlyMediaSessionDescriptionHandlers.forEach((sessionDescriptionHandler) => { sessionDescriptionHandler.close(); }); this.earlyMediaSessionDescriptionHandlers.clear(); } notifyReferer(response) { if (!this.referred) { return; } if (!(this.referred instanceof Session)) { throw new Error("Referred session not instance of session"); } if (!this.referred.dialog) { return; } if (!response.message.statusCode) { throw new Error("Status code undefined."); } if (!response.message.reasonPhrase) { throw new Error("Reason phrase undefined."); } const statusCode = response.message.statusCode; const reasonPhrase = response.message.reasonPhrase; const body = `SIP/2.0 ${statusCode} ${reasonPhrase}`.trim(); const outgoingNotifyRequest = this.referred.dialog.notify(undefined, { extraHeaders: [ "Event: refer", "Subscription-State: terminated", ], body: { contentDisposition: "render", contentType: "message/sipfrag", content: body } }); // The implicit subscription created by a REFER is the same as a // subscription created with a SUBSCRIBE request. The agent issuing the // REFER can terminate this subscription prematurely by unsubscribing // using the mechanisms described in [2]. Terminating a subscription, // either by explicitly unsubscribing or rejecting NOTIFY, is not an // indication that the referenced request should be withdrawn or // abandoned. // https://tools.ietf.org/html/rfc3515#section-2.4.4 // FIXME: TODO: This should be done in a subscribe dialog to satisfy the above. // If the notify is rejected, stop sending NOTIFY requests. outgoingNotifyRequest.delegate = { onReject: () => { this.referred = undefined; } }; } /** * Handle final response to initial INVITE. * @param inviteResponse - 2xx response. */ onAccept(inviteResponse) { this.logger.log("Inviter.onAccept"); // validate state if (this.state !== SessionState$1.Establishing) { this.logger.error(`Accept received while in state ${this.state}, dropping response`); return Promise.reject(new Error(`Invalid session state ${this.state}`)); } const response = inviteResponse.message; const session = inviteResponse.session; // Ported behavior. if (response.hasHeader("P-Asserted-Identity")) { this.assertedIdentity = Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); } // We have a confirmed dialog. this.dialog = session; this.dialog.delegate = { onAck: (ackRequest) => this.onAckRequest(ackRequest), onBye: (byeRequest) => this.onByeRequest(byeRequest), onInfo: (infoRequest) => this.onInfoRequest(infoRequest), onInvite: (inviteRequest) => this.onInviteRequest(inviteRequest), onNotify: (notifyRequest) => this.onNotifyRequest(notifyRequest), onPrack: (prackRequest) => this.onPrackRequest(prackRequest), onRefer: (referRequest) => this.onReferRequest(referRequest) }; const sdhOptions = this.sessionDescriptionHandlerOptions; const sdhModifiers = this.sessionDescriptionHandlerModifiers; switch (session.signalingState) { case SignalingState.Initial: // INVITE without offer, so MUST have offer at this point, so invalid state. this.logger.error("Received 2xx response to INVITE without a session description"); this.ackAndBye(inviteResponse, 400, "Missing session description"); this.stateTransition(SessionState$1.Terminated); return Promise.reject(new Error("Bad Media Description")); case SignalingState.HaveLocalOffer: // INVITE with offer, so MUST have answer at this point, so invalid state. this.logger.error("Received 2xx response to INVITE without a session description"); this.ackAndBye(inviteResponse, 400, "Missing session description"); this.stateTransition(SessionState$1.Terminated); return Promise.reject(new Error("Bad Media Description")); case SignalingState.HaveRemoteOffer: { // INVITE without offer, received offer in 2xx, so MUST send answer in ACK. if (!this.dialog.offer) { throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`); } const options = { sessionDescriptionHandlerOptions: sdhOptions, sessionDescriptionHandlerModifiers: sdhModifiers }; return this.setOfferAndGetAnswer(this.dialog.offer, options) .then((body) => { this.status = _SessionStatus.STATUS_CONFIRMED; const ackRequest = inviteResponse.ack({ body }); this.stateTransition(SessionState$1.Established); }) .catch((error) => { this.ackAndBye(inviteResponse, 488, "Invalid session description"); this.stateTransition(SessionState$1.Terminated); throw error; }); } case SignalingState.Stable: { // If INVITE without offer and we have already completed the initial exchange. if (this.earlyMediaSessionDescriptionHandlers.size > 0) { const sdh = this.earlyMediaSessionDescriptionHandlers.get(session.id); if (!sdh) { throw new Error("Session description handler undefined."); } this.setSessionDescriptionHandler(sdh); this.earlyMediaSessionDescriptionHandlers.delete(session.id); this.status = _SessionStatus.STATUS_CONFIRMED; const ackRequest = inviteResponse.ack(); this.stateTransition(SessionState$1.Established); return Promise.resolve(); } // If INVITE with offer and we used an "early" answer in a provisional response for media if (this.earlyMediaDialog) { // If early media dialog doesn't match confirmed dialog, we must unfortunately fail. // This limitation stems from how WebRTC currently implements its offer/answer model. // There are details elsewhere, but in short a WebRTC offer cannot be forked. if (this.earlyMediaDialog !== session) { if (this.earlyMedia) { const message = "You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests " + "do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly " + "the end point which accepted the INVITE (confirmed dialog) does not match the end point with " + "which early media has been setup (early dialog) and thus this session is unable to proceed. " + "In accordance with the SIP specifications, the SIP servers your end point is connected to " + "determine if an INVITE forks and the forking behaviour of those servers cannot be controlled " + "by this library. If you wish to use early media with this library you must configure those " + "servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow " + "this library to function with any INVITE requests which do fork."; this.logger.error(message); } const error = new Error("Early media dialog does not equal confirmed dialog, terminating session"); this.logger.error(error.message); this.ackAndBye(inviteResponse, 488, "Not Acceptable Here"); this.stateTransition(SessionState$1.Terminated); return Promise.reject(error); } // Otherwise we are good to go. this.status = _SessionStatus.STATUS_CONFIRMED; const ackRequest = inviteResponse.ack(); this.stateTransition(SessionState$1.Established); return Promise.resolve(); } // If INVITE with offer and we have been waiting till now to apply the answer. const answer = session.answer; if (!answer) { throw new Error("Answer is undefined."); } const options = { sessionDescriptionHandlerOptions: sdhOptions, sessionDescriptionHandlerModifiers: sdhModifiers }; return this.setAnswer(answer, options) .then(() => { // This session has completed an initial offer/answer exchange... let ackOptions; if (this.renderbody && this.rendertype) { ackOptions = { body: { contentDisposition: "render", contentType: this.rendertype, content: this.renderbody } }; } this.status = _SessionStatus.STATUS_CONFIRMED; const ackRequest = inviteResponse.ack(ackOptions); this.stateTransition(SessionState$1.Established); }) .catch((error) => { this.logger.error(error.message); this.ackAndBye(inviteResponse, 488, "Not Acceptable Here"); this.stateTransition(SessionState$1.Terminated); throw error; }); } case SignalingState.Closed: // Dialog has terminated. return Promise.reject(new Error("Terminated.")); default: throw new Error("Unknown session signaling state."); } } /** * Handle provisional response to initial INVITE. * @param inviteResponse - 1xx response. */ onProgress(inviteResponse) { this.logger.log("Inviter.onProgress"); // validate state if (this.state !== SessionState$1.Establishing) { this.logger.error(`Progress received while in state ${this.state}, dropping response`); return Promise.reject(new Error(`Invalid session state ${this.state}`)); } if (!this.outgoingInviteRequest) { throw new Error("Outgoing INVITE request undefined."); } const response = inviteResponse.message; const session = inviteResponse.session; // Ported - Set status. this.status = _SessionStatus.STATUS_1XX_RECEIVED; // Ported - Set assertedIdentity. if (response.hasHeader("P-Asserted-Identity")) { this.assertedIdentity = Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); } // If a provisional response is received for an initial request, and // that response contains a Require header field containing the option // tag 100rel, the response is to be sent reliably. If the response is // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be // ignored, and the procedures below MUST NOT be used. // https://tools.ietf.org/html/rfc3262#section-4 const requireHeader = response.getHeader("require"); const rseqHeader = response.getHeader("rseq"); const rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; const responseReliable = !!rseq; const extraHeaders = []; if (responseReliable) { extraHeaders.push("RAck: " + response.getHeader("rseq") + " " + response.getHeader("cseq")); } const sdhOptions = this.sessionDescriptionHandlerOptions; const sdhModifiers = this.sessionDescriptionHandlerModifiers; switch (session.signalingState) { case SignalingState.Initial: // INVITE without offer and session still has no offer (and no answer). if (responseReliable) { // Similarly, if a reliable provisional // response is the first reliable message sent back to the UAC, and the // INVITE did not contain an offer, one MUST appear in that reliable // provisional response. // https://tools.ietf.org/html/rfc3262#section-5 this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."); // FIXME: Known popular UA's currently end up here... inviteResponse.prack({ extraHeaders }); } return Promise.resolve(); case SignalingState.HaveLocalOffer: // INVITE with offer and session only has that initial local offer. if (responseReliable) { inviteResponse.prack({ extraHeaders }); } return Promise.resolve(); case SignalingState.HaveRemoteOffer: if (!responseReliable) { // The initial offer MUST be in either an INVITE or, if not there, // in the first reliable non-failure message from the UAS back to // the UAC. // https://tools.ietf.org/html/rfc3261#section-13.2.1 // According to Section 13.2.1 of [RFC3261], 'The first reliable // non-failure message' must have an offer if there is no offer in the // INVITE request. This means that the User Agent (UA) that receives // the INVITE request without an offer must include an offer in the // first reliable response with 100rel extension. If no reliable // provisional response has been sent, the User Agent Server (UAS) must // include an offer when sending 2xx response. // https://tools.ietf.org/html/rfc6337#section-2.2 this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."); return Promise.resolve(); } // If the initial offer is in the first reliable non-failure // message from the UAS back to UAC, the answer MUST be in the // acknowledgement for that message const sdh = this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions || {}); this.earlyMediaSessionDescriptionHandlers.set(session.id, sdh); return sdh .setDescription(response.body, sdhOptions, sdhModifiers) .then(() => sdh.getDescription(sdhOptions, sdhModifiers)) .then((description) => { const body = { contentDisposition: "session", contentType: description.contentType, content: description.body }; inviteResponse.prack({ extraHeaders, body }); }) .catch((error) => { if (this.status === _SessionStatus.STATUS_TERMINATED) { throw error; } this.stateTransition(SessionState$1.Terminated); throw error; }); case SignalingState.Stable: // This session has completed an initial offer/answer exchange, so... // - INVITE with SDP and this provisional response MAY be reliable // - INVITE without SDP and this provisional response MAY be reliable if (responseReliable) { inviteResponse.prack({ extraHeaders }); } if (this.earlyMedia && !this.earlyMediaDialog) { this.earlyMediaDialog = session; const answer = session.answer; if (!answer) { throw new Error("Answer is undefined."); } const options = { sessionDescriptionHandlerOptions: sdhOptions, sessionDescriptionHandlerModifiers: sdhModifiers }; return this.setAnswer(answer, options) .catch((error) => { if (this.status === _SessionStatus.STATUS_TERMINATED) { throw error; } this.stateTransition(SessionState$1.Terminated); throw error; }); } return Promise.resolve(); case SignalingState.Closed: // Dialog has terminated. return Promise.reject(new Error("Terminated.")); default: throw new Error("Unknown session signaling state."); } } /** * Handle final response to initial INVITE. * @param inviteResponse - 3xx response. */ onRedirect(inviteResponse) { this.logger.log("Inviter.onRedirect"); // validate state if (this.state !== SessionState$1.Establishing && this.state !== SessionState$1.Terminating) { this.logger.error(`Redirect received while in state ${this.state}, dropping response`); return; } // transition state this.stateTransition(SessionState$1.Terminated); } /** * Handle final response to initial INVITE. * @param inviteResponse - 4xx, 5xx, or 6xx response. */ onReject(inviteResponse) { this.logger.log("Inviter.onReject"); // validate state if (this.state !== SessionState$1.Establishing && this.state !== SessionState$1.Terminating) { this.logger.error(`Reject received while in state ${this.state}, dropping response`); return; } // transition state this.stateTransition(SessionState$1.Terminated); } /** * Handle final response to initial INVITE. * @param inviteResponse - 100 response. */ onTrying(inviteResponse) { this.logger.log("Inviter.onTrying"); // validate state if (this.state !== SessionState$1.Establishing) { this.logger.error(`Trying received while in state ${this.state}, dropping response`); return; } } } /** * A received message (incoming MESSAGE). * @public */ class Message { /** @internal */ constructor(incomingMessageRequest) { this.incomingMessageRequest = incomingMessageRequest; } /** Incoming MESSAGE request message. */ get request() { return this.incomingMessageRequest.message; } /** Accept the request. */ accept(options) { this.incomingMessageRequest.accept(options); return Promise.resolve(); } /** Reject the request. */ reject(options) { this.incomingMessageRequest.reject(options); return Promise.resolve(); } } /** * A messager sends a {@link Message} (outgoing MESSAGE). * @public */ class Messager { /** * Constructs a new instance of the `Messager` class. * @param userAgent - User agent. See {@link UserAgent} for details. * @param targetURI - Request URI identifying the target of the message. * @param content - Content for the body of the message. * @param contentType - Content type of the body of the message. * @param options - Options bucket. See {@link MessagerOptions} for details. */ constructor(userAgent, targetURI, content, contentType = "text/plain", options = {}) { this._disposed = false; // Logger this.logger = userAgent.getLogger("sip.Messager"); // Default options params options.params = options.params || {}; // URIs let fromURI = userAgent.userAgentCore.configuration.aor; if (options.params.fromUri) { fromURI = (typeof options.params.fromUri === "string") ? Grammar.URIParse(options.params.fromUri) : options.params.fromUri; } if (!fromURI) { throw new TypeError("Invalid from URI: " + options.params.fromUri); } let toURI = targetURI; if (options.params.toUri) { toURI = (typeof options.params.toUri === "string") ? Grammar.URIParse(options.params.toUri) : options.params.toUri; } if (!toURI) { throw new TypeError("Invalid to URI: " + options.params.toUri); } // Message params const params = options.params ? Object.assign({}, options.params) : {}; // Extra headers const extraHeaders = (options.extraHeaders || []).slice(); // Body const contentDisposition = "render"; const body = { contentDisposition, contentType, content }; // Build the request this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(C.MESSAGE, targetURI, fromURI, toURI, params, extraHeaders, body); // User agent this.userAgent = userAgent; } /** * Send the message. */ message(options = {}) { this.userAgent.userAgentCore.request(this.request, options.requestDelegate); return Promise.resolve(); } /** * Destructor. * @internal */ _dispose() { if (this._disposed) { return; } this._disposed = true; } } /** * {@link Registerer} state. * @remarks * Valid state transitions: * ``` * 1. "initial" --> "registered" * 2. "initial" --> "unregistered" * 3. "initial" --> "terminated" * 4. "registered" --> "unregistered" * 5. "registered" --> "terminated" * 6. "unregistered" --> "registered" * 7. "unregistered" --> "terminated" * ``` * @public */ var RegistererState; (function(RegistererState) { RegistererState["Initial"] = "Initial"; RegistererState["Registered"] = "Registered"; RegistererState["Unregistered"] = "Unregistered"; RegistererState["Terminated"] = "Terminated"; })(RegistererState || (RegistererState = {})); /** * A registerer registers a contact for an address of record (outgoing REGISTER). * @public */ class Registerer { /** * Constructs a new instance of the `Registerer` class. * @param userAgent - User agent. See {@link UserAgent} for details. * @param options - Options bucket. See {@link RegistererOptions} for details. */ constructor(userAgent, options = {}) { /** The contacts returned from the most recent accepted REGISTER request. */ this._contacts = []; /** The registration state. */ this._state = RegistererState.Initial; /** Emits when the registration state changes. */ this._stateEventEmitter = new EventEmitter(); /** True is waiting for final response to outstanding REGISTER request. */ this._waiting = false; /** Emits when waiting changes. */ this._waitingEventEmitter = new EventEmitter(); // Set user agent this.userAgent = userAgent; // Default registrar is domain portion of user agent uri const defaultUserAgentRegistrar = userAgent.configuration.uri.clone(); defaultUserAgentRegistrar.user = undefined; // Initialize configuration this.options = Object.assign(Object.assign(Object.assign({}, Registerer.defaultOptions), { registrar: defaultUserAgentRegistrar }), options); // Make sure we are not using references to array options this.options.extraContactHeaderParams = (this.options.extraContactHeaderParams || []).slice(); this.options.extraHeaders = (this.options.extraHeaders || []).slice(); // Make sure we are not using references to registrar uri if (!this.options.registrar) { throw new Error("Registrar undefined."); } this.options.registrar = this.options.registrar.clone(); // Set instanceId and regId conditional defaults and validate if (this.options.regId && !this.options.instanceId) { this.options.instanceId = Registerer.newUUID(); } else if (!this.options.regId && this.options.instanceId) { this.options.regId = 1; } if (this.options.instanceId && Grammar.parse(this.options.instanceId, "uuid") === -1) { throw new Error("Invalid instanceId."); } if (this.options.regId && this.options.regId < 0) { throw new Error("Invalid regId."); } const registrar = this.options.registrar; const fromURI = (this.options.params && this.options.params.fromUri) || userAgent.userAgentCore.configuration.aor; const toURI = (this.options.params && this.options.params.toUri) || userAgent.configuration.uri; const params = this.options.params || {}; const extraHeaders = (options.extraHeaders || []).slice(); // Build the request this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(C.REGISTER, registrar, fromURI, toURI, params, extraHeaders, undefined); // Registration expires this.expires = this.options.expires || Registerer.defaultOptions.expires; if (this.expires < 0) { throw new Error("Invalid expires."); } // initialize logger this.logger = userAgent.getLogger("sip.Registerer"); if (this.options.logConfiguration) { this.logger.log("Configuration:"); Object.keys(this.options).forEach((key) => { const value = this.options[key]; switch (key) { case "registrar": this.logger.log("· " + key + ": " + value); break; default: this.logger.log("· " + key + ": " + JSON.stringify(value)); } }); } userAgent.transport.on("disconnected", () => this.onTransportDisconnected()); // Add to UA's collection this.id = this.request.callId + this.request.from.parameters.tag; this.userAgent.registerers[this.id] = this; } // http://stackoverflow.com/users/109538/broofa static newUUID() { const UUID = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { const r = Math.floor(Math.random() * 16); const v = c === "x" ? r : (r % 4 + 8); return v.toString(16); }); return UUID; } /** The registered contacts. */ get contacts() { return this._contacts.slice(); } /** The registration state. */ get state() { return this._state; } /** Emits when the registerer state changes. */ get stateChange() { return makeEmitter(this._stateEventEmitter); } /** Destructor. */ async dispose() { // Remove from UA's collection delete this.userAgent.registerers[this.id]; // If registered, unregisters and resolves after final response received. return new Promise((resolve, reject) => { const doClose = () => { // If we are registered, unregister and resolve after our state changes if (!this.waiting && this._state === RegistererState.Registered) { this.stateChange.once(() => { this.terminated(); resolve(); }); this.unregister(); return; } // Otherwise just resolve this.terminated(); resolve(); }; // If we are waiting for an outstanding request, wait for it to finish and then try closing. // Otherwise just try closing. if (this.waiting) { this.waitingChange.once(() => doClose()); } else { doClose(); } }); } /** * Sends the REGISTER request. * @remarks * If successfull, sends re-REGISTER requests prior to registration expiration until `unsubscribe()` is called. * Rejects with `RequestPendingError` if a REGISTER request is alreadly in progress. */ async register(options = {}) { // UAs MUST NOT send a new registration (that is, containing new Contact // header field values, as opposed to a retransmission) until they have // received a final response from the registrar for the previous one or // the previous REGISTER request has timed out. // https://tools.ietf.org/html/rfc3261#section-10.2 if (this.waiting) { const error = new RequestPendingError("REGISTER request already in progress, waiting for final response"); return Promise.reject(error); } // Options if (options.requestOptions) { this.options = Object.assign(Object.assign({}, this.options), options.requestOptions); } // Extra headers const extraHeaders = (this.options.extraHeaders || []).slice(); extraHeaders.push("Contact: " + this.generateContactHeader(this.expires)); // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency extraHeaders.push("Allow: " + [ "ACK", "CANCEL", "INVITE", "MESSAGE", "BYE", "OPTIONS", "INFO", "NOTIFY", "REFER" ].toString()); // extraHeaders.push("User-Agent: " + "xyplat"); // Call-ID: All registrations from a UAC SHOULD use the same Call-ID // header field value for registrations sent to a particular // registrar. // // CSeq: The CSeq value guarantees proper ordering of REGISTER // requests. A UA MUST increment the CSeq value by one for each // REGISTER request with the same Call-ID. // https://tools.ietf.org/html/rfc3261#section-10.2 this.request.cseq++; this.request.setHeader("cseq", this.request.cseq + " REGISTER"); this.request.extraHeaders = extraHeaders; this.waitingToggle(true); const outgoingRegisterRequest = this.userAgent.userAgentCore.register(this.request, { onAccept: (response) => { let expires; // FIXME: This does NOT appear to be to spec and should be removed. // I haven't found anywhere that an Expires header may be used in a response. if (response.message.hasHeader("expires")) { expires = Number(response.message.getHeader("expires")); } // 8. The registrar returns a 200 (OK) response. The response MUST // contain Contact header field values enumerating all current // bindings. Each Contact value MUST feature an "expires" // parameter indicating its expiration interval chosen by the // registrar. The response SHOULD include a Date header field. // https://tools.ietf.org/html/rfc3261#section-10.3 this._contacts = response.message.getHeaders("contact"); let contacts = this._contacts.length; if (!contacts) { this.logger.error("No Contact header in response to REGISTER, dropping response."); this.unregistered(); return; } // The 200 (OK) response from the registrar contains a list of Contact // fields enumerating all current bindings. The UA compares each // contact address to see if it created the contact address, using // comparison rules in Section 19.1.4. If so, it updates the expiration // time interval according to the expires parameter or, if absent, the // Expires field value. The UA then issues a REGISTER request for each // of its bindings before the expiration interval has elapsed. // https://tools.ietf.org/html/rfc3261#section-10.2.4 let contact; while (contacts--) { contact = response.message.parseHeader("contact", contacts); if (contact.uri.user === this.userAgent.contact.uri.user) { expires = contact.getParam("expires"); break; } else { contact = undefined; } } // There must be a matching contact. if (contact === undefined) { this.logger.error("No Contact header pointing to us, dropping response"); this.unregistered(); this.waitingToggle(false); return; } // The contact must have an expires. if (expires === undefined) { this.logger.error("Contact pointing to us is missing expires parameter, dropping response"); this.unregistered(); this.waitingToggle(false); return; } // Save gruu values if (contact.hasParam("temp-gruu")) { this.userAgent.contact.tempGruu = Grammar.URIParse(contact.getParam("temp-gruu").replace(/"/g, "")); } if (contact.hasParam("pub-gruu")) { this.userAgent.contact.pubGruu = Grammar.URIParse(contact.getParam("pub-gruu").replace(/"/g, "")); } this.registered(expires); if (options.requestDelegate && options.requestDelegate.onAccept) { options.requestDelegate.onAccept(response); } this.waitingToggle(false); }, onProgress: (response) => { if (options.requestDelegate && options.requestDelegate.onProgress) { options.requestDelegate.onProgress(response); } }, onRedirect: (response) => { this.logger.error("Redirect received. Not supported."); this.unregistered(); if (options.requestDelegate && options.requestDelegate.onRedirect) { options.requestDelegate.onRedirect(response); } this.waitingToggle(false); }, onReject: (response) => { if (response.message.statusCode === 423) { // If a UA receives a 423 (Interval Too Brief) response, it MAY retry // the registration after making the expiration interval of all contact // addresses in the REGISTER request equal to or greater than the // expiration interval within the Min-Expires header field of the 423 // (Interval Too Brief) response. // https://tools.ietf.org/html/rfc3261#section-10.2.8 // // The registrar MAY choose an expiration less than the requested // expiration interval. If and only if the requested expiration // interval is greater than zero AND smaller than one hour AND // less than a registrar-configured minimum, the registrar MAY // reject the registration with a response of 423 (Interval Too // Brief). This response MUST contain a Min-Expires header field // that states the minimum expiration interval the registrar is // willing to honor. It then skips the remaining steps. // https://tools.ietf.org/html/rfc3261#section-10.3 if (!response.message.hasHeader("min-expires")) { // This response MUST contain a Min-Expires header field this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"); this.unregistered(); this.waitingToggle(false); return; } // Increase our registration interval to the suggested minimum this.expires = Number(response.message.getHeader("min-expires")); // Attempt the registration again immediately this.waitingToggle(false); this.register(); return; } if (response.message.statusCode === 403) { let ifcregError = response.message.getHeader("errcode"); if (ifcregError != null) { if (ifcregError.startsWith("10003")) { response.message.statusCode = 404; } else if (ifcregError.startsWith("10001")) { response.message.statusCode = 405; } else if (ifcregError.startsWith("10002")) { response.message.statusCode = 406; } } } this.logger.warn(`Failed to register, status code ${response.message.statusCode}`); this.unregistered(); if (options.requestDelegate && options.requestDelegate.onReject) { options.requestDelegate.onReject(response); } this.waitingToggle(false); }, onTrying: (response) => { if (options.requestDelegate && options.requestDelegate.onTrying) { options.requestDelegate.onTrying(response); } } }); return Promise.resolve(outgoingRegisterRequest); } /** * Sends the REGISTER request with expires equal to zero. * Rejects with `RequestPendingError` if a REGISTER request is alreadly in progress. */ async unregister(options = {}) { // UAs MUST NOT send a new registration (that is, containing new Contact // header field values, as opposed to a retransmission) until they have // received a final response from the registrar for the previous one or // the previous REGISTER request has timed out. // https://tools.ietf.org/html/rfc3261#section-10.2 if (this.waiting) { const error = new RequestPendingError("REGISTER request already in progress, waiting for final response"); return Promise.reject(error); } if (this._state !== RegistererState.Registered && !options.all) { this.logger.warn("Not currently registered, but sending an unregister anyway."); } if (options.requestOptions) { this.options = Object.assign(Object.assign({}, this.options), options.requestOptions); } // Extra headers const extraHeaders = (this.options.extraHeaders || []).slice(); // Extra headers // const extraHeaders = (options.requestOptions && options.requestOptions.extraHeaders || []).slice(); this.request.extraHeaders = extraHeaders; // Registrations are soft state and expire unless refreshed, but can // also be explicitly removed. A client can attempt to influence the // expiration interval selected by the registrar as described in Section // 10.2.1. A UA requests the immediate removal of a binding by // specifying an expiration interval of "0" for that contact address in // a REGISTER request. UAs SHOULD support this mechanism so that // bindings can be removed before their expiration interval has passed. // // The REGISTER-specific Contact header field value of "*" applies to // all registrations, but it MUST NOT be used unless the Expires header // field is present with a value of "0". // https://tools.ietf.org/html/rfc3261#section-10.2.2 if (options.all) { extraHeaders.push("Contact: *"); extraHeaders.push("Expires: 0"); } else { extraHeaders.push("Contact: " + this.generateContactHeader(0)); } // Call-ID: All registrations from a UAC SHOULD use the same Call-ID // header field value for registrations sent to a particular // registrar. // // CSeq: The CSeq value guarantees proper ordering of REGISTER // requests. A UA MUST increment the CSeq value by one for each // REGISTER request with the same Call-ID. // https://tools.ietf.org/html/rfc3261#section-10.2 this.request.cseq++; this.request.setHeader("cseq", this.request.cseq + " REGISTER"); // Pre-emptively clear the registration timer to avoid a race condition where // this timer fires while waiting for a final response to the unsubscribe. if (this.registrationTimer !== undefined) { clearTimeout(this.registrationTimer); this.registrationTimer = undefined; } this.waitingToggle(true); const outgoingRegisterRequest = this.userAgent.userAgentCore.register(this.request, { onAccept: (response) => { this._contacts = response.message.getHeaders("contact"); // Update contacts this.unregistered(); if (options.requestDelegate && options.requestDelegate.onAccept) { options.requestDelegate.onAccept(response); } this.waitingToggle(false); }, onProgress: (response) => { if (options.requestDelegate && options.requestDelegate.onProgress) { options.requestDelegate.onProgress(response); } }, onRedirect: (response) => { this.logger.error("Unregister redirected. Not currently supported."); this.unregistered(); if (options.requestDelegate && options.requestDelegate.onRedirect) { options.requestDelegate.onRedirect(response); } this.waitingToggle(false); }, onReject: (response) => { this.logger.error(`Unregister rejected with status code ${response.message.statusCode}`); this.unregistered(); if (options.requestDelegate && options.requestDelegate.onReject) { options.requestDelegate.onReject(response); } this.waitingToggle(false); }, onTrying: (response) => { if (options.requestDelegate && options.requestDelegate.onTrying) { options.requestDelegate.onTrying(response); } } }); return Promise.resolve(outgoingRegisterRequest); } /** * Clear registration timers. */ clearTimers() { if (this.registrationTimer !== undefined) { clearTimeout(this.registrationTimer); this.registrationTimer = undefined; } if (this.registrationExpiredTimer !== undefined) { clearTimeout(this.registrationExpiredTimer); this.registrationExpiredTimer = undefined; } } /** * Generate Contact Header */ generateContactHeader(expires) { let contact = this.userAgent.contact.toString(); if (this.options.regId && this.options.instanceId) { contact += ";reg-id=" + this.options.regId; contact += ';+sip.instance=""'; } if (this.options.extraContactHeaderParams) { this.options.extraContactHeaderParams.forEach((header) => { contact += ";" + header; }); } contact += ";expires=" + expires; return contact; } /** * @deprecated This should get cleaned up when Transport is reworked */ onTransportDisconnected() { // this.unregistered(); } /** * Helper function, called when registered. */ registered(expires) { this.clearTimers(); // Re-Register before the expiration interval has elapsed. // For that, decrease the expires value. ie: 3 seconds this.registrationTimer = setTimeout(() => { this.registrationTimer = undefined; this.register(); }, (expires * 1000) - 3000); // We are unregistered if the registration expires. this.registrationExpiredTimer = setTimeout(() => { this.logger.warn("Registration expired"); this.unregistered(); }, expires * 1000); if (this._state !== RegistererState.Registered) { this.stateTransition(RegistererState.Registered); } } /** * Helper function, called when unregistered. */ unregistered() { this.clearTimers(); if (this._state !== RegistererState.Unregistered) { this.stateTransition(RegistererState.Unregistered); } } /** * Helper function, called when terminated. */ terminated() { this.clearTimers(); if (this._state !== RegistererState.Terminated) { this.stateTransition(RegistererState.Terminated); } } /** * Transition registration state. */ stateTransition(newState) { const invalidTransition = () => { throw new Error(`Invalid state transition from ${this._state} to ${newState}`); }; // Validate transition switch (this._state) { case RegistererState.Initial: if (newState !== RegistererState.Registered && newState !== RegistererState.Unregistered && newState !== RegistererState.Terminated) { invalidTransition(); } break; case RegistererState.Registered: if (newState !== RegistererState.Unregistered && newState !== RegistererState.Terminated) { invalidTransition(); } break; case RegistererState.Unregistered: if (newState !== RegistererState.Registered && newState !== RegistererState.Terminated) { invalidTransition(); } break; case RegistererState.Terminated: invalidTransition(); break; default: throw new Error("Unrecognized state."); } // Transition this._state = newState; this.logger.log(`Registration transitioned to state ${this._state}`); this._stateEventEmitter.emit("event", this._state); } /** True if the registerer is currently waiting for final response to a REGISTER request. */ get waiting() { return this._waiting; } /** Emits when the registerer waiting state changes. */ get waitingChange() { return makeEmitter(this._waitingEventEmitter); } /** * Toggle waiting. */ waitingToggle(waiting) { if (this._waiting === waiting) { throw new Error(`Invalid waiting transition from ${this._waiting} to ${waiting}`); } this._waiting = waiting; this.logger.log(`Waiting toggled to ${this._waiting}`); this._waitingEventEmitter.emit("event", this._waiting); } } /** Default registerer options. */ Registerer.defaultOptions = { expires: 50, extraContactHeaderParams: [], extraHeaders: [], logConfiguration: true, instanceId: "", params: {}, regId: 0, registrar: new URI("sip", "anonymous", "anonymous.invalid") }; /** * {@link Subscription} state. * @remarks * Valid state transitions: * ``` * 1. "initial" --> "notify-wait" --> "subscribed" --> "terminated" * 2. "initial" --> "notify-wait" --> "terminated" * 3. "initial" --> "terminated" * ``` * @public */ var SubscriptionState$1; (function(SubscriptionState) { SubscriptionState["Initial"] = "Initial"; SubscriptionState["NotifyWait"] = "NotifyWait"; SubscriptionState["Subscribed"] = "Subscribed"; SubscriptionState["Terminated"] = "Terminated"; })(SubscriptionState$1 || (SubscriptionState$1 = {})); var TransportStatus; (function(TransportStatus) { TransportStatus[TransportStatus["STATUS_CONNECTING"] = 0] = "STATUS_CONNECTING"; TransportStatus[TransportStatus["STATUS_OPEN"] = 1] = "STATUS_OPEN"; TransportStatus[TransportStatus["STATUS_CLOSING"] = 2] = "STATUS_CLOSING"; TransportStatus[TransportStatus["STATUS_CLOSED"] = 3] = "STATUS_CLOSED"; })(TransportStatus || (TransportStatus = {})); /** * Transport */ class Transport$1 extends Transport { constructor(logger, options) { super(logger); this.servers = []; this.reconnectionAttempts = 0; this.status = TransportStatus.STATUS_CONNECTING; // initialize configuration this.configuration = Object.assign(Object.assign({}, Transport$1.defaultOptions), options); // initialize WebSocket servers let urls = options.wsServers; if (typeof urls === "string") { urls = [urls]; } for (const url of urls) { const parsed = Grammar.parse(url, "absoluteURI"); if (parsed === -1) { this.logger.error(`Invalid WebSocket Server URL "${url}"`); throw new Error("Invalid WebSocket Server URL"); } if (["wss", "ws", "udp"].indexOf(parsed.scheme) < 0) { this.logger.error(`Invalid scheme in WebSocket Server URL "${url}"`); throw new Error("Invalid scheme in WebSocket Server URL"); } const scheme = parsed.scheme.toUpperCase(); const sipUri = ""; const wsUri = url; const weight = 0; const isError = false; this.servers.push({ scheme, sipUri, wsUri, weight, isError }); } if (this.servers.length === 0) { throw new Error("No WebSocket server."); } this.server = this.servers[0]; } /** * @returns {Boolean} */ isConnected() { return this.status === TransportStatus.STATUS_OPEN; } /** * Send a message. * @param message - Outgoing message. * @param options - Options bucket. */ sendPromise(message, options = {}) { if (this.ws === undefined) { this.onError("unable to send message - WebSocket undefined"); return Promise.reject(new Error("WebSocket undefined.")); } // FIXME: This check is likely not necessary as WebSocket.send() will // throw INVALID_STATE_ERR if the connection is not currently open // which could happen regardless of what we thing the state is. if (!this.statusAssert(TransportStatus.STATUS_OPEN, options.force)) { this.onError("unable to send message - WebSocket not open"); return Promise.reject(new Error("WebSocket not open.")); } if (this.configuration.traceSip === true) { this.logger.log("sending WebSocket message:\n\n" + message + "\n"); } // WebSocket.send() can throw. // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send try { this.ws.send(message); } catch (error) { if (error instanceof error) { Promise.reject(error); } return Promise.reject(new Error("Failed to send message.")); } return Promise.resolve({ msg: message }); } /** * Disconnect socket. */ disconnectPromise(options = {}) { if (this.disconnectionPromise) { // Already disconnecting. Just return this. return this.disconnectionPromise; } options.code = options.code || 1000; if (!this.statusTransition(TransportStatus.STATUS_CLOSING, options.force)) { if (this.status === TransportStatus.STATUS_CLOSED) { // Websocket is already closed return Promise.resolve({ overrideEvent: true }); } else if (this.connectionPromise) { // Websocket is connecting, cannot move to disconneting yet return this.connectionPromise.then(() => Promise.reject("The websocket did not disconnect")) .catch(() => Promise.resolve({ overrideEvent: true })); } else { // Cannot move to disconnecting, but not in connecting state. return Promise.reject("The websocket did not disconnect"); } } this.emit("disconnecting"); this.disconnectionPromise = new Promise((resolve, reject) => { this.disconnectDeferredResolve = resolve; if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = undefined; } if (this.ws) { this.stopSendingKeepAlives(); this.logger.log("closing WebSocket " + this.server.wsUri); this.ws.close(options.code, options.reason); } else { reject("Attempted to disconnect but the websocket doesn't exist"); } }); return this.disconnectionPromise; } /** * Connect socket. */ connectPromise(options = {}) { if (this.status === TransportStatus.STATUS_CLOSING && !options.force) { return Promise.reject("WebSocket " + this.server.wsUri + " is closing"); } if (this.connectionPromise) { return this.connectionPromise; } this.server = this.server || this.getNextWsServer(options.force); this.connectionPromise = new Promise((resolve, reject) => { if ((this.status === TransportStatus.STATUS_OPEN || this.status === TransportStatus.STATUS_CLOSING) && !options.force) { this.logger.warn("WebSocket " + this.server.wsUri + " is already connected"); reject("Failed status check - attempted to open a connection but already open/closing"); return; } this.connectDeferredResolve = resolve; this.connectDeferredReject = reject; this.status = TransportStatus.STATUS_CONNECTING; this.emit("connecting"); this.logger.log("connecting to WebSocket " + this.server.wsUri); this.disposeWs(); try { this.ws = new WebSocket(this.server.wsUri, "sip"); } catch (e) { this.ws = undefined; this.statusTransition(TransportStatus.STATUS_CLOSED, true); this.onError("error connecting to WebSocket " + this.server.wsUri + ":" + e); reject("Failed to create a websocket"); this.connectDeferredResolve = undefined; this.connectDeferredReject = undefined; return; } if (!this.ws) { reject("Unexpected instance websocket not set"); this.connectDeferredResolve = undefined; this.connectDeferredReject = undefined; return; } this.connectionTimeout = setTimeout(() => { this.statusTransition(TransportStatus.STATUS_CLOSED); this.logger.warn("took too long to connect - exceeded time set in configuration.connectionTimeout: " + this.configuration.connectionTimeout + "s"); this.emit("disconnected", { code: 1000 }); this.connectionPromise = undefined; reject("Connection timeout"); this.connectDeferredResolve = undefined; this.connectDeferredReject = undefined; const ws = this.ws; this.disposeWs(); if (ws) { ws.close(1000); } }, this.configuration.connectionTimeout * 1000); this.boundOnOpen = this.onOpen.bind(this); this.boundOnMessage = this.onMessage.bind(this); this.boundOnClose = this.onClose.bind(this); this.boundOnError = this.onWebsocketError.bind(this); this.ws.addEventListener("open", this.boundOnOpen); this.ws.addEventListener("message", this.boundOnMessage); this.ws.addEventListener("close", this.boundOnClose); this.ws.addEventListener("error", this.boundOnError); }); return this.connectionPromise; } /** * @event * @param {event} e */ onMessage(e) { const data = e.data; let finishedData; // CRLF Keep Alive response from server. Clear our keep alive timeout. if (/^(\r\n)+$/.test(data)) { this.clearKeepAliveTimeout(); if (this.configuration.traceSip === true) { this.logger.log("received WebSocket message with CRLF Keep Alive response"); } return; } else if (!data) { this.logger.warn("received empty message, message discarded"); return; } else if (typeof data !== "string") { // WebSocket binary message. try { // the UInt8Data was here prior to types, and doesn't check finishedData = String.fromCharCode.apply(null, new Uint8Array(data)); } catch (err) { this.logger.warn("received WebSocket binary message failed to be converted into string, message discarded"); return; } if (this.configuration.traceSip === true) { this.logger.log("received WebSocket binary message:\n\n" + data + "\n"); } } else { // WebSocket text message. if (this.configuration.traceSip === true) { this.logger.log("received WebSocket text message:\n\n" + data + "\n"); } finishedData = data; } this.emit("message", finishedData); } // Transport Event Handlers /** * @event * @param {event} e */ onOpen() { if (this.status === TransportStatus.STATUS_CLOSED) { // Indicated that the transport thinks the ws is dead already const ws = this.ws; this.disposeWs(); if (ws) { ws.close(1000); } return; } this.statusTransition(TransportStatus.STATUS_OPEN, true); this.emit("connected"); if (this.connectionTimeout) { clearTimeout(this.connectionTimeout); this.connectionTimeout = undefined; } this.logger.log("WebSocket " + this.server.wsUri + " connected"); // Clear reconnectTimer since we are not disconnected if (this.reconnectTimer !== undefined) { clearTimeout(this.reconnectTimer); this.reconnectTimer = undefined; } // Reset reconnectionAttempts this.reconnectionAttempts = 0; // Reset disconnection promise so we can disconnect from a fresh state this.disconnectionPromise = undefined; this.disconnectDeferredResolve = undefined; // Start sending keep-alives this.startSendingKeepAlives(); if (this.connectDeferredResolve) { this.connectDeferredResolve({ overrideEvent: true }); this.connectDeferredResolve = undefined; this.connectDeferredReject = undefined; } else { this.logger.warn("Unexpected websocket.onOpen with no connectDeferredResolve"); } } /** * @event * @param {event} e */ onClose(e) { this.logger.log("WebSocket disconnected (code: " + e.code + (e.reason ? "| reason: " + e.reason : "") + ")"); if (this.status !== TransportStatus.STATUS_CLOSING) { this.logger.warn("WebSocket closed without SIP.js requesting it"); this.emit("transportError"); } this.stopSendingKeepAlives(); // Clean up connection variables so we can connect again from a fresh state if (this.connectionTimeout) { clearTimeout(this.connectionTimeout); } if (this.connectDeferredReject) { this.connectDeferredReject("Websocket Closed"); } this.connectionTimeout = undefined; this.connectionPromise = undefined; this.connectDeferredResolve = undefined; this.connectDeferredReject = undefined; // Check whether the user requested to close. if (this.disconnectDeferredResolve) { this.disconnectDeferredResolve({ overrideEvent: true }); this.statusTransition(TransportStatus.STATUS_CLOSED); this.disconnectDeferredResolve = undefined; return; } this.statusTransition(TransportStatus.STATUS_CLOSED, true); this.emit("disconnected", { code: e.code, reason: e.reason }); this.disposeWs(); this.reconnect(); } /** * Removes event listeners and clears the instance ws */ disposeWs() { if (this.ws) { this.ws.removeEventListener("open", this.boundOnOpen); this.ws.removeEventListener("message", this.boundOnMessage); this.ws.removeEventListener("close", this.boundOnClose); this.ws.removeEventListener("error", this.boundOnError); this.ws = undefined; } } /** * @event * @param {string} e */ onError(e) { this.logger.warn("Transport error: " + e); this.emit("transportError"); } /** * @event * @private */ onWebsocketError() { this.onError("The Websocket had an error"); } /** * Reconnection attempt logic. */ reconnect() { if (this.reconnectionAttempts > 0) { this.logger.log("Reconnection attempt " + this.reconnectionAttempts + " failed"); } if (this.noAvailableServers()) { this.logger.warn("attempted to get next ws server but there are no available ws servers left"); this.logger.warn("no available ws servers left - going to closed state"); this.statusTransition(TransportStatus.STATUS_CLOSED, true); this.emit("closed"); this.resetServerErrorStatus(); return; } if (this.isConnected()) { this.logger.warn("attempted to reconnect while connected - forcing disconnect"); this.disconnect({ force: true }); } this.reconnectionAttempts += 1; if (this.reconnectionAttempts > this.configuration.maxReconnectionAttempts) { this.logger.warn("maximum reconnection attempts for WebSocket " + this.server.wsUri); this.logger.log("transport " + this.server.wsUri + " failed | connection state set to 'error'"); this.server.isError = true; this.emit("transportError"); if (!this.noAvailableServers()) { this.server = this.getNextWsServer(); } // When there are no available servers, the reconnect function ends on the next recursive call // after checking for no available servers again. this.reconnectionAttempts = 0; this.reconnect(); } else { this.logger.log("trying to reconnect to WebSocket " + this.server.wsUri + " (reconnection attempt " + this.reconnectionAttempts + ")"); this.reconnectTimer = setTimeout(() => { this.connect(); this.reconnectTimer = undefined; }, (this.reconnectionAttempts === 1) ? 0 : this.configuration.reconnectionTimeout * 1000); } } /** * Resets the error state of all servers in the configuration */ resetServerErrorStatus() { for (const websocket of this.servers) { websocket.isError = false; } } /** * Retrieve the next server to which connect. * @param {Boolean} force allows bypass of server error status checking * @returns {Object} WsServer */ getNextWsServer(force = false) { if (this.noAvailableServers()) { this.logger.warn("attempted to get next ws server but there are no available ws servers left"); throw new Error("Attempted to get next ws server, but there are no available ws servers left."); } // Order servers by weight let candidates = []; for (const server of this.servers) { if (server.isError && !force) { continue; } else if (candidates.length === 0) { candidates.push(server); } else if (server.weight > candidates[0].weight) { candidates = [server]; } else if (server.weight === candidates[0].weight) { candidates.push(server); } } const idx = Math.floor(Math.random() * candidates.length); return candidates[idx]; } /** * Checks all configuration servers, returns true if all of them have isError: true and false otherwise * @returns {Boolean} */ noAvailableServers() { for (const server of this.servers) { if (!server.isError) { return false; } } return true; } // ============================== // KeepAlive Stuff // ============================== /** * Send a keep-alive (a double-CRLF sequence). * @returns {Boolean} */ sendKeepAlive() { if (this.keepAliveDebounceTimeout) { // We already have an outstanding keep alive, do not send another. return; } this.keepAliveDebounceTimeout = setTimeout(() => { this.emit("keepAliveDebounceTimeout"); this.clearKeepAliveTimeout(); }, this.configuration.keepAliveDebounce * 1000); return this.send("\r\n\r\n"); } clearKeepAliveTimeout() { if (this.keepAliveDebounceTimeout) { clearTimeout(this.keepAliveDebounceTimeout); } this.keepAliveDebounceTimeout = undefined; } /** * Start sending keep-alives. */ startSendingKeepAlives() { // Compute an amount of time in seconds to wait before sending another keep-alive. const computeKeepAliveTimeout = (upperBound) => { const lowerBound = upperBound * 0.8; return 1000 * (Math.random() * (upperBound - lowerBound) + lowerBound); }; if (this.configuration.keepAliveInterval && !this.keepAliveInterval) { this.keepAliveInterval = setInterval(() => { this.sendKeepAlive(); this.startSendingKeepAlives(); }, computeKeepAliveTimeout(this.configuration.keepAliveInterval)); } } /** * Stop sending keep-alives. */ stopSendingKeepAlives() { if (this.keepAliveInterval) { clearInterval(this.keepAliveInterval); } if (this.keepAliveDebounceTimeout) { clearTimeout(this.keepAliveDebounceTimeout); } this.keepAliveInterval = undefined; this.keepAliveDebounceTimeout = undefined; } // ============================== // Status Stuff // ============================== /** * Checks given status against instance current status. Returns true if they match * @param {Number} status * @param {Boolean} [force] * @returns {Boolean} */ statusAssert(status, force) { if (status === this.status) { return true; } else { if (force) { this.logger.warn("Attempted to assert " + Object.keys(TransportStatus)[this.status] + " as " + Object.keys(TransportStatus)[status] + "- continuing with option: 'force'"); return true; } else { this.logger.warn("Tried to assert " + Object.keys(TransportStatus)[status] + " but is currently " + Object.keys(TransportStatus)[this.status]); return false; } } } /** * Transitions the status. Checks for legal transition via assertion beforehand * @param {Number} status * @param {Boolean} [force] * @returns {Boolean} */ statusTransition(status, force = false) { this.logger.log("Attempting to transition status from " + Object.keys(TransportStatus)[this.status] + " to " + Object.keys(TransportStatus)[status]); if ((status === TransportStatus.STATUS_CONNECTING && this.statusAssert(TransportStatus.STATUS_CLOSED, force)) || (status === TransportStatus.STATUS_OPEN && this.statusAssert(TransportStatus.STATUS_CONNECTING, force)) || (status === TransportStatus.STATUS_CLOSING && this.statusAssert(TransportStatus.STATUS_OPEN, force)) || (status === TransportStatus.STATUS_CLOSED)) { this.status = status; return true; } else { this.logger.warn("Status transition failed - result: no-op - reason:" + " either gave an nonexistent status or attempted illegal transition"); return false; } } } Transport$1.C = TransportStatus; Transport$1.defaultOptions = { wsServers: [], connectionTimeout: 5, maxReconnectionAttempts: 30, reconnectionTimeout: 4, keepAliveInterval: 0, keepAliveDebounce: 10, traceSip: true }; /** * {@link UserAgent} state. * @remarks * Valid state transitions: * ``` * 1. "initial" --> "starting" * 2. "starting" --> "started" * 3. "starting" --> "stopped" * 4. "started" --> "stopping" * 5. "started" --> "stopped" * 6. "stopped" --> "starting" * ``` * @public */ var UserAgentState; (function(UserAgentState) { UserAgentState["Initial"] = "Initial"; UserAgentState["Starting"] = "Starting"; UserAgentState["Started"] = "Started"; UserAgentState["Stopping"] = "Stopping"; UserAgentState["Stopped"] = "Stopped"; })(UserAgentState || (UserAgentState = {})); /** * Deprecated * @internal */ var _UAStatus; (function(_UAStatus) { _UAStatus[_UAStatus["STATUS_INIT"] = 0] = "STATUS_INIT"; _UAStatus[_UAStatus["STATUS_STARTING"] = 1] = "STATUS_STARTING"; _UAStatus[_UAStatus["STATUS_READY"] = 2] = "STATUS_READY"; _UAStatus[_UAStatus["STATUS_USER_CLOSED"] = 3] = "STATUS_USER_CLOSED"; _UAStatus[_UAStatus["STATUS_NOT_READY"] = 4] = "STATUS_NOT_READY"; })(_UAStatus || (_UAStatus = {})); /** * A user agent sends and receives requests using a `Transport`. * * @remarks * A user agent (UA) is associated with a user via the user's SIP address of record (AOR) * and acts on behalf of that user to send and receive SIP requests. The user agent can * register to receive incoming requests, as well as create and send outbound messages. * The user agent also maintains the Transport over which its signaling travels. * * @public */ class UserAgent { /** * Constructs a new instance of the `UserAgent` class. * @param options - Options bucket. See {@link UserAgentOptions} for details. */ constructor(options = {}) { /** @internal */ this.data = {}; /** @internal */ this.applicants = {}; /** @internal */ this.publishers = {}; /** @internal */ this.registerers = {}; /** @internal */ this.sessions = {}; /** @internal */ this.subscriptions = {}; /** LoggerFactory. */ this.loggerFactory = new LoggerFactory(); this._state = UserAgentState.Initial; this._stateEventEmitter = new EventEmitter(); /** @internal */ this.status = _UAStatus.STATUS_INIT; /** Unload listener. */ this.unloadListener = (() => { this.stop(); }); // initialize delegate this.delegate = options.delegate; // initialize configuration this.options = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, UserAgent.defaultOptions), { sipjsId: createRandomToken(5) }), { uri: new URI("sip", "anonymous." + createRandomToken(6), "anonymous.invalid") }), { viaHost: createRandomToken(12) + ".invalid" }), UserAgent.stripUndefinedProperties(options)); // viaHost is hack if (this.options.hackIpInContact) { if (typeof this.options.hackIpInContact === "boolean" && this.options.hackIpInContact) { const from = 1; const to = 254; const octet = Math.floor(Math.random() * (to - from + 1) + from); // random Test-Net IP (http://tools.ietf.org/html/rfc5735) this.options.viaHost = "192.0.2." + octet; } else if (this.options.hackIpInContact) { this.options.viaHost = (this.options.hackIpInContact.toString()); } } // initialize logger & logger factory this.logger = this.loggerFactory.getLogger("sip.UserAgent"); this.loggerFactory.builtinEnabled = this.options.logBuiltinEnabled; this.loggerFactory.connector = this.options.logConnector; switch (this.options.logLevel) { case "error": this.loggerFactory.level = Levels.error; break; case "warn": this.loggerFactory.level = Levels.warn; break; case "log": this.loggerFactory.level = Levels.log; break; case "debug": this.loggerFactory.level = Levels.debug; break; default: break; } if (this.options.logConfiguration) { this.logger.log("Configuration:"); Object.keys(this.options).forEach((key) => { const value = this.options[key]; switch (key) { case "uri": case "sessionDescriptionHandlerFactory": this.logger.log("· " + key + ": " + value); break; case "authorizationPassword": this.logger.log("· " + key + ": " + "NOT SHOWN"); break; case "transportConstructor": this.logger.log("· " + key + ": " + value.name); break; default: this.logger.log("· " + key + ": " + JSON.stringify(value)); } }); } // initialize transport this.transport = new this.options.transportConstructor(this.getLogger("sip.Transport"), this.options.transportOptions); // initialize contact this.contact = this.initContact(); // initialize core this.userAgentCore = this.initCore(); if (this.options.autoStart) { this.start(); } } /** * Create a URI instance from a string. * @param uri - The string to parse. * * @example * ```ts * const uri = UserAgent.makeURI("sip:edgar@example.com"); * ``` */ static makeURI(uri) { return Grammar.URIParse(uri); } /** * Strip properties with undefined values from options. * This is a work around while waiting for missing vs undefined to be addressed (or not)... * https://github.com/Microsoft/TypeScript/issues/13195 * @param options - Options to reduce */ static stripUndefinedProperties(options) { return Object.keys(options).reduce((object, key) => { if (options[key] !== undefined) { object[key] = options[key]; } return object; }, {}); } /** * User agent configuration. */ get configuration() { return this.options; } /** * Connect user agent to network transport. * @remarks * Connect to the WS server if status = STATUS_INIT. * Resume UA after being closed. */ start() { this.logger.log("user requested startup..."); if (this.status === _UAStatus.STATUS_INIT) { this.status = _UAStatus.STATUS_STARTING; this.setTransportListeners(); return this.transport.connect(); } else if (this.status === _UAStatus.STATUS_USER_CLOSED || this.status === _UAStatus.STATUS_NOT_READY) { //make reconnect sucess this.logger.log("resuming"); this.status = _UAStatus.STATUS_READY; return this.transport.connect(); } else if (this.status === _UAStatus.STATUS_STARTING) { this.logger.log("UA is in STARTING status, not opening new connection"); } else if (this.status === _UAStatus.STATUS_READY) { this.logger.log("UA is in READY status, not resuming"); } else { this.logger.error("Connection is down. Auto-Recovery system is trying to connect"); } if (this.options.autoStop) { // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps const googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; if (typeof window !== "undefined" && typeof window.addEventListener === "function" && !googleChromePackagedApp) { window.addEventListener("unload", this.unloadListener); } } return Promise.resolve(); } /** * Gracefully close. * Gracefully disconnect from network transport. * @remarks * Unregisters and terminates active sessions/subscriptions. */ async stop() { this.logger.log(`Stopping user agent ${this.configuration.uri}...`); if (this.status === _UAStatus.STATUS_USER_CLOSED) { this.logger.warn("UA already closed"); } // Dispose of Registerers for (const id in this.registerers) { if (this.registerers[id]) { await this.registerers[id].dispose(); } } // End every Session for (const id in this.sessions) { if (this.sessions[id]) { this.logger.log("closing session " + id); const session = this.sessions[id]; switch (session.state) { case SessionState$1.Initial: case SessionState$1.Establishing: if (session instanceof Invitation) { session.reject(); } if (session instanceof Inviter) { session.cancel(); } break; case SessionState$1.Established: session._bye(); break; case SessionState$1.Terminating: case SessionState$1.Terminated: default: break; } } } // Run unsubscribe on every Subscription for (const subscription in this.subscriptions) { if (this.subscriptions[subscription]) { this.logger.log("unsubscribe " + subscription); this.subscriptions[subscription].unsubscribe(); } } // Run close on every Publisher for (const publisher in this.publishers) { if (this.publishers[publisher]) { this.logger.log("unpublish " + publisher); this.publishers[publisher]._close(); } } // Run close on every applicant for (const applicant in this.applicants) { if (this.applicants[applicant]) { this.applicants[applicant]._close(); } } this.status = _UAStatus.STATUS_USER_CLOSED; // Disconnect the transport and reset user agent core this.transport.disconnect(); this.userAgentCore.reset(); if (this.options.autoStop) { // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps const googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; if (typeof window !== "undefined" && window.removeEventListener && !googleChromePackagedApp) { window.removeEventListener("unload", this.unloadListener); } } return Promise.resolve(); } /** @internal */ findSession(request) { return this.sessions[request.callId + request.fromTag] || this.sessions[request.callId + request.toTag] || undefined; } /** @internal */ getLogger(category, label) { return this.loggerFactory.getLogger(category, label); } /** @internal */ getLoggerFactory() { return this.loggerFactory; } /** @internal */ getSupportedResponseOptions() { let optionTags = []; if (this.contact.pubGruu || this.contact.tempGruu) { optionTags.push("gruu"); } if (this.options.sipExtension100rel === SIPExtension.Supported) { optionTags.push("100rel"); } if (this.options.sipExtensionReplaces === SIPExtension.Supported) { optionTags.push("replaces"); } optionTags.push("outbound"); optionTags = optionTags.concat(this.options.sipExtensionExtraSupported || []); const allowUnregistered = this.options.hackAllowUnregisteredOptionTags || false; const optionTagSet = {}; optionTags = optionTags.filter((optionTag) => { const registered = UserAgentRegisteredOptionTags[optionTag]; const unique = !optionTagSet[optionTag]; optionTagSet[optionTag] = true; return (registered || allowUnregistered) && unique; }); return optionTags; } /** @internal */ makeInviter(targetURI, options) { return new Inviter(this, targetURI, options); } // ============================== // Event Handlers // ============================== onTransportError() { if (this.status === _UAStatus.STATUS_USER_CLOSED) { return; } this.status = _UAStatus.STATUS_NOT_READY; } /** * Helper function. Sets transport listeners */ setTransportListeners() { this.transport.on("connected", () => this.onTransportConnected()); this.transport.on("message", (message) => this.onTransportReceiveMsg(message)); this.transport.on("transportError", () => this.onTransportError()); } /** * Transport connection event. */ onTransportConnected() { console.warn("onTransportConnected2"); for (const id in this.registerers) { if (this.registerers[id]) { this.registerers[id].register(); } } // for (const session in this.sessions) { // if (Object.prototype.hasOwnProperty.call(this.sessions, session)) { // const element = this.sessions[session]; // element.invite(); // } // } // if (this.configuration.register) { // In an effor to maintain behavior from when we "initialized" an // authentication factory, this is in a Promise.then // Promise.resolve().then(() => this.registerers[0].register()); // } } /** * Handle SIP message received from the transport. * @param messageString - The message. */ onTransportReceiveMsg(messageString) { const message = Parser.parseMessage(messageString, this.getLogger("sip.parser")); if (!message) { this.logger.warn("Failed to parse incoming message. Dropping."); return; } if (this.status === _UAStatus.STATUS_USER_CLOSED && message instanceof IncomingRequestMessage) { this.logger.warn(`Received ${message.method} request in state USER_CLOSED. Dropping.`); return; } // A valid SIP request formulated by a UAC MUST, at a minimum, contain // the following header fields: To, From, CSeq, Call-ID, Max-Forwards, // and Via; all of these header fields are mandatory in all SIP // requests. // https://tools.ietf.org/html/rfc3261#section-8.1.1 const hasMinimumHeaders = () => { const mandatoryHeaders = ["from", "to", "call_id", "cseq", "via"]; for (const header of mandatoryHeaders) { if (!message.hasHeader(header)) { this.logger.warn(`Missing mandatory header field : ${header}.`); return false; } } return true; }; // Request Checks if (message instanceof IncomingRequestMessage) { // This is port of SanityCheck.minimumHeaders(). if (!hasMinimumHeaders()) { this.logger.warn(`Request missing mandatory header field. Dropping.`); return; } // FIXME: This is non-standard and should be a configruable behavior (desirable regardless). // Custom SIP.js check to reject request from ourself (this instance of SIP.js). // This is port of SanityCheck.rfc3261_16_3_4(). if (!message.toTag && message.callId.substr(0, 5) === this.options.sipjsId) { this.userAgentCore.replyStateless(message, { statusCode: 482 }); return; } // FIXME: This should be Transport check before we get here (Section 18). // Custom SIP.js check to reject requests if body length wrong. // This is port of SanityCheck.rfc3261_18_3_request(). const len = str_utf8_length(message.body); const contentLength = message.getHeader("content-length"); if (contentLength && len < Number(contentLength)) { this.userAgentCore.replyStateless(message, { statusCode: 400 }); return; } } // Reponse Checks if (message instanceof IncomingResponseMessage) { // This is port of SanityCheck.minimumHeaders(). if (!hasMinimumHeaders()) { this.logger.warn(`Response missing mandatory header field. Dropping.`); return; } // Custom SIP.js check to drop responses if multiple Via headers. // This is port of SanityCheck.rfc3261_8_1_3_3(). if (message.getHeaders("via").length > 1) { this.logger.warn("More than one Via header field present in the response. Dropping."); return; } // FIXME: This should be Transport check before we get here (Section 18). // Custom SIP.js check to drop responses if bad Via header. // This is port of SanityCheck.rfc3261_18_1_2(). if (message.via.host !== this.options.viaHost || message.via.port !== undefined) { this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping."); return; } // FIXME: This should be Transport check before we get here (Section 18). // Custom SIP.js check to reject requests if body length wrong. // This is port of SanityCheck.rfc3261_18_3_response(). const len = str_utf8_length(message.body); const contentLength = message.getHeader("content-length"); if (contentLength && len < Number(contentLength)) { this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping."); return; } } // Handle Request if (message instanceof IncomingRequestMessage) { this.userAgentCore.receiveIncomingRequestFromTransport(message); return; } // Handle Response if (message instanceof IncomingResponseMessage) { this.userAgentCore.receiveIncomingResponseFromTransport(message); return; } throw new Error("Invalid message type."); } initContact() { const contactName = createRandomToken(8); // FIXME: should be configurable const contactTransport = this.options.hackWssInTransport ? "wss" : "ws"; // FIXME: clearly broken for non ws transports const contact = { pubGruu: undefined, tempGruu: undefined, uri: new URI("sip", contactName, this.options.viaHost, undefined, { transport: contactTransport }), toString: (contactToStringOptions = {}) => { const anonymous = contactToStringOptions.anonymous || false; const outbound = contactToStringOptions.outbound || false; let contactString = "<"; if (anonymous) { contactString += this.contact.tempGruu || `sip:anonymous@anonymous.invalid;transport=${contactTransport}`; } else { contactString += this.contact.pubGruu || this.contact.uri; } if (outbound) { contactString += ";ob"; } contactString += ">"; return contactString; } }; return contact; } initCore() { // supported options let supportedOptionTags = []; supportedOptionTags.push("outbound"); // TODO: is this really supported? if (this.options.sipExtension100rel === SIPExtension.Supported) { supportedOptionTags.push("100rel"); } if (this.options.sipExtensionReplaces === SIPExtension.Supported) { supportedOptionTags.push("replaces"); } if (this.options.sipExtensionExtraSupported) { supportedOptionTags.push(...this.options.sipExtensionExtraSupported); } if (!this.options.hackAllowUnregisteredOptionTags) { supportedOptionTags = supportedOptionTags.filter((optionTag) => UserAgentRegisteredOptionTags[optionTag]); } supportedOptionTags = Array.from(new Set(supportedOptionTags)); // array of unique values // FIXME: TODO: This was ported, but this is and was just plain broken. const supportedOptionTagsResponse = supportedOptionTags.slice(); if (this.contact.pubGruu || this.contact.tempGruu) { supportedOptionTagsResponse.push("gruu"); } // core configuration const userAgentCoreConfiguration = { aor: this.options.uri, contact: this.contact, displayName: this.options.displayName, loggerFactory: this.loggerFactory, hackViaTcp: this.options.hackViaTcp, routeSet: this.options.usePreloadedRoute && this.transport.server && this.transport.server.sipUri ? [this.transport.server.sipUri] : [], supportedOptionTags, supportedOptionTagsResponse, sipjsId: this.options.sipjsId, userAgentHeaderFieldValue: this.options.userAgentString, viaForceRport: this.options.forceRport, viaHost: this.options.viaHost, authenticationFactory: () => { const username = this.options.authorizationUsername ? this.options.authorizationUsername : this.options.uri.user; // if authorization username not provided, use uri user as username const password = this.options.authorizationPassword ? this.options.authorizationPassword : undefined; return new DigestAuthentication(this.getLoggerFactory(), username, password); }, transportAccessor: () => this.transport }; const userAgentCoreDelegate = { onInvite: (incomingInviteRequest) => { const invitation = new Invitation(this, incomingInviteRequest); incomingInviteRequest.delegate = { onCancel: (cancel) => { invitation._onCancel(cancel); }, onTransportError: (error) => { // A server transaction MUST NOT discard transaction state based only on // encountering a non-recoverable transport error when sending a // response. Instead, the associated INVITE server transaction state // machine MUST remain in its current state. (Timers will eventually // cause it to transition to the "Terminated" state). // https://tools.ietf.org/html/rfc6026#section-7.1 // As noted in the comment above, we are to leaving it to the transaction // timers to evenutally cause the transaction to sort itself out in the case // of a transport failure in an invite server transaction. This delegate method // is here simply here for completeness and to make it clear that it provides // nothing more than informational hook into the core. That is, if you think // you should be trying to deal with a transport error here, you are likely wrong. this.logger.error("A transport error has occured while handling an incoming INVITE request."); } }; // FIXME: Ported - 100 Trying send should be configurable. // Only required if TU will not respond in 200ms. // https://tools.ietf.org/html/rfc3261#section-17.2.1 incomingInviteRequest.trying(); // The Replaces header contains information used to match an existing // SIP dialog (call-id, to-tag, and from-tag). Upon receiving an INVITE // with a Replaces header, the User Agent (UA) attempts to match this // information with a confirmed or early dialog. // https://tools.ietf.org/html/rfc3891#section-3 if (this.options.sipExtensionReplaces !== SIPExtension.Unsupported) { const message = incomingInviteRequest.message; const replaces = message.parseHeader("replaces"); if (replaces) { const callId = replaces.call_id; if (typeof callId !== "string") { throw new Error("Type of call id is not string"); } const toTag = replaces.replaces_to_tag; if (typeof toTag !== "string") { throw new Error("Type of to tag is not string"); } const fromTag = replaces.replaces_from_tag; if (typeof fromTag !== "string") { throw new Error("type of from tag is not string"); } const targetDialogId = callId + toTag + fromTag; const targetDialog = this.userAgentCore.dialogs.get(targetDialogId); // If no match is found, the UAS rejects the INVITE and returns a 481 // Call/Transaction Does Not Exist response. Likewise, if the Replaces // header field matches a dialog which was not created with an INVITE, // the UAS MUST reject the request with a 481 response. // https://tools.ietf.org/html/rfc3891#section-3 if (!targetDialog) { invitation.reject({ statusCode: 481 }); return; } // If the Replaces header field matches a confirmed dialog, it checks // for the presence of the "early-only" flag in the Replaces header // field. (This flag allows the UAC to prevent a potentially // undesirable race condition described in Section 7.1.) If the flag is // present, the UA rejects the request with a 486 Busy response. // https://tools.ietf.org/html/rfc3891#section-3 if (!targetDialog.early && replaces.early_only === true) { invitation.reject({ statusCode: 486 }); return; } // Provide a handle on the session being replaced. const targetSession = this.sessions[callId + fromTag] || this.sessions[callId + toTag] || undefined; if (!targetSession) { throw new Error("Session does not exist."); } invitation.replacee = targetSession; } } // A common scenario occurs when the callee is currently not willing or // able to take additional calls at this end system. A 486 (Busy Here) // SHOULD be returned in such a scenario. // https://tools.ietf.org/html/rfc3261#section-13.3.1.3 if (!this.delegate || !this.delegate.onInvite) { invitation.reject({ statusCode: 486 }); return; } // Delegate invitation handling. if (!invitation.autoSendAnInitialProvisionalResponse) { this.delegate.onInvite(invitation); } else { const onInvite = this.delegate.onInvite; invitation.progress() .then(() => onInvite(invitation)); } }, onMessage: (incomingMessageRequest) => { if (this.delegate && this.delegate.onMessage) { const message = new Message(incomingMessageRequest); this.delegate.onMessage(message); } else { // Accept the MESSAGE request, but do nothing with it. incomingMessageRequest.accept(); } }, onNotify: (incomingNotifyRequest) => { // NOTIFY requests are sent to inform subscribers of changes in state to // which the subscriber has a subscription. Subscriptions are created // using the SUBSCRIBE method. In legacy implementations, it is // possible that other means of subscription creation have been used. // However, this specification does not allow the creation of // subscriptions except through SUBSCRIBE requests and (for backwards- // compatibility) REFER requests [RFC3515]. // https://tools.ietf.org/html/rfc6665#section-3.2 if (this.delegate && this.delegate.onNotify) { const notification = new Notification(incomingNotifyRequest); this.delegate.onNotify(notification); } else { // Per the above which sbsoletes https://tools.ietf.org/html/rfc3265, // the use of out of dialog NOTIFY is obsolete, but... if (this.options.allowLegacyNotifications) { incomingNotifyRequest.accept(); // Accept the NOTIFY request, but do nothing with it. } else { incomingNotifyRequest.reject({ statusCode: 481 }); } } }, onRefer: (incomingReferRequest) => { this.logger.log("Received an out of dialog refer"); if (!this.options.allowOutOfDialogRefers) { incomingReferRequest.reject({ statusCode: 405 }); } this.logger.log("Allow out of dialog refers is enabled on the UA"); // const referContext = new ReferServerContext(this, incomingReferRequest); // if (this.listeners("outOfDialogReferRequested").length) { // this.emit("outOfDialogReferRequested", referContext); // } else { // this.logger.log( // "No outOfDialogReferRequest listeners, automatically accepting and following the out of dialog refer" // ); // referContext.accept({ followRefer: true }); // } // if (this.delegate && this.delegate.onRefer) { // this.delegate.onRefer(incomingReferRequest); // } }, onRegister: (incomingRegisterRequest) => { // TOOD: this.delegate.onRegister(...) if (this.delegate && this.delegate.onRegisterRequest) { this.delegate.onRegisterRequest(incomingRegisterRequest); } }, onSubscribe: (incomingSubscribeRequest) => { // TOOD: this.delegate.onSubscribe(...) if (this.delegate && this.delegate.onSubscribeRequest) { this.delegate.onSubscribeRequest(incomingSubscribeRequest); } } }; return new UserAgentCore(userAgentCoreConfiguration, userAgentCoreDelegate); } } /** Default user agent options. */ UserAgent.defaultOptions = { allowLegacyNotifications: false, allowOutOfDialogRefers: false, authorizationPassword: "", authorizationUsername: "", autoStart: false, autoStop: true, delegate: {}, displayName: "", forceRport: false, hackAllowUnregisteredOptionTags: false, hackIpInContact: false, hackViaTcp: false, hackWssInTransport: false, logBuiltinEnabled: true, logConfiguration: true, logConnector: () => {}, logLevel: "log", noAnswerTimeout: 60, sessionDescriptionHandlerFactory: SessionDescriptionHandler.defaultFactory, sessionDescriptionHandlerFactoryOptions: {}, sipExtension100rel: SIPExtension.Unsupported, sipExtensionReplaces: SIPExtension.Unsupported, sipExtensionExtraSupported: [], sipjsId: "", transportConstructor: Transport$1, transportOptions: {}, uri: new URI("sip", "anonymous", "anonymous.invalid"), usePreloadedRoute: false, // userAgentString: "SIP.js/" + LIBRARY_VERSION, userAgentString: "xyplat", viaHost: "" }; /** * A Simple SIP User class. * @remarks * While this class is completely functional for simple use cases, it is not intended * to provide an interface which is suitable for most (must less all) applications. * While this class has many limitations (for example, it only handles a single concurrent session), * it is, however, intended to serve as a simple example of using the SIP.js API. */ class Sphone extends EventEmitter { // private calls: Array = []; /** * Constructs a new instance of the `SimpleUser` class. * @param webSocketServerURL - SIP WebSocket Server URL. * @param options - Options bucket. See {@link SimpleUserOptions} for details. */ constructor(webSocketServerURL, options = {}) { super(); this.registerer = undefined; // Delegate this.delegate = options.delegate; // Copy options this.options = Object.assign({}, options); // UserAgentOptions const userAgentOptions = Object.assign({}, options.userAgentOptions); // Transport if (!userAgentOptions.transportConstructor) { userAgentOptions.transportConstructor = Transport$1; } // TransportOptions if (!userAgentOptions.transportOptions) { userAgentOptions.transportOptions = { wsServers: webSocketServerURL }; } // URI if (!userAgentOptions.uri) { // If an AOR was provided, convert it to a URI if (options.aor) { const uri = UserAgent.makeURI(options.aor); if (!uri) { throw new Error(`Failed to create valid URI from ${options.aor}`); } userAgentOptions.uri = uri; } } // UserAgent this.userAgent = new UserAgent(userAgentOptions); // UserAgent's delegate this.userAgent.delegate = { // Handle incoming invitations onInvite: (invitation) => { this.logger.log(`[${this.id}] received INVITE`); invitation.setDelegate(this.delegate); // Guard against a pre-existing session. This implementation only supports one session at a time. // However an incoming INVITE request may be received at any time and/or while in the process // of sending an outgoing INVITE request. So we reject any incoming INVITE in those cases. // if (this.session) { // this.logger.warn(`[${this.id}] session already in progress, rejecting INVITE...`); // invitation.reject() // .then(() => { // this.logger.log(`[${this.id}] rejected INVITE`); // }) // .catch((error: Error) => { // this.logger.error(`[${this.id}] failed to reject INVITE`); // this.logger.error(error.toString()); // }); // return; // } // Use our configured constraints as options for any Inviter created as result of a REFER const referralInviterOptions = { sessionDescriptionHandlerOptions: { constraints: this.constraints } }; // Initialize our session // this.initSession(invitation, referralInviterOptions); // this.initSession1() // Delegate if (this.delegate && this.delegate.onCallReceived) { let cid = ""; let callType = ""; let caller = ""; let schedule = ""; if (invitation._ifcContent != null) { var ifccontent = invitation._ifcContent.split("."); cid = ifccontent[0]; callType = ifccontent[1]; caller = ifccontent[2]; if (ifccontent.length >= 4) { schedule = ifccontent[3]; } } this.delegate.onCallReceived(invitation.id, invitation.remoteIdentity.uri.user, cid, callType, caller); let para = new IncomingCallPara(); para.id = invitation.id; para.orgCaller = invitation.remoteIdentity.uri.user; para.cid = cid; para.calltype = callType; para.caller = caller; if (schedule == "1") { para.isScheduleConference = true; } // let isVideo; // if( invitation.remoteVideoTrack == undefined){ // isVideo = false; // }else{ // isVideo = true; // } para.isVideo = invitation.isVideo; para.invitation = invitation; // console.log("11111111"); this.emit(SphoneEventName.IncomingCall.toString(), para); // console.log("4444444444444444"); } else { this.logger.warn(`[${this.id}] no handler available, rejecting INVITE...`); invitation.reject() .then(() => { this.logger.log(`[${this.id}] rejected INVITE`); }) .catch((error) => { this.logger.error(`[${this.id}] failed to reject INVITE`); this.logger.error(error.toString()); }); } }, onMessage: (message) => { console.log("message.request.body"); message.accept() .then(() => { console.log(message.request.body); if (this.delegate && this.delegate.onMessageReceived) { this.delegate.onMessageReceived(message.request.body); } }); } }; // Use the SIP.js logger this.logger = this.userAgent.getLogger("sip.SimpleUser"); } /** Instance identifier. */ get id() { return (this.options.userAgentOptions && this.options.userAgentOptions.displayName) || "Anonymous"; } /** The local audio track, if available. */ // get localAudioTrack(): MediaStreamTrack | undefined { // return this.getSenderTrack("audio"); // } // /** The local video track, if available. */ // get localVideoTrack(): MediaStreamTrack | undefined { // return this.getSenderTrack("video"); // } // /** The remote audio track, if available. */ // get remoteAudioTrack(): MediaStreamTrack | undefined { // return this.getReceiverTrack("audio"); // } // /** The remote video track, if available. */ // get remoteVideoTrack(): MediaStreamTrack | undefined { // return this.getReceiverTrack("video"); // } /** * Connect. * Start the UserAgent's WebSocket Transport. */ connect() { this.logger.log(`[${this.id}] starting UserAgent...`); return this.userAgent.start(); } /** * Disconnect. * Stop the UserAgent's WebSocket Transport. */ disconnect() { this.logger.log(`[${this.id}] stopping UserAgent...`); return this.userAgent.stop(); } /** * Start receiving incoming calls. * Send a REGISTER request for the UserAgent's AOR. */ register(registererOptions, registererRegisterOptions) { this.logger.log(`[${this.id}] registering UserAgent...`); if (!this.registerer) { this.registerer = new Registerer(this.userAgent, registererOptions); this.registerer.stateChange.on((state) => { switch (state) { case RegistererState.Initial: break; case RegistererState.Registered: if (this.delegate && this.delegate.onRegistered) { this.delegate.onRegistered(); } break; case RegistererState.Unregistered: if (this.delegate && this.delegate.onUnregistered) { this.delegate.onUnregistered(); } break; case RegistererState.Terminated: this.registerer = undefined; alert("reg termianl"); break; default: throw new Error("Unknown registerer state."); } }); } return this.registerer.register(registererRegisterOptions) .then(() => { return; }); } /** * Stop receiving incoming calls. * Send an un-REGISTER request for the UserAgent's AOR. */ unregister(registererUnregisterOptions) { this.logger.log(`[${this.id}] unregistering UserAgent...`); if (!this.registerer) { return Promise.resolve(); } return this.registerer.unregister(registererUnregisterOptions) .then(() => { return; }); } /** * Make an outoing call. * Send an INVITE request to create a new Session. * @param destination - The target destination to call. A SIP address to send the INVITE to. */ // public call( // destination: string, // inviterOptions?: InviterOptions, // inviterInviteOptions?: InviterInviteOptions // ): Promise { // this.logger.log(`[${this.id}] beginning Session...`); // if (this.session) { // return Promise.reject(new Error("Session already exists.")); // } // const target = UserAgent.makeURI(destination); // if (!target) { // return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`)); // } // // Use our configured constraints as InviterOptions if none provided // if (!inviterOptions) { // inviterOptions = {}; // } // if (!inviterOptions.sessionDescriptionHandlerOptions) { // inviterOptions.sessionDescriptionHandlerOptions = {}; // } // if (!inviterOptions.sessionDescriptionHandlerOptions.constraints) { // inviterOptions.sessionDescriptionHandlerOptions.constraints = this.constraints; // } // // Create a new Inviter for the outgoing Session // const inviter = new Inviter(this.userAgent, target, inviterOptions); // // Send INVITE // return this.sendInvite(inviter, inviterOptions, inviterInviteOptions) // .then(() => { return; }); // } /** * Make an outoing call. * Send an INVITE request to create a new Session. * @param destination - The target destination to call. A SIP address to send the INVITE to. */ call1(destination, localVideoControl, remoteVideoControl, remoteAudioControl, inviterOptions, inviterInviteOptions) { this.logger.log(`[${this.id}] beginning Session...`); // if (this.session) { // return Promise.reject(new Error("Session already exists.")); // } const target = UserAgent.makeURI(destination); if (!target) { return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`)); } // Use our configured constraints as InviterOptions if none provided if (!inviterOptions) { inviterOptions = {}; } if (!inviterOptions.sessionDescriptionHandlerOptions) { inviterOptions.sessionDescriptionHandlerOptions = {}; } if (!inviterOptions.sessionDescriptionHandlerOptions.constraints) { inviterOptions.sessionDescriptionHandlerOptions.constraints = this.constraints; } // Create a new Inviter for the outgoing Session const inviter = new Inviter(this.userAgent, target, inviterOptions); // Send INVITE return this.sendInvite1(inviter, localVideoControl, remoteVideoControl, remoteAudioControl, inviterOptions, inviterInviteOptions) .then(() => { return; }); } /** * Hangup a call. * Send a BYE request to end the current Session. */ // public hangup(): Promise { // this.logger.log(`[${this.id}] ending Session...`); // if (!this.session) { // return Promise.reject(new Error("Session does not exist.")); // } // // Attempt to CANCEL outgoing sessions that are not yet established // if (this.session instanceof Inviter) { // if (this.session.state === SessionState.Initial || this.session.state === SessionState.Establishing) { // return this.session.cancel() // .then(() => { // this.logger.log(`[${this.id}] sent CANCEL`); // }); // } // } // // Send BYE // return new Byer(this.session).bye() // .then(() => { // this.logger.log(`[${this.id}] sent BYE`); // }); // } hangup1(callId) { this.logger.log(`[${this.id}] ending Session...`); // Attempt to CANCEL outgoing sessions that are not yet established var session = this.userAgent.sessions[callId]; if (session instanceof Inviter) { if (session.state === SessionState$1.Initial || session.state === SessionState$1.Establishing) { return session.cancel() .then(() => { this.logger.log(`[${this.id}] sent CANCEL`); }); } } else if (session instanceof Invitation) { if (session.state === SessionState$1.Initial || session.state === SessionState$1.Establishing) { return session.reject() .then(() => { this.logger.log(`[${this.id}] sent reject`); }); } } // Send BYE return new Byer(session).bye() .then(() => { this.logger.log(`[${this.id}] sent BYE`); }); } /** * Answer an incoming call. * Accept an incoming INVITE request creating a new Session. */ // public answer( // invitationAcceptOptions?: InvitationAcceptOptions // ): Promise { // this.logger.log(`[${this.id}] accepting Invitation...`); // if (!this.session) { // return Promise.reject(new Error("Session does not exist.")); // } // if (!(this.session instanceof Invitation)) { // return Promise.reject(new Error("Session not instance of Invitation.")); // } // // Use our configured constraints as InvitationAcceptOptions if none provided // if (!invitationAcceptOptions) { // invitationAcceptOptions = {}; // } // if (!invitationAcceptOptions.sessionDescriptionHandlerOptions) { // invitationAcceptOptions.sessionDescriptionHandlerOptions = {}; // } // if (!invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints) { // invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints = this.constraints; // } // return this.session.accept(invitationAcceptOptions); // } answerVideo(callId, videoControl) { const options = { sessionDescriptionHandlerOptions: { constraints: { audio: true, video: true } } }; this.answer1(callId, videoControl, null, options); } answerAudio(callId, control) { const options = { sessionDescriptionHandlerOptions: { constraints: { audio: true, video: false } } }; this.answer1(callId, control, null, options); } answer2(callId, control, isVideo, audioDeviceId = "", videoDeviceId = "", width = 0, height = 0, frameRate = 100, offerToReceiveVideoPara = true) { navigator.mediaDevices.enumerateDevices().then((devices) => { let videoCount = 0; let videoDeviceName = ""; devices.forEach(element => { if (element.kind == "videoinput") { videoCount++; videoDeviceName = element.label; } }); if ((videoCount == 0) || (videoCount == 1 && videoDeviceName == "sceen-capture-recorder")) { isVideo = false; } }); let videoContrains = null; if (!isVideo) { videoContrains = false; } else { if (videoDeviceId == "") { videoContrains = true; } else { if (width != 0 && height != 0) { videoContrains = { deviceId: { exact: videoDeviceId }, frameRate: frameRate, width: { exact: width }, height: { exact: height } }; } else { videoContrains = { deviceId: { exact: videoDeviceId }, frameRate: frameRate }; } } } const sdho = { RTCOfferOptions: { iceRestart: false, offerToReceiveAudio: true, offerToReceiveVideo: offerToReceiveVideoPara }, // constraints:{ audio: true, video: isVideo } constraints: { audio: (audioDeviceId == "") ? true : { deviceId: { exact: audioDeviceId } }, // audio: (audioDeviceId=="")? true :{deviceId: {exact: audioDeviceId}, sampleRate: 8000 }, // video: isVideo? ( (videoDeviceId=="")? true: {deviceId: {exact: videoDeviceId}}) : false video: videoContrains // video: {deviceId: {exact: "c8e23370c8134f8523ee727948873c7d2a1010b298aa62364ab1bf394fec4ecc"}} // video: {deviceId: {exact: "dcd54561d46e08074964cedf19fa4a0bfb0344532a34df3ef2db019ebac97f9d"}} } }; const options = { sessionDescriptionHandlerOptions: sdho }; return this.answer1(callId, control, null, options); } /** * Answer an incoming call. * Accept an incoming INVITE request creating a new Session. */ answer1(callId, videoControl, audioControl, invitationAcceptOptions) { this.logger.log(`[${this.id}] accepting Invitation...`); // if (!this.session) { // return Promise.reject(new Error("Session does not exist.")); // } // if (!(this.session instanceof Invitation)) { // return Promise.reject(new Error("Session not instance of Invitation.")); // } // Use our configured constraints as InvitationAcceptOptions if none provided if (!invitationAcceptOptions) { invitationAcceptOptions = {}; } if (!invitationAcceptOptions.sessionDescriptionHandlerOptions) { invitationAcceptOptions.sessionDescriptionHandlerOptions = {}; } if (!invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints) { invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints = this.constraints; } let findSession = this.userAgent.sessions[callId]; let findCall = findSession; findCall.setupCall(null, videoControl, this.logger, audioControl); return findCall.accept(invitationAcceptOptions); } /** * Decline an incoming call. * Reject an incoming INVITE request. */ // public decline(): Promise { // this.logger.log(`[${this.id}] rejecting Invitation...`); // if (!this.session) { // return Promise.reject(new Error("Session does not exist.")); // } // if (!(this.session instanceof Invitation)) { // return Promise.reject(new Error("Session not instance of Invitation.")); // } // return this.session.reject(); // } declineById(id) { this.logger.log(`[${this.id}] rejecting Invitation...`); let findSession = this.userAgent.sessions[id]; let findCall = findSession; return findCall.reject(); } /** * Hold call. * Send a re-INVITE with new offer indicating "hold". * See: https://tools.ietf.org/html/rfc6337 */ // public hold(): Promise { // this.logger.log(`[${this.id}] holding session...`); // if (!this.session) { // return Promise.reject(new Error("Session does not exist.")); // } // if (this.session.state !== SessionState.Established) { // return Promise.reject(new Error("Session is not established.")); // } // const sessionDescriptionHandler = this.session.sessionDescriptionHandler; // if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) { // throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); // } // const options: SessionInviteOptions = { // sessionDescriptionHandlerModifiers: [sessionDescriptionHandler.holdModifier] // }; // // Mute // this.mute(); // // Send re-INVITE // return this.session.invite(options) // .then(() => { return; }); // } hold1(callId) { this.logger.log(`[${this.id}] holding session...`); var session = this.userAgent.sessions[callId]; if (!session) { return Promise.reject(new Error("Session does not exist.")); } if (session.state !== SessionState$1.Established) { return Promise.reject(new Error("Session is not established.")); } const sessionDescriptionHandler = session.sessionDescriptionHandler; if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) { throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); } const options = { sessionDescriptionHandlerModifiers: [sessionDescriptionHandler.holdModifier] }; // Mute this.mute(callId); // Send re-INVITE return session.invite(options) .then(() => { return; }); } /** * Unhold call. * Send a re-INVITE with new offer indicating "unhold". * See: https://tools.ietf.org/html/rfc6337 */ // public unhold(): Promise { // this.logger.log(`[${this.id}] unholding session...`); // if (!this.session) { // return Promise.reject(new Error("Session does not exist.")); // } // if (this.session.state !== SessionState.Established) { // return Promise.reject(new Error("Session is not established.")); // } // const sessionDescriptionHandler = this.session.sessionDescriptionHandler; // if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) { // throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); // } // const options: SessionInviteOptions = {}; // // Unmute // this.unmute(); // // Send re-INVITE // return this.session.invite(options) // .then(() => { return; }); // } unhold1(callId) { this.logger.log(`[${this.id}] unholding session...`); let session = this.userAgent.sessions[callId]; if (!session) { return Promise.reject(new Error("Session does not exist.")); } if (session.state !== SessionState$1.Established) { return Promise.reject(new Error("Session is not established.")); } const sessionDescriptionHandler = session.sessionDescriptionHandler; if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) { throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); } const options = {}; // Unmute this.unmute(callId); // Send re-INVITE return session.invite(options) .then(() => { return; }); } /** * Mute call. * Disable sender's media tracks. */ // public mute(): void { // this.logger.log(`[${this.id}] disabling media tracks...`); // if (!this.session) { // this.logger.warn(`[${this.id}] an session is required to disable media tracks`); // return; // } // if (this.session.state !== SessionState.Established) { // this.logger.warn(`[${this.id}] an established session is required to disable media tracks`); // return; // } // this.enableSenderTracks(false); // } /** * Mute call. * Disable sender's media tracks. */ mute(callId) { return this.muteDetail(callId, true, true); } muteAudio(callId) { return this.muteDetail(callId, true, false); } muteVideo(callId) { return this.muteDetail(callId, false, true); } muteDetail(callId, audio, video) { this.logger.log(`[${this.id}] disabling media tracks...`); let session = this.userAgent.sessions[callId]; if (!session) { this.logger.warn(`[${this.id}] an session is required to disable media tracks`); return; } if (session.state !== SessionState$1.Established) { this.logger.warn(`[${this.id}] an established session is required to disable media tracks`); return; } this.enableSenderTracksDetail(callId, false, audio, video); } /** * Unmute call. * Enable sender's media tracks. */ // public unmute(): void { // this.logger.log(`[${this.id}] enabling media tracks...`); // if (!this.session) { // this.logger.warn(`[${this.id}] an session is required to enable media tracks`); // return; // } // if (this.session.state !== SessionState.Established) { // this.logger.warn(`[${this.id}] an established session is required to enable media tracks`); // return; // } // this.enableSenderTracks(true); // } /** * Unmute call. * Enable sender's media tracks. */ unmuteDetail(callId, audio, video) { this.logger.log(`[${this.id}] enabling media tracks...`); let session = this.userAgent.sessions[callId]; if (!session) { this.logger.warn(`[${this.id}] an session is required to enable media tracks`); return; } if (session.state !== SessionState$1.Established) { this.logger.warn(`[${this.id}] an established session is required to enable media tracks`); return; } this.enableSenderTracksDetail(callId, true, audio, video); } unmute(callId) { return this.unmuteDetail(callId, true, true); } unmuteAudio(callId) { return this.unmuteDetail(callId, true, false); } unmuteVideo(callId) { return this.unmuteDetail(callId, false, true); } /** * Mute state. * True if sender's media track is disabled. */ // public isMuted(): boolean { // const track = this.localAudioTrack || this.localVideoTrack; // if (!track) { // return false; // } // return !track.enabled; // } /** * Send DTMF. * Send an INFO request with content type application/dtmf-relay. * @param tone - Tone to send. */ // public sendDTMF(tone: string): Promise { // this.logger.log(`[${this.id}] sending DTMF...`); // // Validate tone // if (!tone.match(/^[0-9A-D#*,]$/)) { // return Promise.reject(new Error("Invalid DTMF tone.")); // } // if (!this.session) { // return Promise.reject(new Error("Session does not exist.")); // } // this.logger.log("Sending DTMF tone: " + tone); // const dtmf = tone; // const duration = 2000; // const body = { // contentDisposition: "render", // contentType: "application/dtmf-relay", // content: "Signal=" + dtmf + "\r\nDuration=" + duration // }; // const requestOptions = { body }; // return new Infoer(this.session).info({ requestOptions }) // .then(() => { return; }); // } /** * Send DTMF. * Send an INFO request with content type application/dtmf-relay. * @param tone - Tone to send. */ sendDTMF(callId, tone) { this.logger.log(`[${this.id}] sending DTMF...`); // Validate tone if (!tone.match(/^[0-9A-D#*,]$/)) { return Promise.reject(new Error("Invalid DTMF tone.")); } // this.logger.log(`[${this.id}] enabling media tracks...`); let session = this.userAgent.sessions[callId]; if (!session) { this.logger.warn(`[${this.id}] an session is required to senddtmf`); return; } if (!session) { return Promise.reject(new Error("Session does not exist.")); } this.logger.log("Sending DTMF tone: " + tone); const dtmf = tone; const duration = 2000; const body = { contentDisposition: "render", contentType: "application/dtmf-relay", content: "Signal=" + dtmf + "\r\nDuration=" + duration }; const requestOptions = { body }; return new Infoer(session).info({ requestOptions }) .then(() => { return; }); } /** * Send a message. * Send a MESSAGE request. * @param destination - The target destination for the message. A SIP address to send the MESSAGE to. */ message(destination, message) { this.logger.log(`[${this.id}] sending message...`); const target = UserAgent.makeURI(destination); if (!target) { return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`)); } return new Messager(this.userAgent, target, message).message(); } /** Media constraints. */ get constraints() { let constraints = { audio: true, video: false }; // default to audio only calls if (this.options.media && this.options.media.constraints) { constraints = Object.assign({}, this.options.media.constraints); if (!constraints.audio && !constraints.video) { throw new Error("Invalid media constraints - audio and/or video must be true."); } } return constraints; } /** Helper function to enable/disable media tracks. */ // private enableSenderTracks(enable: boolean): void { // if (!this.session) { // throw new Error("Session does not exist."); // } // const sessionDescriptionHandler = this.session.sessionDescriptionHandler; // if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) { // throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); // } // const peerConnection = sessionDescriptionHandler.peerConnection; // peerConnection.getSenders().forEach((sender) => { // if (sender.track) { // sender.track.enabled = enable; // } // }); // } enableSenderTracksDetail(callId, enable, audio, video) { let session = this.userAgent.sessions[callId]; if (!session) { throw new Error("Session does not exist."); } const sessionDescriptionHandler = session.sessionDescriptionHandler; if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) { throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); } const peerConnection = sessionDescriptionHandler.peerConnection; peerConnection.getSenders().forEach((sender) => { if (sender.track) { if (video) { if (sender.track.kind == "video") { sender.track.enabled = enable; } } if (audio) { if (sender.track.kind == "audio") { sender.track.enabled = enable; } } } }); } enableSenderTracks(callId, enable) { return this.enableSenderTracksDetail(callId, enable, true, true); } /** The receiver media track, if available. */ // private getReceiverTrack(kind: "audio" | "video"): MediaStreamTrack | undefined { // if (!this.session) { // this.logger.warn(`[${this.id}] getReceiverTrack - session undefined`); // return undefined; // } // const sessionDescriptionHandler = this.session.sessionDescriptionHandler; // if (!sessionDescriptionHandler) { // this.logger.warn(`[${this.id}] getReceiverTrack - session description handler undefined`); // return undefined; // } // if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) { // throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); // } // const peerConnection = sessionDescriptionHandler.peerConnection; // const rs = peerConnection.getReceivers().length; // const rtpReceiver = peerConnection.getReceivers().find((receiver) => { // return receiver.track.kind === kind ? true : false; // }); // return rtpReceiver ? rtpReceiver.track : undefined; // } /** The sender media track, if available. */ // private getSenderTrack(kind: "audio" | "video"): MediaStreamTrack | undefined { // if (!this.session) { // this.logger.warn(`[${this.id}] getSenderTrack - session undefined`); // return undefined; // } // const sessionDescriptionHandler = this.session.sessionDescriptionHandler; // if (!sessionDescriptionHandler) { // this.logger.warn(`[${this.id}] getSenderTrack - session description handler undefined`); // return undefined; // } // if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) { // throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); // } // const peerConnection = sessionDescriptionHandler.peerConnection; // const rtpSender = peerConnection.getSenders().find((sender) => { // return sender.track && sender.track.kind === kind ? true : false; // }); // return rtpSender && rtpSender.track ? rtpSender.track : undefined; // } /** * Setup session delegate and state change handler. * @param session - Session to setup * @param referralInviterOptions - Options for any Inviter created as result of a REFER. */ // private initSession( // session: Session, // referralInviterOptions?: InviterOptions, // ): void { // // Set session // this.session = session; // // Call session created callback // if (this.delegate && this.delegate.onCallCreated) { // this.delegate.onCallCreated( session.id, null ); // } // // Setup session state change handler // this.session.stateChange.on((state: SessionState) => { // if (this.session !== session) { // return; // if our session has changed, just return // } // this.logger.log(`[${this.id}] session state changed to ${state}`); // switch (state) { // case SessionState.Initial: // break; // case SessionState.Establishing: // break; // case SessionState.Established: // this.setupLocalMedia(); // this.setupRemoteMedia(); // if (this.delegate && this.delegate.onCallAnswered) { // this.delegate.onCallAnswered("0"); // } // break; // case SessionState.Terminating: // break; // case SessionState.Terminated: // this.session = undefined; // this.cleanupMedia(); // if (this.delegate && this.delegate.onCallHangup) { // // this.delegate.onCallHangup("0"); // } // break; // default: // throw new Error("Unknown session state."); // } // }); // // Setup delegate // this.session.delegate = { // onRefer: (referral: Referral) => { // referral // .accept() // .then(() => this.sendInvite(referral.makeInviter(referralInviterOptions), referralInviterOptions)) // .catch((error: Error) => { // this.logger.error(error.message); // }); // } // }; // } initSession1(session, localVideoControl, remoteVideoControl, remoteAudioControl, referralInviterOptions) { // Set session // this.session = session; const callLogger = this.userAgent.getLogger("sip.Call"); session.setupCall(localVideoControl, remoteVideoControl, callLogger, remoteAudioControl); session.setDelegate(this.delegate); // this.calls.push( call1 ); // Call session created callback if (this.delegate && this.delegate.onCallCreated) { this.delegate.onCallCreated(session.id, session.remoteVideoControal); } // Setup session state change handler // this.session.stateChange.on((state: SessionState) => { // if (this.session !== session) { // return; // if our session has changed, just return // } // this.logger.log(`[${this.id}] session state changed to ${state}`); // switch (state) { // case SessionState.Initial: // break; // case SessionState.Establishing: // break; // case SessionState.Established: // this.setupLocalMedia(); // this.setupRemoteMedia(); // if (this.delegate && this.delegate.onCallAnswered) { // this.delegate.onCallAnswered("0"); // } // break; // case SessionState.Terminating: // break; // case SessionState.Terminated: // this.session = undefined; // this.cleanupMedia(); // if (this.delegate && this.delegate.onCallHangup) { // this.delegate.onCallHangup("0"); // } // break; // default: // throw new Error("Unknown session state."); // } // }); // Setup delegate // this.session.delegate = { // onRefer: (referral: Referral) => { // referral // .accept() // .then(() => this.sendInvite(referral.makeInviter(referralInviterOptions), referralInviterOptions)) // .catch((error: Error) => { // this.logger.error(error.message); // }); // } // }; } // private initSession2( // session: Session, // referralInviterOptions?: InviterOptions // ): void { // // Set session // // this.session = session; // const callLogger = this.userAgent.getLogger("sip.Call"); // const call1 = new Call(session, null, null, // callLogger, this.delegate, null); // this.calls.push( call1 ); // // Call session created callback // if (this.delegate && this.delegate.onCallCreated) { // this.delegate.onCallCreated(); // } // Setup session state change handler // this.session.stateChange.on((state: SessionState) => { // if (this.session !== session) { // return; // if our session has changed, just return // } // this.logger.log(`[${this.id}] session state changed to ${state}`); // switch (state) { // case SessionState.Initial: // break; // case SessionState.Establishing: // break; // case SessionState.Established: // this.setupLocalMedia(); // this.setupRemoteMedia(); // if (this.delegate && this.delegate.onCallAnswered) { // this.delegate.onCallAnswered("0"); // } // break; // case SessionState.Terminating: // break; // case SessionState.Terminated: // this.session = undefined; // this.cleanupMedia(); // if (this.delegate && this.delegate.onCallHangup) { // this.delegate.onCallHangup("0"); // } // break; // default: // throw new Error("Unknown session state."); // } // }); // Setup delegate // this.session.delegate = { // onRefer: (referral: Referral) => { // referral // .accept() // .then(() => this.sendInvite(referral.makeInviter(referralInviterOptions), referralInviterOptions)) // .catch((error: Error) => { // this.logger.error(error.message); // }); // } // }; // } /** Helper function to init send then send invite. */ // private sendInvite( // inviter: Inviter, // inviterOptions?: InviterOptions, // inviterInviteOptions?: InviterInviteOptions // ): Promise { // // Initialize our session // this.initSession(inviter, inviterOptions); // // Send the INVITE // return inviter.invite(inviterInviteOptions) // .then((request) => { // this.logger.log(`[${this.id}] sent INVITE`); // }); // } sendInvite1(inviter, localVideoControl, remoteVideoControl, remoteAudioControl, inviterOptions, inviterInviteOptions) { // Initialize our session this.initSession1(inviter, localVideoControl, remoteVideoControl, remoteAudioControl, inviterOptions); // Send the INVITE return inviter.invite(inviterInviteOptions) .then((request) => { this.logger.log(`[${this.id}] sent INVITE`); }); } /** Helper function to attach local media to html elements. */ // private setupLocalMedia(): void { // if (!this.session) { // throw new Error("Session does not exist."); // } // if (this.options.media && this.options.media.local && this.options.media.local.video) { // const localVideoTrack = this.localVideoTrack; // const localAudioTrack = this.localAudioTrack; // if (localVideoTrack) { // const localStream = new MediaStream([localVideoTrack]); // if (localAudioTrack) { // localStream.addTrack(localAudioTrack); // } // this.options.media.local.video.srcObject = localStream; // this.options.media.local.video.volume = 0; // if (this.session.sessionDescriptionHandler ) { // const sessionDescriptionHandler = this.session.sessionDescriptionHandler; // if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) { // throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); // } // const localStream1 = new MediaStream( ); // sessionDescriptionHandler.peerConnection.getSenders().forEach( (sender1) => { // if ( sender1.track ) { // localStream1.addTrack(sender1.track); // } // }); // this.options.media.local.video.srcObject = localStream1; // } // this.options.media.local.video.play(); // } // } // } /** Helper function to attach remote media to html elements. */ // private setupRemoteMedia(): void { // if (!this.session) { // throw new Error("Session does not exist."); // } // if (this.options.media && this.options.media.remote) { // const remoteAudioTrack = this.remoteAudioTrack; // const remoteVideoTrack = this.remoteVideoTrack; // const remoteStream = new MediaStream(); // // If there is a video element, both audio and video will be attached that element. // if (this.options.media.remote.video) { // if (remoteAudioTrack) { // remoteStream.addTrack(remoteAudioTrack); // } // if (remoteVideoTrack) { // remoteStream.addTrack(remoteVideoTrack); // } // this.options.media.remote.video.srcObject = null; // this.options.media.remote.video.srcObject = remoteStream; // // this.options.media.remote.video.volume = 1; // this.options.media.remote.video.play() // .catch((error: Error) => { // this.logger.error(`[${this.id}] error playing video`); // this.logger.error(error.message); // }); // } // if (this.options.media.remote.audio) { // if (remoteAudioTrack) { // remoteStream.addTrack(remoteAudioTrack); // this.options.media.remote.audio.srcObject = remoteStream; // this.options.media.remote.audio.play() // .catch((error: Error) => { // this.logger.error(`[${this.id}] error playing audio`); // this.logger.error(error.message); // }); // } // } // } // } /** Helper function to remove media from html elements. */ cleanupMedia() { if (this.options.media) { if (this.options.media.local) { if (this.options.media.local.video) { this.options.media.local.video.srcObject = null; this.options.media.local.video.pause(); } } if (this.options.media.remote) { if (this.options.media.remote.audio) { this.options.media.remote.audio.srcObject = null; this.options.media.remote.audio.pause(); } if (this.options.media.remote.video) { this.options.media.remote.video.srcObject = null; this.options.media.remote.video.pause(); } } } } previewCamera(videoControl) { const constraints = { audio: false, video: true }; return navigator.mediaDevices.getUserMedia(constraints).then((stream) => { videoControl.srcObject = stream; videoControl.play(); return Promise.resolve(); }).catch((reason) => { return Promise.reject(reason); }); } changeVideoElement(callId, videoControl) { this.logger.log(`[${this.id}] changeVideoElement...`); // if (!session) { // return; // } // Attempt to CANCEL outgoing sessions that are not yet established var session = this.userAgent.sessions[callId]; if (session instanceof Call) { const call = session; call.changeVideoElement(videoControl); } } getIsVideoByCallId(callId) { var session = this.userAgent.sessions[callId]; if (!session) { return false; } if (session instanceof Call) { const call = session; return call.isVideo; } return false; } } var SphoneEventName; (function(SphoneEventName) { SphoneEventName[SphoneEventName["IncomingCall"] = 0] = "IncomingCall"; })(SphoneEventName || (SphoneEventName = {})); class IncomingCallPara { constructor() { this.isScheduleConference = false; } } /** * 注册用户类型 */ var RegUserType; (function(RegUserType) { /** * SIP电话 */ RegUserType[RegUserType["Sip"] = 0] = "Sip"; /** * 终端 */ RegUserType[RegUserType["APPDevice"] = 1] = "APPDevice"; /** * 调度台 */ RegUserType[RegUserType["Dispatcher"] = 2] = "Dispatcher"; })(RegUserType || (RegUserType = {})); var TransferVideoState; (function(TransferVideoState) { /** * 无 */ TransferVideoState[TransferVideoState["None"] = 0] = "None"; /** * 初始 */ TransferVideoState[TransferVideoState["Init"] = 1] = "Init"; /** * 空闲 */ TransferVideoState[TransferVideoState["Normal"] = 2] = "Normal"; /** * 呼出 */ TransferVideoState[TransferVideoState["Callout"] = 3] = "Callout"; /** * 呼入 */ TransferVideoState[TransferVideoState["Incoming"] = 4] = "Incoming"; /** * 回铃 */ TransferVideoState[TransferVideoState["Ringing"] = 5] = "Ringing"; /** * 通话 */ TransferVideoState[TransferVideoState["Connect"] = 6] = "Connect"; /** * 结束 */ TransferVideoState[TransferVideoState["Release"] = 7] = "Release"; /** * 保持 */ TransferVideoState[TransferVideoState["Hold"] = 8] = "Hold"; /** * 取消保持 */ TransferVideoState[TransferVideoState["Unhold"] = 9] = "Unhold"; })(TransferVideoState || (TransferVideoState = {})); class TransferVideoImp { constructor(iceClient, srcNumber, targetNumber, parentCid) { this._stateEmiter = new EventEmitter(); this._iceClient = iceClient; this.srcNumber = srcNumber; this.dstNumber = targetNumber; this._parentCid = parentCid; this._iceClient.on(IceEventName.SessionSendToCreaterState.toString(), (content) => { let sessionState = JSON.parse(content)[0]; let sessionId = sessionState.cid; if (sessionId != this._sessionId) { return; } let state = this.convertIceState(sessionState.state); if (this._state != state) { this._state = state; this._stateEmiter.emit("event", { sender: this, state: this._state }); } }); } set state(value) { if (this._state != value) { this._state = value; } } get state() { return this._state; } convertIceState(iceState) { let state = TransferVideoState.None; switch (iceState) { case "1": state = TransferVideoState.Init; break; case "2": state = TransferVideoState.Normal; break; case "3": state = TransferVideoState.Callout; break; case "4": state = TransferVideoState.Incoming; break; case "5": state = TransferVideoState.Ringing; break; case "6": state = TransferVideoState.Connect; break; case "7": state = TransferVideoState.Hold; break; case "10": state = TransferVideoState.Release; break; case "14": state = TransferVideoState.Unhold; break; default: break; } return state; } start() { return this._iceClient.transferVideo(this._parentCid, this.srcNumber, [this.dstNumber]).then((result) => { this._sessionId = result.newcid; if (result.newcid != null && result.newcid != "") { return Promise.resolve(this._sessionId); } else { return Promise.reject(); } }).catch((reason) => { return Promise.reject(reason); }); } end() { return this._iceClient.endConference(this._sessionId); } get onStateChanged() { return makeEmitter(this._stateEmiter); } } class CallImp { constructor(number, mediaControl, iceClient, sphone) { this._callStateEventEmitter = new EventEmitter(); this._forceInterposeEventEmitter = new EventEmitter(); this._callId = ""; this._sessionIdUndefine = ""; this._memberHasVideo = false; this._transferVideos = {}; this._logger = Logger.getInstance(); this.callType = CallType.Single; // get isVideo(): boolean{ // if (this.state == CallState.Connect) { // return this._memberHasVideo; // } // return this._sphone.getIsVideoByCallId(this._callId); // } this._isVideo = false; this._sessionRelease = false; this._holdOperating = false; this.isCaller = false; this.offerVideo = true; this._isSendVideo = true; this.number = number; this._mediaControl = mediaControl; this._sessionId = this._sessionIdUndefine; this.state = CallState.None; this._sphone = sphone; this._iceClient = iceClient; iceClient.on(IceEventName.SessionMemberChange.toString(), (content) => { let memberState = JSON.parse(content); if (memberState[0].cid != this._sessionId) { return; } if (memberState[0].havevideo == "0") { this._memberHasVideo = false; } else if (memberState[0].havevideo == "1") { this._memberHasVideo = true; } }); // iceClient.on(IceEventName.SessionStateChange.toString(), (content: string) => { // if (this._sessionId == this._sessionIdUndefine) { // return; // } // let sessionState = JSON.parse(content); // let sessionId = sessionState[0].cid; // if (this._sessionId != sessionId) { // return; // } // let callState = this._state; // switch (sessionState[0].state) { // case "1": // callState = CallState.Init; // break; // case "2": // callState = CallState.Normal; // break; // case "3": // callState = CallState.Callout; // break; // case "4": // callState = CallState.Incoming; // break; // case "5": // callState = CallState.Ringing; // break; // case "6": // callState = CallState.Connect; // break; // case "7": // callState = CallState.Hold; // break; // case "10": // callState = CallState.Release; // break; // case "14": // callState = CallState.Unhold; // break; // default: // break; // } // if (callState != this._state) { // let para = { sender: this, state: callState }; // this._callStateEventEmitter.emit("event", para); // } // } // ); // this._sphone.on(SphoneEventName.IncomingCall.toString(), (para: IncomingCallPara )=>{ // console.log(JSON.stringify(para)); // if (this._sessionId == this._sessionIdUndefine || para.cid != this._sessionId) { // return; // } // this._callId = para.id; // this._sphone.answerVideo(this._callId, this._mediaControl as HTMLVideoElement); // }); } open(isPreCamera, isAutoAnswer) { return this._iceClient.SipPhoneVideoBug(this.number, isPreCamera, isAutoAnswer); } close() { return this.hangup(); } PTZMoveX(step, isStart, timeout) { return this._iceClient.PTZMoveX(this.number, step, isStart, timeout); } PTZMoveY(step, isStart, timeout) { return this._iceClient.PTZMoveY(this.number, step, isStart, timeout); } PTZZoom(step, isStart, timeout) { return this._iceClient.PTZZoom(this.number, step, isStart, timeout); } PTZMoveLR(step, isStart, timeout) { return this._iceClient.PTZMoveLR(this.number, step, isStart, timeout); } PTZFocus(step, isStart, timeout) { return this._iceClient.PTZFocus(this.number, step, isStart, timeout); } negotiatedTransfer(otherCall) { let call = otherCall; return this._iceClient.negotiatedTransfer(this._sessionId, call._sessionId, this.number, call.number); } set sipCall(value) { this._sipCall = value; this._sipCall.stateChange.on((sipCallState) => { if (sipCallState == SessionState$1.Terminated) { this._sipCall = null; if (this._sessionRelease) { this._logger.warn("call sipCall State terminated"); this.callStateInternal = CallState.Release; } else { this._logger.warn("call sipCall State terminated but session not release return"); } } }); } get isVideo() { if (!this._isVideo) { return this._sphone.getIsVideoByCallId(this._callId); } return this._isVideo; } set isVideo(value) { this._isVideo = value; } // private _eventEmitter = new EventEmitter(); get callStateChange() { return makeEmitter(this._callStateEventEmitter); } get onBecomeConference() { return makeEmitter(this._forceInterposeEventEmitter); } // onCallStateChange(listener:(sender: Call, state: CallState)=>void){ // this._eventEmitter.on(CallEventName.CallState.toString(), listener); // } set callstate(state) { let callState = iceAPI.convertIceCallState1(state); this.callStateInternal = callState; } set callStateInternal(v) { if (this._holdOperating) { //call hold function server push sessionTerminal imite, just ignore it this._holdOperating = false; return; } if (v == CallState.Release) { this._sessionRelease = true; if (this._sipCall != null) { this._logger.warn("call session release but sipCall not hangup return"); return; } this._logger.warn("call setCallstate release"); } if (this.state != v) { this.state = v; let para = { sender: this, state: this.state }; this._callStateEventEmitter.emit("event", para); // this._eventEmitter.emit(CallEventName.CallState.toString(), this, this._state ); } } get transferVideos() { let result = new Array(); for (const key in this._transferVideos) { if (Object.prototype.hasOwnProperty.call(this._transferVideos, key)) { const element = this._transferVideos[key]; result.push(element); } } return result; } invite(isVideo, callType = 0) { return this._iceClient.makecall(this.number, isVideo, callType).then((cid) => { // this._sessionId = cid; // this._state = CallState.Init; // this.callStateInternal = CallState.Init; return Promise.resolve(); }).catch((reason) => { return Promise.reject(reason); }); } inviteByLeftPhone(isVideo) { return this._iceClient.makecallByLeftPhone(this.number, isVideo).then((cid) => { // this._sessionId = cid; // this.state = CallState.Init; // this.callStateInternal = CallState.Init; return Promise.resolve(); }).catch((reason) => { return Promise.reject(reason); }); } answer(mediaControl, isvideo) { this._mediaControl = mediaControl; if (!this.isVideo) { isvideo = false; } if (!this._isSendVideo) { isvideo = true; } return this._sphone.answer2(this._callId, this._mediaControl, isvideo, LoginInfo.getInstance().audioInputDeviceConfig.id, LoginInfo.getInstance().videoInputDeviceConfig.id, LoginInfo.getInstance().videoInputDeviceConfig.width, LoginInfo.getInstance().videoInputDeviceConfig.height, LoginInfo.getInstance().videoInputDeviceConfig.frameRate, this.offerVideo); } hangup() { // if (this._callId != "") { // this._sphone.hangup1(this._callId); // }else{ // this._iceClient.endConference(this._sessionId); // } if (this.callType == CallType.TransferVideoToMCU) { if (this._sipCall != null) { return this._sphone.hangup1(this._callId); } } return this._iceClient.hangup(this._sessionId).then((result) => { this._logger.warn("call hangup success; " + JSON.stringify(result)); return Promise.resolve(); }).catch((reason) => { this._logger.warn("call hangup fail; " + JSON.stringify(reason)); if (this._sipCall != null) { return this._sphone.hangup1(this._callId); } return Promise.reject(reason); }); } hold() { this._holdOperating = true; // this._sphone.hold1(this._callId); return this._iceClient.hold(this._sessionId); } unhold() { this._holdOperating = false; return this._iceClient.unHold(this._sessionId); } mute() { this._sphone.mute(this._callId); this._iceClient.muteLocalCamera(this._sessionId, LoginInfo.getInstance().number, true); return this._iceClient.muteLocalMic(this._sessionId, LoginInfo.getInstance().number, true); } unmute() { this._sphone.unmute(this._callId); this._iceClient.muteLocalCamera(this._sessionId, LoginInfo.getInstance().number, false); return this._iceClient.muteLocalMic(this._sessionId, LoginInfo.getInstance().number, false); } muteAudio() { this._sphone.muteAudio(this._callId); return this._iceClient.muteLocalMic(this._sessionId, LoginInfo.getInstance().number, true); } muteVideo() { this._sphone.muteVideo(this._callId); return this._iceClient.muteLocalCamera(this._sessionId, LoginInfo.getInstance().number, true); } unmuteAudio() { this._sphone.unmuteAudio(this._callId); return this._iceClient.muteLocalMic(this._sessionId, LoginInfo.getInstance().number, false); } unmuteVideo() { this._sphone.unmuteVideo(this._callId); return this._iceClient.muteLocalCamera(this._sessionId, LoginInfo.getInstance().number, false); } switch (number) { return this._iceClient.switch(this._sessionId, number, this.number); } SubsituteCall(cid) { return this._iceClient.SubsituteCall(this.number, cid).then((callResult) => { console.warn("substitutecall " + JSON.stringify(callResult)); // this._sessionId = callResult.seq[0].cid; // this._state = CallState.Init; // this.callStateInternal = CallState.Init; return Promise.resolve(); }).catch((error) => { return Promise.reject(error); }); } addMember(member) { return this._iceClient.conferenceAddMember(this._sessionId, member); } becomeConference(conf) { let para = { sender: this, changeToConference: conf }; this._forceInterposeEventEmitter.emit("event", para); } startDecoderWall(decoderId, channel) { return this._iceClient.startDecoderWall(decoderId, channel, this._sessionId, this.number); } stopDecoderWall(decoderId, channel) { return this._iceClient.stopDecoderWall(decoderId, channel); } transferVideo(number, receivers) { return this._iceClient.transferVideo(this._sessionId, number, receivers).then((result) => { return Promise.resolve(result.newcid); }).catch((reason) => { return Promise.reject(reason); }); } changeVideoElement(videoControl) { this._sphone.changeVideoElement(this._callId, videoControl); } sendDTMF(tone) { return this._sphone.sendDTMF(this._callId, tone); } transferVideo1(srcNumber, dstNumber) { const transfer = new TransferVideoImp(this._iceClient, srcNumber, dstNumber, this._sessionId); return transfer.start().then((cid) => { this._transferVideos[cid] = transfer; transfer.onStateChanged.on((para) => { if (para.state == TransferVideoState.Release) { delete this._transferVideos[cid]; } }); return Promise.resolve(transfer); }).catch((reason) => { return Promise.reject(reason); }); } requestSendVideo() { if (!this.isVideo) { return false; } if (this._isSendVideo) { this._isSendVideo = false; return this._iceClient.requestSendVideoByJson(this._sessionId); } return false; } hangdleRequestVideo(videoControl) { if (!this.isVideo) { return false; } if (this._isSendVideo) { this._isSendVideo = false; this._mediaControl = videoControl; return this._iceClient.requestSendVideoByJson(this._sessionId); } return false; } requestKeyframe() { return this._iceClient.getKeyframe(this._sessionId, this.number); } get peerConnection() { if (this._sipCall) { return this._sipCall.peerConnection; } return null; } shareScreen() { const mediaDevice = navigator.mediaDevices; mediaDevice.getDisplayMedia({ video: true, audio: false }).then(stream => { let screentrack = stream.getVideoTracks()[0]; this.peerConnection.getSenders().forEach((sender) => { if (sender.track && sender.track.kind == "video") { sender.replaceTrack(screentrack); } }); }); // if (this.peerConnection.removeTrack) { // console.log( "pc senders count: " + this.peerConnection.getSenders().length ); // this.peerConnection.getSenders().forEach((sender: RTCRtpSender) => { // this.peerConnection.removeTrack(sender); // }); // console.log( "pc senders count: " + this.peerConnection.getSenders().length ); // } // navigator.mediaDevices.getUserMedia({video: true, audio: true}) // .then(stream => { // const videoTracks = stream.getVideoTracks(); // console.log( "video track count: " + videoTracks.length ); // if (videoTracks.length > 0) { // console.log(`Using video device: ${videoTracks[0].label}`); // } // this.peerConnection.addTrack(stream.getAudioTracks()[0], stream); // this.peerConnection.addTrack(stream.getVideoTracks()[0], stream); // }); // const options: InviterOptions = { // sessionDescriptionHandlerOptions: { // constraints: { audio: true, video: true } // } // }; // this._sipCall.invite(options); // localStream.addTrack(videoTracks[0]); // localVideo.srcObject = null; // localVideo.srcObject = localStream; // this.peerConnection.addTrack(videoTracks[0], stream); console.log("pc senders count: " + this.peerConnection.getSenders().length); // this.peerConnection.createOffer().then((offer: RTCSessionDescriptionInit)=>{ // this.peerConnection.setLocalDescription(offer); // }) // }) } } var CallEventName; (function(CallEventName) { CallEventName[CallEventName["CallState"] = 0] = "CallState"; })(CallEventName || (CallEventName = {})); class BusinessClient { constructor() { this._eventEmiiter = new EventEmitter(); } static getInstance() { if (BusinessClient.s_bsclient == null) { BusinessClient.s_bsclient = new BusinessClient(); } return BusinessClient.s_bsclient; } newEvent(listener) { this._eventEmiiter.on(BusinessEventName.newEvent.toString(), listener); } dataChanged(listener) { this._eventEmiiter.on(BusinessEventName.datachange.toString(), listener); } heartBeat(listener) { this._eventEmiiter.on(BusinessEventName.haartbeat.toString(), listener); } materalChanged(listener) { this._eventEmiiter.on(BusinessEventName.materialchange.toString(), listener); } newTast(listener) { this._eventEmiiter.on(BusinessEventName.newtask.toString(), listener); } stateChanged(listener) { this._eventEmiiter.on(BusinessEventName.statechange.toString(), listener); } tastStateChanged(listener) { this._eventEmiiter.on(BusinessEventName.taskstatechange.toString(), listener); } wareHouseChanged(listener) { this._eventEmiiter.on(BusinessEventName.warehousechange.toString(), listener); } regist(ip, port, userName) { this._serverIP = ip; this._serverPort = port; this._username = userName; this.iceInit(); return this.connect(); } iceInit() { const properties = ice.Ice.createProperties(); properties.setProperty("Ice.ACM.Close", "0"); // properties.setProperty("Ice.ACM.Client","0"); //禁用连接管理器,3.5.1版本,双向连接不会自动关闭 // properties.setProperty("Ice.ACM.Server","0"); //禁用连接管理器 const id = new ice.Ice.InitializationData(); id.properties = properties; this._iceCommunicator = ice.Ice.initialize(id); // this._iceStatus = e_Status.nDisconnect; } async connect() { // const hostname = document.location.hostname || "127.0.0.1"; // let proxy = this._iceCommunicator.stringToProxy("EMSrv:tcp -h " + this._serverIP + " -p " + this._serverPort); let proxy = this._iceCommunicator.stringToProxy("EMSrv" + ":wss -h " + this._serverIP + " -p " + this._serverPort); // this._caller = this._username; proxy.ice_timeout(10000); // // Set or clear the timeout. // // const timeout:number = Number($("#timeout").val()); const timeout = 3000; proxy = proxy.ice_invocationTimeout(timeout); // // Set the mode and protocol // // const mode = $("#mode").val(); // if(mode == "twoway") // { proxy = proxy.ice_twoway(); // } // else if(mode == "twoway-secure") // { // proxy = proxy.ice_twoway().ice_secure(true); // } // else if(mode == "oneway") // { // proxy = proxy.ice_oneway(); // } // else if(mode == "oneway-secure") // { // proxy = proxy.ice_oneway().ice_secure(true); // } // else if(mode == "oneway-batch") // { // proxy = proxy.ice_batchOneway(); // } // else if(mode == "oneway-batch-secure") // { // proxy = proxy.ice_batchOneway().ice_secure(true); // } this._proxy = EM.EMSrvPrx.uncheckedCast(proxy); const myadapter = await this._iceCommunicator.createObjectAdapter(""); const identity1 = new ice.Ice.Identity(this._username, "EMCli"); this._myid = new EM.EMIdentity(this._username); //业务服务器ICE注册 // ic_mdcsrv.begin_EMRegisterOP(bsIdentity, "", new Callback_EMSrv_EMRegisterOP() { // @Override // public void response(String code) { // Log.e(TAG,"begin_BSRegisterOP。。。。。。。。。。。。。。。。。。"+code); // ReceiveHeartBeat(); // } // @Override // public void exception(UserException __ex) { // Log.e(TAG,"UserException。。。。。。。。。。。。。。。。。。"); // g_Conn= ConnState.stateInit; // TreateException(__ex); // threadSleep(1000); // } // @Override // public void exception(LocalException e) { // Log.e(TAG,"LocalException。。。。。。。。。。。。。。。。。。"); // g_Conn= ConnState.stateInit; // TreateException(e); // threadSleep(1000); // } // }); this._myReceiver = new BusinessProxyReceive(); this._myReceiver.eventEmiter = this._eventEmiiter; myadapter.add(this._myReceiver, identity1); const connection = await this._proxy.ice_getConnection(); connection.setAdapter(myadapter); let bsIdentity = new EM.EMIdentity(); bsIdentity.user = this._username; return this._proxy.EMRegisterOP(bsIdentity, ""); } getEventsList(json) { let bsIdentity = new EM.EMIdentity(); bsIdentity.user = this._username; return this._proxy.EMGetEventsOP(bsIdentity, json); } getEventPara() { let bsIdentity = new EM.EMIdentity(); bsIdentity.user = this._username; return this._proxy.EMEventGetParam(bsIdentity, ""); } getEventDetail(eventid) { let bsIdentity = new EM.EMIdentity(); bsIdentity.user = this._username; return this._proxy.EMGetEventDetialOP(bsIdentity, eventid); } getTastList(json) { let bsIdentity = new EM.EMIdentity(); bsIdentity.user = this._username; return this._proxy.EMGetTaskBySelfOP(bsIdentity, json); } returnTast(json) { let bsIdentity = new EM.EMIdentity(); bsIdentity.user = this._username; return this._proxy.EMEventReturnOP(bsIdentity, json); } startProcessTast(json) { let bsIdentity = new EM.EMIdentity(); bsIdentity.user = this._username; return this._proxy.EMEventStartProcessOP(bsIdentity, json); } overProcessTast(json) { let bsIdentity = new EM.EMIdentity(); bsIdentity.user = this._username; return this._proxy.EMEventProcessOverOP(bsIdentity, json); } reportNewevent(json) { let bsIdentity = new EM.EMIdentity(); bsIdentity.user = this._username; return this._proxy.EMEventReportOP(bsIdentity, json); } /** * 派单 * @param json {"evt_id":"35d3fc61-9934-4701-ab6f-6de38ecc3dd1","executor_id":"2000","task_receivers":[{"user":"3000"}],"mark":"请马上处理1215"} */ eventDistribute(json) { let bsIdentity = new EM.EMIdentity(); bsIdentity.user = this._username; return this._proxy.EMEventDistributeOP(bsIdentity, json); } /** * 事件确认 * @param json {"evt_id":"35d3fc61-9934-4701-ab6f-6de38ecc3dd1","executor_id":"2000","mark":""} */ eventConfirm(json) { let bsIdentity = new EM.EMIdentity(); bsIdentity.user = this._username; return this._proxy.EMEventConfirmOP(bsIdentity, json); } /** * 查看事件 * @param json {"evt_id":"72fe9fa3-4634-4d84-bd52-712d995b19e5"} */ eventView(json) { let bsIdentity = new EM.EMIdentity(); bsIdentity.user = this._username; return this._proxy.EMEventViewOP(bsIdentity, json); } } class BusinessProxyReceive extends EM.EMCli { constructor() { super(); } EMCBNotifyNewEvent(msg, current) { this.eventEmiter.emit(BusinessEventName.newEvent.toString(), msg); } EMCBNotifyEventStateChanged(msg, current) { this.eventEmiter.emit(BusinessEventName.statechange.toString(), msg); } EMCBNotifyNewTask(msg, current) { this.eventEmiter.emit(BusinessEventName.newtask.toString(), msg); } EMCBNotifyTaskStateChanged(msg, current) { this.eventEmiter.emit(BusinessEventName.taskstatechange.toString(), msg); } EMCBNotifyWarehouseChanged(operate, msg, current) { this.eventEmiter.emit(BusinessEventName.warehousechange.toString(), operate, msg); } EMCBNotifyMaterialChanged(operate, msg, current) { this.eventEmiter.emit(BusinessEventName.materialchange.toString(), operate, msg); } EMHeartbeatCB(msg, current) { this.eventEmiter.emit(BusinessEventName.haartbeat.toString(), msg); } EMDataChangedCB(msg, current) { this.eventEmiter.emit(BusinessEventName.datachange.toString(), msg); } } var BusinessEventName; (function(BusinessEventName) { BusinessEventName[BusinessEventName["newEvent"] = 0] = "newEvent"; BusinessEventName[BusinessEventName["statechange"] = 1] = "statechange"; BusinessEventName[BusinessEventName["newtask"] = 2] = "newtask"; BusinessEventName[BusinessEventName["taskstatechange"] = 3] = "taskstatechange"; BusinessEventName[BusinessEventName["warehousechange"] = 4] = "warehousechange"; BusinessEventName[BusinessEventName["materialchange"] = 5] = "materialchange"; BusinessEventName[BusinessEventName["haartbeat"] = 6] = "haartbeat"; BusinessEventName[BusinessEventName["datachange"] = 7] = "datachange"; })(BusinessEventName || (BusinessEventName = {})); /** * 会议状态 */ var ConferenceState; (function(ConferenceState) { /** * 0 无 */ ConferenceState[ConferenceState["None"] = 0] = "None"; /** * 1 正在入会 */ ConferenceState[ConferenceState["Connecting"] = 1] = "Connecting"; /** * 2 已经入会 */ ConferenceState[ConferenceState["Connected"] = 2] = "Connected"; /** * 3 被踢出会议 */ ConferenceState[ConferenceState["Kickout"] = 3] = "Kickout"; /** * 4 结束 */ ConferenceState[ConferenceState["Terminaled"] = 4] = "Terminaled"; /** * 5 离开会议 */ ConferenceState[ConferenceState["Leave"] = 5] = "Leave"; })(ConferenceState || (ConferenceState = {})); /** * 会议成员状态改变事件 */ var ConferenceMemberState; (function(ConferenceMemberState) { /** * 0 入会 */ ConferenceMemberState[ConferenceMemberState["Enter"] = 0] = "Enter"; /** * 1 离会 */ ConferenceMemberState[ConferenceMemberState["Leave"] = 1] = "Leave"; /** * 2 允许讲话 */ ConferenceMemberState[ConferenceMemberState["Speak"] = 2] = "Speak"; /** * 3 禁止发言 */ ConferenceMemberState[ConferenceMemberState["Unspeak"] = 3] = "Unspeak"; /** * 4 允许听讲 */ ConferenceMemberState[ConferenceMemberState["listen"] = 4] = "listen"; /** * 5 禁止听讲 */ ConferenceMemberState[ConferenceMemberState["unlisten"] = 5] = "unlisten"; /** * 6 拒绝入会 */ ConferenceMemberState[ConferenceMemberState["Reject"] = 6] = "Reject"; /** * 7 响铃 */ ConferenceMemberState[ConferenceMemberState["ringing"] = 7] = "ringing"; /** * 8 入会 */ ConferenceMemberState[ConferenceMemberState["connected"] = 8] = "connected"; /** * 9 本地禁言 */ ConferenceMemberState[ConferenceMemberState["MuteLocalMic"] = 9] = "MuteLocalMic"; /** * 10 解除本地禁言 */ ConferenceMemberState[ConferenceMemberState["UnmuteLocalMic"] = 10] = "UnmuteLocalMic"; /** * 11 本地禁止摄像头 */ ConferenceMemberState[ConferenceMemberState["MuteLocalCamera"] = 11] = "MuteLocalCamera"; /** * 11 本地解除禁止摄像头 */ ConferenceMemberState[ConferenceMemberState["UnmuteLocalCamera"] = 12] = "UnmuteLocalCamera"; })(ConferenceMemberState || (ConferenceMemberState = {})); /** * 推送音频到RTSP状态 */ var PushAudioToRTSPState; (function(PushAudioToRTSPState) { /** * 停止 */ PushAudioToRTSPState[PushAudioToRTSPState["stop"] = 0] = "stop"; /** * 开始 */ PushAudioToRTSPState[PushAudioToRTSPState["start"] = 1] = "start"; })(PushAudioToRTSPState || (PushAudioToRTSPState = {})); class ConferenceImp { constructor(videoControl, members, name, iceClient, sphone, startVideo = true) { this._logger = Logger.getInstance(); this._members = {}; this._calls = {}; // private _tempOutgoingCall: CallImp; this._tempOutgoingCalls = new Array(); this.isReEnter = false; this._startVideo = true; this.isSchedule = false; this._transferVideos = {}; this._isVideo = false; // sipCall: Invitation; this._sessionRelease = false; this.isCaller = false; this.monitorVideoCall = false; this._pushAudioToRTSPState = PushAudioToRTSPState.stop; this.state = ConferenceState.None; this._stateChangeEmiiter = new EventEmitter(); this._memberStateChangeEmiiter = new EventEmitter(); this._currentVideoChanged = new EventEmitter(); this._pushAudioToRTSPStateEmitter = new EventEmitter(); this._lastOpenMemberVideoTime = 0; this._isSendVideo = true; this._mediaControl = videoControl; this.name = name; this._iceClient = iceClient; this._sphone = sphone; this._initMembers = members; this._startVideo = startVideo; this._iceClient.on(IceEventName.SessionMemberChange.toString(), (content) => { // this._logger.warn("sessionMemberChange: " + content); if (this.state == ConferenceState.Terminaled || this.state == ConferenceState.Kickout || this.state == ConferenceState.Leave) { this._logger.warn("not in conference"); return; } let sessionState = JSON.parse(content); let sessionId = sessionState[0].cid; if (sessionId != this._sessionId) { return; } let state = sessionState[0].state; let member = sessionState[0].employeeid; let name = sessionState[0].name; let existMember = this._members[member]; let para; let callState = iceAPI.convertIceCallState1(state); let allowSpeak; let notSpeak = sessionState[0].notspeak; if (notSpeak == "0") { allowSpeak = true; } else { allowSpeak = false; } let allowListen; let notHear = sessionState[0].nothear; if (notHear == "0") { allowListen = true; } else { allowListen = false; } let muteLocalMic = false; if (sessionState[0].muteLocalMic == "0") { muteLocalMic = false; } else { muteLocalMic = true; } let muteLocalCamera = false; if (sessionState[0].muteLocalCamera == "0") { muteLocalCamera = false; } else { muteLocalCamera = true; } let preState = CallState.None; if (existMember == null) { existMember = { number: member, name: name, allowSpeak: allowSpeak, allowListen: allowListen, hasVideo: true, callState: callState, muteLocalCamera: false, muteLocalMic: false }; this._members[member] = existMember; para = { sender: this, state: ConferenceMemberState.Enter, member: member }; this._memberStateChangeEmiiter.emit("event", para); } else { preState = existMember.callState; existMember.callState = callState; } let havevideo = sessionState[0].havevideo; if (havevideo == "0") { existMember.hasVideo = false; } else { existMember.hasVideo = true; } switch (state) { case "1": // if (existMember == null) { para = { sender: this, state: ConferenceMemberState.ringing, member: member }; this._memberStateChangeEmiiter.emit("event", para); // } break; case "6": if (preState != CallState.Connect) { para = { sender: this, state: ConferenceMemberState.connected, member: member }; this._memberStateChangeEmiiter.emit("event", para); } else { if (allowSpeak != existMember.allowSpeak) { existMember.allowSpeak = allowSpeak; let memberState = ConferenceMemberState.Speak; if (!allowSpeak) { memberState = ConferenceMemberState.Unspeak; } para = { sender: this, state: memberState, member: member }; this._memberStateChangeEmiiter.emit("event", para); } if (allowListen != existMember.allowListen) { existMember.allowListen = allowListen; let memberState1 = ConferenceMemberState.listen; if (!allowListen) { memberState1 = ConferenceMemberState.unlisten; } para = { sender: this, state: memberState1, member: member }; this._memberStateChangeEmiiter.emit("event", para); } if (muteLocalMic != existMember.muteLocalMic) { existMember.muteLocalMic = muteLocalMic; let memberState = ConferenceMemberState.MuteLocalMic; if (!muteLocalMic) { memberState = ConferenceMemberState.UnmuteLocalMic; } para = { sender: this, state: memberState, member: member }; this._memberStateChangeEmiiter.emit("event", para); } if (muteLocalCamera != existMember.muteLocalCamera) { existMember.muteLocalCamera = muteLocalCamera; let memberState = ConferenceMemberState.MuteLocalCamera; if (!muteLocalCamera) { memberState = ConferenceMemberState.UnmuteLocalCamera; } para = { sender: this, state: memberState, member: member }; this._memberStateChangeEmiiter.emit("event", para); } } let ispush = sessionState[0].ispush; if (ispush == 1) { if (this.currentVideoMember != member) { this.currentVideoMember = member; this._currentVideoChanged.emit("event", { sender: this, member: member }); } } break; case "10": if (existMember != null) { delete this._members[member]; para = { sender: this, state: ConferenceMemberState.Leave, member: member }; this._memberStateChangeEmiiter.emit("event", para); this.closeMemberVideo(member); } // else { // para = { sender: this, state: ConferenceMemberState.Reject, member: member }; // this._memberStateChangeEmiiter.emit("event", para); // } break; default: break; } }); var _handleIncomingCall = this._handleIncomingCall.bind(this); this._sphone.on(SphoneEventName.IncomingCall.toString(), _handleIncomingCall); this.removeListeners = function() { this._sphone.removeListener(SphoneEventName.IncomingCall.toString(), _handleIncomingCall); }; } set sipCall(value) { this._sipCall = value; this._sipCall.stateChange.on((sipCallState) => { if (sipCallState == SessionState$1.Terminated) { this._sipCall = null; if (this._sessionRelease) { this._logger.warn("call sipCall State terminated"); this.stateInternal = ConferenceState.Terminaled; } else { this._logger.warn("call sipCall State terminated but session not release return"); } } }); } get currentVideoMember() { if (this.isMCU) { return "*"; } return this._currentVideoMember; } set currentVideoMember(v) { this._currentVideoMember = v; } get isVideo() { if (this.monitorVideoCall) { return true; } if (!this._isVideo) { return this._sphone.getIsVideoByCallId(this._callId); } return this._isVideo; } set isVideo(value) { this._isVideo = value; } get transferVideos() { let result = new Array(); for (const key in this._transferVideos) { if (Object.prototype.hasOwnProperty.call(this._transferVideos, key)) { const element = this._transferVideos[key]; result.push(element); } } return result; } get pushAudioToRTSPState() { return this._pushAudioToRTSPState; } set pushAudioToRTSPState(v) { if (this._pushAudioToRTSPState != v) { let para = { sender: this, state: v }; this._pushAudioToRTSPStateEmitter.emit("event", para); } this._pushAudioToRTSPState = v; } _handleIncomingCall(para) { if (para.orgCaller == "*5*get") { let tempCall = this._tempOutgoingCalls.shift(); if (tempCall == null) { return; } tempCall._callId = para.id; tempCall.sipCall = para.invitation; tempCall._sessionId = para.cid; this._calls[tempCall.number] = tempCall; // this.answerMemberCall(para.id); tempCall.offerVideo = false; console.warn("conference autoanswer member call " + tempCall.number); tempCall.answer(tempCall._mediaControl, true); return; } } get memberStateChange() { return makeEmitter(this._memberStateChangeEmiiter); } get stateChange() { return makeEmitter(this._stateChangeEmiiter); } get currentVideoChanged() { return makeEmitter(this._currentVideoChanged); } get pushAudioToRTSPStateChanged() { return makeEmitter(this._pushAudioToRTSPStateEmitter); } get members() { // this._members = new Array(); this.getMembers(); return this._members; } getMembers() { return this._iceClient.getConfMembers(this._sessionId).then((results) => { this._logger.warn("getconfMembers: " + JSON.stringify(results)); results.forEach(element => { let callState = element.state.value; let isAlllowSpeakStr = element.stateDecorate.substr(0, 1); let isAlllowSpeak = true; if (isAlllowSpeakStr == "1") { isAlllowSpeak = false; } let isAlllowListenStr = element.stateDecorate.substr(1, 1); let isAlllowListen = true; if (isAlllowListenStr == "1") { isAlllowListen = false; } let ismuteLocalCameraStr = element.stateDecorate.substr(5, 1); let ismuteLocalCamera = true; if (ismuteLocalCameraStr == "0") { ismuteLocalCamera = false; } let ismuteLocalMicStr = element.stateDecorate.substr(4, 1); let ismuteLocalMic = true; if (ismuteLocalMicStr == "0") { ismuteLocalMic = false; } let member = { number: element.employeeid, name: element.name, allowSpeak: isAlllowSpeak, allowListen: isAlllowListen, hasVideo: true, callState: callState, muteLocalCamera: ismuteLocalCamera, muteLocalMic: ismuteLocalMic }; this._members[member.number] = member; let ispush = element.stateDecorate.substr(3, 1); if (ispush == "1") { this._logger.warn("member " + element.employeeid + ", is current push Video"); if (this.currentVideoMember != element.employeeid) { this.currentVideoMember = element.employeeid; this._currentVideoChanged.emit("event", { sender: this, member: this.currentVideoMember }); } } }); return Promise.resolve(this._members); }).catch((reason) => { // return Promise.reject(reason); return Promise.resolve(this._members); }); } // _state:ConferenceState; start(number = LoginInfo.getInstance().number) { // let strMembers = new Array(); // this.members.forEach(element => { // strMembers.push(element.number); // }); return this._iceClient.createConference(this._initMembers, this._startVideo, number).then((result) => { this._logger.log("createConf sucess " + JSON.stringify(result)); this._sessionId = result.cid; }); } accept(mediaControl, isvideo) { this._mediaControl = mediaControl; if (!this.isVideo) { isvideo = false; } // this._sphone.answer2(this._callId, this._mediaControl as HTMLVideoElement, isvideo, LoginInfo.getInstance().audioInputDeviceConfig.id, LoginInfo.getInstance().videoInputDeviceConfig.id); this._sphone.answer2(this._callId, this._mediaControl, isvideo, LoginInfo.getInstance().audioInputDeviceConfig.id, LoginInfo.getInstance().videoInputDeviceConfig.id, LoginInfo.getInstance().videoInputDeviceConfig.width, LoginInfo.getInstance().videoInputDeviceConfig.height, LoginInfo.getInstance().videoInputDeviceConfig.frameRate); } reEnter() { this.isReEnter = true; return this.add(LoginInfo.getInstance().number); } // answerMemberCall(callId: string) { // // for (const key in this._calls) { // // if (Object.prototype.hasOwnProperty.call(this._calls, key)) { // // const element = this._calls[key]; // // element.answer( element._mediaControl, true ) // // break; // // } // // } // //this._calls[0] // if (this._tempOutgoingCall != null) { // this._tempOutgoingCall._callId = callId; // this._tempOutgoingCall.answer(this._tempOutgoingCall._mediaControl, true) // } // } add(number) { return this._iceClient.conferenceAddMember(this._sessionId, number); } remove(number) { return this._iceClient.conferenceDeleteMember(this._sessionId, number); } end() { this.removeListeners && this.removeListeners(); return this._iceClient.endConference(this._sessionId); } exit() { // this.removeListeners && this.removeListeners(); this.stateInternal = ConferenceState.Leave; // return this._sphone.hangup1(this._callId) if (this.monitorVideoCall) { return this._sphone.hangup1(this._callId); } return this._iceClient.hangup(this._sessionId); } openMemberVideo(member, videoControl) { let innerFun = () => { let call = this._calls[member]; if (call != null) { return Promise.reject(); } call = new CallImp(member, videoControl, this._iceClient, this._sphone); // this._calls[member] = call; this._tempOutgoingCalls.push(call); // this._tempOutgoingCall = call; this._lastOpenMemberVideoTime = new Date().valueOf(); console.warn("openMembervideo " + member); return this._iceClient.conferenceGetVideo(this._sessionId, member).then((result) => { console.warn("openMembervideo success " + member + ", " + result); return Promise.resolve(result); }).catch((reason) => { console.warn("openMembervideo fail " + member + ", " + reason); return Promise.reject(reason); }); }; if (this._lastOpenMemberVideoTime == 0 || (new Date().valueOf() - this._lastOpenMemberVideoTime) > 1000) { innerFun(); } else { setTimeout(() => { return innerFun(); }, 2000); } return Promise.resolve(); } openMemberVideoMCU(member, videoControl) { let innerFun = () => { let call = this._calls[member]; if (call != null) { return Promise.reject(); } call = new CallImp(member, videoControl, this._iceClient, this._sphone); call.callType = CallType.TransferVideoToMCU; // this._calls[member] = call; this._tempOutgoingCalls.push(call); // this._tempOutgoingCall = call; this._lastOpenMemberVideoTime = new Date().valueOf(); console.warn("openMembervideo " + member); return this._iceClient.conferenceGetVideoMCU(this._sessionId, member).then((result) => { console.warn("openMembervideo success " + member + ", " + result); return Promise.resolve(result); }).catch((reason) => { console.warn("openMembervideo fail " + member + ", " + reason); return Promise.reject(reason); }); }; if (this._lastOpenMemberVideoTime == 0 || (new Date().valueOf() - this._lastOpenMemberVideoTime) > 1000) { innerFun(); } else { setTimeout(() => { return innerFun(); }, 2000); } return Promise.resolve(); } closeMemberVideo(member) { // this._iceClient.conferenceGetVideo(this._sessionId, member); let call = this._calls[member]; if (call != null) { delete this._calls[member]; call.hangup(); } } setConferenceVideo(member) { // return this._iceClient.conferenceGetVideo(this._sessionId, member); return this._iceClient.conferencePushMember(this._sessionId, member); } allowSpeak(member, allow) { return this._iceClient.allowSpeak(this._sessionId, member, allow); } allowListen(member, allow) { return this._iceClient.allowListen(this._sessionId, member, allow); } set stateice(state) { let confState = this.state; switch (state) { case "1": // callState = CallState.Init; break; case "2": // callState = CallState.Normal; break; case "3": confState = ConferenceState.Connecting; break; case "4": break; case "5": break; case "6": confState = ConferenceState.Connected; break; case "7": break; case "10": confState = ConferenceState.Terminaled; break; case "14": break; case "15": if (this.state != ConferenceState.Leave) { confState = ConferenceState.Kickout; } break; default: break; } this.stateInternal = confState; } set stateInternal(v) { if (v == ConferenceState.Terminaled) { this._sessionRelease = true; if (this._sipCall != null) { this._logger.warn("conference session release but sipCall not hangup return"); return; } this._logger.warn("conference setCallstate release"); } if (this.state != v) { if (v == ConferenceState.Connected) { this.getMembers(); } this.state = v; let para = { sender: this, state: this.state }; this._logger.log("conference state change " + this.isMCU + this.currentVideoMember); this._stateChangeEmiiter.emit("event", para); // this._eventEmitter.emit(CallEventName.CallState.toString(), this, this._state ); } } startDecoderWall(decoderId, channel, member) { return this._iceClient.startDecoderWall(decoderId, channel, this._sessionId, member); } stopDecoderWall(decoderId, channel) { return this._iceClient.stopDecoderWall(decoderId, channel); } transferVideo(number, receivers) { return this._iceClient.transferVideo(this._sessionId, number, receivers); } transferVideo1(srcNumber, dstNumber) { const transfer = new TransferVideoImp(this._iceClient, srcNumber, dstNumber, this._sessionId); return transfer.start().then((cid) => { this._transferVideos[cid] = transfer; transfer.onStateChanged.on((para) => { if (para.state == TransferVideoState.Release) { delete this._transferVideos[cid]; } }); return Promise.resolve(transfer); }).catch((reason) => { return Promise.reject(reason); }); } mute() { this._sphone.mute(this._callId); this._iceClient.muteLocalCamera(this._sessionId, LoginInfo.getInstance().number, true); return this._iceClient.muteLocalMic(this._sessionId, LoginInfo.getInstance().number, true); } unmute() { this._sphone.unmute(this._callId); this._iceClient.muteLocalCamera(this._sessionId, LoginInfo.getInstance().number, false); return this._iceClient.muteLocalMic(this._sessionId, LoginInfo.getInstance().number, false); } muteAudio() { this._sphone.muteAudio(this._callId); return this._iceClient.muteLocalMic(this._sessionId, LoginInfo.getInstance().number, true); } muteVideo() { this._sphone.muteVideo(this._callId); return this._iceClient.muteLocalCamera(this._sessionId, LoginInfo.getInstance().number, true); } unmuteAudio() { this._sphone.unmuteAudio(this._callId); return this._iceClient.muteLocalMic(this._sessionId, LoginInfo.getInstance().number, false); } unmuteVideo() { this._sphone.unmuteVideo(this._callId); return this._iceClient.muteLocalCamera(this._sessionId, LoginInfo.getInstance().number, false); } requestSendVideo() { if (this._isSendVideo) { this._isSendVideo = false; return this._iceClient.requestSendVideoByJson(this._sessionId); } return false; } hangdleRequestVideo(videoControl) { if (this._isSendVideo) { this._isSendVideo = false; this._mediaControl = videoControl; return this._iceClient.requestSendVideoByJson(this._sessionId); } return false; } requestKeyframe() { return this._iceClient.getKeyframe(this._sessionId, this.currentVideoMember); } get peerConnection() { if (this._sipCall) { return this._sipCall.peerConnection; } return null; } /** * 开启关闭屏幕共享 * @param enable 是否开启屏幕共享 */ shareScreen(enable) { if (enable) { const mediaDevice = navigator.mediaDevices; mediaDevice.getDisplayMedia({ video: true, audio: false }).then(stream => { // stream.getVideoTracks()[0].applyConstraints({frameRate: 15}); let screentrack = stream.getVideoTracks()[0]; this.peerConnection.getSenders().forEach((sender) => { if (sender.track && sender.track.kind == "video") { sender.replaceTrack(screentrack); // let para = sender.getParameters(); // para.encodings[0].maxBitrate = 2000000000; // sender.setParameters(para).then( () =>{ // console.log("set with"); // } ); } }); // const options: InviterOptions = { // sessionDescriptionHandlerOptions: { // constraints: { audio: true, video: true } // } // }; // this._sipCall.invite(options); }); } else { navigator.mediaDevices.getUserMedia({ video: true, audio: false }).then(stream => { let screentrack = stream.getVideoTracks()[0]; this.peerConnection.getSenders().forEach((sender) => { if (sender.track && sender.track.kind == "video") { sender.replaceTrack(screentrack); } }); }); } } startPushRTSP(rtspUrl, codec) { return this._iceClient.PushStartCallAudio(this._sessionId, rtspUrl, codec); } stopPushRTSP() { return this._iceClient.PushStopCallAudio(this._sessionId); } } /** * 对讲状态 */ var IntercomState; (function(IntercomState) { /** * 无 */ IntercomState[IntercomState["None"] = 0] = "None"; /** * 正在连接 */ IntercomState[IntercomState["Connecting"] = 1] = "Connecting"; /** * 已经接通 */ IntercomState[IntercomState["Connected"] = 2] = "Connected"; // Kickout, /** * 结束 */ IntercomState[IntercomState["Terminaled"] = 3] = "Terminaled"; })(IntercomState || (IntercomState = {})); var IntercomMemberState; (function(IntercomMemberState) { /** * 加入对讲 */ IntercomMemberState[IntercomMemberState["Enter"] = 0] = "Enter"; /** * 退出对讲 */ IntercomMemberState[IntercomMemberState["Leave"] = 1] = "Leave"; })(IntercomMemberState || (IntercomMemberState = {})); class IntercomImp { constructor(mediaControl, members, name, iceClient, sphone) { this._logger = Logger.getInstance(); this._stateChangeEmiiter = new EventEmitter(); this._memberStateChangeEmiiter = new EventEmitter(); this._speakerChangeEmiiter = new EventEmitter(); this._waitingStateChangeEmiiter = new EventEmitter(); this._members = {}; this._mediaControl = mediaControl; this.name = name; this._iceClient = iceClient; this._sphone = sphone; this._initMembers = members; this._iceClient.on(IceEventName.SessionMemberChange.toString(), (content) => { this._logger.warn("sessionMemberChange: " + content); let sessionState = JSON.parse(content); let sessionId = sessionState[0].cid; if (sessionId != this._sessionId) { return; } let state = sessionState[0].state; let member = sessionState[0].employeeid; let name = sessionState[0].name; let existMember = this._members[member]; let para; switch (state) { case "6": if (existMember == null) { let existMember = { number: member, name: name }; this._members[member] = existMember; para = { sender: this, state: IntercomMemberState.Enter, member: member }; this._memberStateChangeEmiiter.emit("event", para); } break; case "10": if (existMember != null) { delete this._members[member]; para = { sender: this, state: IntercomMemberState.Leave, member: member }; this._memberStateChangeEmiiter.emit("event", para); } break; default: break; } }); this._iceClient.on(IceEventName.PttStateSpeaker.toString(), (content) => { let sessionId = content.substring(content.indexOf("call_id:") + "call_id:".length).trim(); // sessionId = sessionId.substring(0, sessionId.length -1); this._logger.warn("ptt speaker changed, cid: " + sessionId + ", _cid: " + this._sessionId + "."); if (sessionId != this._sessionId) { this._logger.warn("ptt not equal"); return; } let speakerStr = content.substring(content.indexOf("speaker:") + "speaker:".length, content.indexOf("call_id:")).trim(); this._logger.warn(speakerStr); if (speakerStr != this.speaker) { this.speaker = speakerStr; let para = { sender: this, speaker: speakerStr }; this._speakerChangeEmiiter.emit("event", para); } }); this._iceClient.on(IceEventName.PttWaiting.toString(), (content) => { let msgObj = JSON.parse(content)[0]; let sessionId = msgObj.cid; // sessionId = sessionId.substring(0, sessionId.length -1); this._logger.warn("ptt waiting, cid: " + sessionId + ", _cid: " + this._sessionId + "."); if (sessionId != this._sessionId) { this._logger.warn("ptt not equal"); return; } let para = { sender: this, state: msgObj.nqueue }; this._waitingStateChangeEmiiter.emit("event", para); }); this._iceClient.on(IceEventName.PttReject.toString(), (content) => { let msgObj = JSON.parse(content)[0]; let sessionId = msgObj.cid; // sessionId = sessionId.substring(0, sessionId.length -1); this._logger.warn("ptt reject, cid: " + sessionId + ", _cid: " + this._sessionId + "."); if (sessionId != this._sessionId) { this._logger.warn("ptt not equal"); return; } let para = { sender: this, state: msgObj.nqueue }; this._waitingStateChangeEmiiter.emit("event", para); }); } start(caller = LoginInfo.getInstance().number) { // let strMembers = new Array(); // this.members.forEach(element => { // strMembers.push(element.number); // }); return this._iceClient.startTempIntercom(this._initMembers, caller).then((result) => { this._logger.warn("createTempIntercom sucess " + JSON.stringify(result)); this.groupNumber = result.sessnum; return Promise.resolve(result); // this._sessionId = result.cid; }).catch((reason) => { return Promise.reject(reason); }); } applySpeak(caller = LoginInfo.getInstance().number) { // if (this.groupNumber != null) { return this._iceClient.applySpeak(this.groupNumber, caller).then((result) => { this._logger.log("apply speak sucess " + JSON.stringify(result)); // this._sessionId = result.cid; return Promise.resolve(result); }).catch((reason) => { return Promise.reject(reason); }); } applySpeakByLeftPhone() { return this.applySpeak(LoginInfo.getInstance().leftPhone); } applySpeakByRightPhone() { return this.applySpeak(LoginInfo.getInstance().rightPhone); } freeSpeak() { // // if (this.groupNumber != null) { // return this._iceClient.releaseSpeak(this.groupNumber).then((result: Dispatcher.CommonRequestT) => { // this._logger.log("free speak sucess " + JSON.stringify(result)); // }); // // } return this._iceClient.releaseSpeak(this.groupNumber).then((result) => { this._logger.log("free speak sucess " + JSON.stringify(result)); // this._sessionId = result.cid; return Promise.resolve(result); }).catch((reason) => { return Promise.reject(reason); }); } accept(mediaControl) { this._mediaControl = mediaControl; return this._sphone.answer2(this._callId, this._mediaControl, false, LoginInfo.getInstance().audioInputDeviceConfig.id, LoginInfo.getInstance().videoInputDeviceConfig.id); } end() { return this._iceClient.endConference(this._sessionId); } exit() { return this._iceClient.hangup(this._sessionId); } get stateChange() { return makeEmitter(this._stateChangeEmiiter); } get memberStateChange() { return makeEmitter(this._memberStateChangeEmiiter); } get speakerChanged() { return makeEmitter(this._speakerChangeEmiiter); } get waitingStateChanged() { return makeEmitter(this._waitingStateChangeEmiiter); } set stateice(state) { let confState = this.state; switch (state) { case "1": // callState = CallState.Init; break; case "2": // callState = CallState.Normal; break; case "3": confState = IntercomState.Connecting; break; case "4": break; case "5": break; case "6": confState = IntercomState.Connected; break; case "7": break; case "10": confState = IntercomState.Terminaled; break; case "14": break; default: break; } this.stateInternal = confState; } set stateInternal(v) { if (this.state != v) { if (v == IntercomState.Connected) { this.getMembers(); } this.state = v; let para = { sender: this, state: this.state }; this._stateChangeEmiiter.emit("event", para); // this._eventEmitter.emit(CallEventName.CallState.toString(), this, this._state ); } } get members() { // this._members = new Array(); this.getMembers(); return this._members; } getMembers() { return this._iceClient.getConfMembers(this._sessionId).then((results) => { this._logger.warn("getMembers success: " + JSON.stringify(results)); results.forEach(element => { if (element.state == Dispatcher.CallState.CallStateConnect) { let member = { number: element.employeeid, name: element.name }; this._members[member.number] = member; } }); return Promise.resolve(this._members); }).catch((error) => { this._logger.warn("getMembers fail :" + JSON.stringify(error)); return Promise.resolve(this._members); }); } } /** * 广播状态 */ var BroadcastState; (function(BroadcastState) { /** * 0 无 */ BroadcastState[BroadcastState["None"] = 0] = "None"; /** * 1 正常连接 */ BroadcastState[BroadcastState["Connecting"] = 1] = "Connecting"; /** * 2 已经接通 */ BroadcastState[BroadcastState["Connected"] = 2] = "Connected"; /** * 3 踢出 */ BroadcastState[BroadcastState["Kickout"] = 3] = "Kickout"; /** * 4 结束 */ BroadcastState[BroadcastState["Terminaled"] = 4] = "Terminaled"; /** * 5 离开 */ BroadcastState[BroadcastState["Leave"] = 5] = "Leave"; })(BroadcastState || (BroadcastState = {})); /** * 广播成员状态 */ var BroadcastMemberState; (function(BroadcastMemberState) { /** * 0 入会 */ BroadcastMemberState[BroadcastMemberState["Enter"] = 0] = "Enter"; /** * 1 离会 */ BroadcastMemberState[BroadcastMemberState["Leave"] = 1] = "Leave"; /** * 2 解除禁言 */ BroadcastMemberState[BroadcastMemberState["Speak"] = 2] = "Speak"; /** * 3 禁言 */ BroadcastMemberState[BroadcastMemberState["Unspeak"] = 3] = "Unspeak"; /** * 4 解除禁听 */ BroadcastMemberState[BroadcastMemberState["listen"] = 4] = "listen"; /** * 5 禁听 */ BroadcastMemberState[BroadcastMemberState["unlisten"] = 5] = "unlisten"; /** * 6 拒绝入会 */ BroadcastMemberState[BroadcastMemberState["Reject"] = 6] = "Reject"; /** * 7 响铃 */ BroadcastMemberState[BroadcastMemberState["ringing"] = 7] = "ringing"; /** * 8 已经连接入会 */ BroadcastMemberState[BroadcastMemberState["connected"] = 8] = "connected"; })(BroadcastMemberState || (BroadcastMemberState = {})); class BroadcastImp { constructor(mediaControl, members, name, iceClient, sphone) { this._logger = Logger.getInstance(); this._stateChangeEmiiter = new EventEmitter(); this._memberStateChangeEmiiter = new EventEmitter(); this._members = {}; this._pushAudioToRTSPState = PushAudioToRTSPState.stop; this._pushAudioToRTSPStateEmitter = new EventEmitter(); this._mediaControl = mediaControl; this.name = name; this._iceClient = iceClient; this._sphone = sphone; this._initMembers = members; // this._iceClient.on(IceEventName.SessionMemberChange.toString(), (content: string) => { // this._logger.warn("sessionMemberChange: " + content); // let sessionState = JSON.parse(content); // let sessionId = sessionState[0].cid; // if (sessionId != this._sessionId) { // return; // } // let state = sessionState[0].state; // let member = sessionState[0].employeeid; // let name = sessionState[0].name; // let existMember = this._members[member]; // let para; // switch (state) { // case "6": // if (existMember == null) { // let existMember = { number: member, name: name}; // this._members[member] = existMember; // para = { sender: this, state: BroadcastMemberState.Enter, member: member }; // this._memberStateChangeEmiiter.emit("event", para); // } // break; // case "10": // if (existMember != null) { // delete this._members[member]; // para = { sender: this, state: BroadcastMemberState.Leave, member: member }; // this._memberStateChangeEmiiter.emit("event", para); // } // break; // default: // break; // } // }); this._iceClient.on(IceEventName.SessionMemberChange.toString(), (content) => { // this._logger.warn("sessionMemberChange: " + content); if (this.state == BroadcastState.Terminaled || this.state == BroadcastState.Kickout || this.state == BroadcastState.Leave) { this._logger.warn("not in conference"); return; } let sessionState = JSON.parse(content); let sessionId = sessionState[0].cid; if (sessionId != this._sessionId) { return; } let state = sessionState[0].state; let member = sessionState[0].employeeid; let name = sessionState[0].name; let existMember = this._members[member]; let para; let callState = iceAPI.convertIceCallState1(state); let notSpeak = sessionState[0].notspeak; let allowListen; let notHear = sessionState[0].nothear; if (notHear == "0") { allowListen = true; } else { allowListen = false; } let preState = CallState.None; if (existMember == null) { existMember = { number: member, name: name, allowListen: allowListen, callState: callState }; this._members[member] = existMember; para = { sender: this, state: BroadcastMemberState.Enter, member: member }; this._memberStateChangeEmiiter.emit("event", para); } else { preState = existMember.callState; existMember.callState = callState; } switch (state) { case "1": // if (existMember == null) { para = { sender: this, state: BroadcastMemberState.ringing, member: member }; this._memberStateChangeEmiiter.emit("event", para); // } break; case "6": if (preState != CallState.Connect) { para = { sender: this, state: BroadcastMemberState.connected, member: member }; this._memberStateChangeEmiiter.emit("event", para); } else { // if (allowSpeak != existMember.allowSpeak) { // existMember.allowSpeak = allowSpeak; // let memberState = BroadcastMemberState.Speak; // if (!allowSpeak) { // memberState = BroadcastMemberState.Unspeak; // } // para = { sender: this, state: memberState, member: member }; // this._memberStateChangeEmiiter.emit("event", para); // } if (allowListen != existMember.allowListen) { existMember.allowListen = allowListen; let memberState = BroadcastMemberState.listen; if (!allowListen) { memberState = BroadcastMemberState.unlisten; } para = { sender: this, state: memberState, member: member }; this._memberStateChangeEmiiter.emit("event", para); } } break; case "10": if (existMember != null) { delete this._members[member]; para = { sender: this, state: BroadcastMemberState.Leave, member: member }; this._memberStateChangeEmiiter.emit("event", para); } // else { // para = { sender: this, state: BroadcastMemberState.Reject, member: member }; // this._memberStateChangeEmiiter.emit("event", para); // } break; default: break; } }); } get sessionId() { return this._sessionId; } start(caller = LoginInfo.getInstance().number) { // let strMembers = new Array(); // this.members.forEach(element => { // strMembers.push(element.number); // }); // return this._iceClient.startBroadcast(this._initMembers, caller); return this._iceClient.startBroadcast(this._initMembers, caller).then((result) => { this._logger.warn("createBroadcast sucess " + JSON.stringify(result)); this._sessionId = result.cid; }); } accept(mediaControl) { this._mediaControl = mediaControl; // this._sphone.answer2(this._callId, this._mediaControl as HTMLVideoElement, false, LoginInfo.getInstance().audioInputDeviceConfig.id, LoginInfo.getInstance().videoInputDeviceConfig.id); return this._sphone.answer2(this._callId, this._mediaControl, false, LoginInfo.getInstance().audioInputDeviceConfig.id, LoginInfo.getInstance().videoInputDeviceConfig.id, LoginInfo.getInstance().videoInputDeviceConfig.width, LoginInfo.getInstance().videoInputDeviceConfig.height, LoginInfo.getInstance().videoInputDeviceConfig.frameRate); } end() { return this._iceClient.endConference(this._sessionId); } exit() { // this.removeListeners && this.removeListeners(); // this.stateInternal = ConferenceState.Leave; // return this._sphone.hangup1(this._callId) return this._iceClient.hangup(this._sessionId); } get stateChange() { return makeEmitter(this._stateChangeEmiiter); } get memberStateChange() { return makeEmitter(this._memberStateChangeEmiiter); } set stateice(state) { let confState = this.state; switch (state) { case "1": // callState = CallState.Init; break; case "2": // callState = CallState.Normal; break; case "3": confState = BroadcastState.Connecting; break; case "4": break; case "5": break; case "6": confState = BroadcastState.Connected; break; case "7": break; case "10": confState = BroadcastState.Terminaled; break; case "14": break; default: break; } this.stateInternal = confState; } set stateInternal(v) { if (this.state != v) { if (v == BroadcastState.Connected) { this.getMembers(); } this.state = v; let para = { sender: this, state: this.state }; this._stateChangeEmiiter.emit("event", para); // this._eventEmitter.emit(CallEventName.CallState.toString(), this, this._state ); } } get members() { // this._members = new Array(); return this._members; } getMembers() { this._iceClient.getConfMembers(this._sessionId).then((results) => { this._logger.warn("getMembers success: " + JSON.stringify(results)); results.forEach(element => { let callState = element.state.value; let member = { number: element.employeeid, name: element.name, callState: callState, allowListen: true }; this._members[member.number] = member; }); }).catch((error) => { this._logger.warn("getMembers fail :" + JSON.stringify(error)); }); } add(number) { return this._iceClient.conferenceAddMember(this._sessionId, number); } remove(number) { return this._iceClient.conferenceDeleteMember(this._sessionId, number); } allowListen(member, allow) { return this._iceClient.allowListen(this._sessionId, member, allow); } get pushAudioToRTSPState() { return this._pushAudioToRTSPState; } set pushAudioToRTSPState(v) { if (this._pushAudioToRTSPState != v) { let para = { sender: this, state: v }; this._pushAudioToRTSPStateEmitter.emit("event", para); } this._pushAudioToRTSPState = v; } get pushAudioToRTSPStateChanged() { return makeEmitter(this._pushAudioToRTSPStateEmitter); } startPushRTSP(rtspUrl, codec) { return this._iceClient.PushStartCallAudio(this._sessionId, rtspUrl, codec); } stopPushRTSP() { return this._iceClient.PushStopCallAudio(this._sessionId); } } /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve) { resolve(value); }); } return new(P || (P = Promise))(function(resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function(v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } /** @deprecated */ function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } /** * FingerprintJS v3.1.2 - Copyright (c) FingerprintJS, Inc, 2021 (https://fingerprintjs.com) * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license. * * This software contains code from open-source projects: * MurmurHash3 by Karan Lyons (https://github.com/karanlyons/murmurHash3.js) */ /* * Taken from https://github.com/karanlyons/murmurHash3.js/blob/a33d0723127e2e5415056c455f8aed2451ace208/murmurHash3.js */ // // Given two 64bit ints (as an array of two 32bit ints) returns the two // added together as a 64bit int (as an array of two 32bit ints). // function x64Add(m, n) { m = [m[0] >>> 16, m[0] & 0xffff, m[1] >>> 16, m[1] & 0xffff]; n = [n[0] >>> 16, n[0] & 0xffff, n[1] >>> 16, n[1] & 0xffff]; var o = [0, 0, 0, 0]; o[3] += m[3] + n[3]; o[2] += o[3] >>> 16; o[3] &= 0xffff; o[2] += m[2] + n[2]; o[1] += o[2] >>> 16; o[2] &= 0xffff; o[1] += m[1] + n[1]; o[0] += o[1] >>> 16; o[1] &= 0xffff; o[0] += m[0] + n[0]; o[0] &= 0xffff; return [(o[0] << 16) | o[1], (o[2] << 16) | o[3]]; } // // Given two 64bit ints (as an array of two 32bit ints) returns the two // multiplied together as a 64bit int (as an array of two 32bit ints). // function x64Multiply(m, n) { m = [m[0] >>> 16, m[0] & 0xffff, m[1] >>> 16, m[1] & 0xffff]; n = [n[0] >>> 16, n[0] & 0xffff, n[1] >>> 16, n[1] & 0xffff]; var o = [0, 0, 0, 0]; o[3] += m[3] * n[3]; o[2] += o[3] >>> 16; o[3] &= 0xffff; o[2] += m[2] * n[3]; o[1] += o[2] >>> 16; o[2] &= 0xffff; o[2] += m[3] * n[2]; o[1] += o[2] >>> 16; o[2] &= 0xffff; o[1] += m[1] * n[3]; o[0] += o[1] >>> 16; o[1] &= 0xffff; o[1] += m[2] * n[2]; o[0] += o[1] >>> 16; o[1] &= 0xffff; o[1] += m[3] * n[1]; o[0] += o[1] >>> 16; o[1] &= 0xffff; o[0] += m[0] * n[3] + m[1] * n[2] + m[2] * n[1] + m[3] * n[0]; o[0] &= 0xffff; return [(o[0] << 16) | o[1], (o[2] << 16) | o[3]]; } // // Given a 64bit int (as an array of two 32bit ints) and an int // representing a number of bit positions, returns the 64bit int (as an // array of two 32bit ints) rotated left by that number of positions. // function x64Rotl(m, n) { n %= 64; if (n === 32) { return [m[1], m[0]]; } else if (n < 32) { return [(m[0] << n) | (m[1] >>> (32 - n)), (m[1] << n) | (m[0] >>> (32 - n))]; } else { n -= 32; return [(m[1] << n) | (m[0] >>> (32 - n)), (m[0] << n) | (m[1] >>> (32 - n))]; } } // // Given a 64bit int (as an array of two 32bit ints) and an int // representing a number of bit positions, returns the 64bit int (as an // array of two 32bit ints) shifted left by that number of positions. // function x64LeftShift(m, n) { n %= 64; if (n === 0) { return m; } else if (n < 32) { return [(m[0] << n) | (m[1] >>> (32 - n)), m[1] << n]; } else { return [m[1] << (n - 32), 0]; } } // // Given two 64bit ints (as an array of two 32bit ints) returns the two // xored together as a 64bit int (as an array of two 32bit ints). // function x64Xor(m, n) { return [m[0] ^ n[0], m[1] ^ n[1]]; } // // Given a block, returns murmurHash3's final x64 mix of that block. // (`[0, h[0] >>> 1]` is a 33 bit unsigned right shift. This is the // only place where we need to right shift 64bit ints.) // function x64Fmix(h) { h = x64Xor(h, [0, h[0] >>> 1]); h = x64Multiply(h, [0xff51afd7, 0xed558ccd]); h = x64Xor(h, [0, h[0] >>> 1]); h = x64Multiply(h, [0xc4ceb9fe, 0x1a85ec53]); h = x64Xor(h, [0, h[0] >>> 1]); return h; } // // Given a string and an optional seed as an int, returns a 128 bit // hash using the x64 flavor of MurmurHash3, as an unsigned hex. // function x64hash128(key, seed) { key = key || ''; seed = seed || 0; var remainder = key.length % 16; var bytes = key.length - remainder; var h1 = [0, seed]; var h2 = [0, seed]; var k1 = [0, 0]; var k2 = [0, 0]; var c1 = [0x87c37b91, 0x114253d5]; var c2 = [0x4cf5ad43, 0x2745937f]; var i; for (i = 0; i < bytes; i = i + 16) { k1 = [ (key.charCodeAt(i + 4) & 0xff) | ((key.charCodeAt(i + 5) & 0xff) << 8) | ((key.charCodeAt(i + 6) & 0xff) << 16) | ((key.charCodeAt(i + 7) & 0xff) << 24), (key.charCodeAt(i) & 0xff) | ((key.charCodeAt(i + 1) & 0xff) << 8) | ((key.charCodeAt(i + 2) & 0xff) << 16) | ((key.charCodeAt(i + 3) & 0xff) << 24), ]; k2 = [ (key.charCodeAt(i + 12) & 0xff) | ((key.charCodeAt(i + 13) & 0xff) << 8) | ((key.charCodeAt(i + 14) & 0xff) << 16) | ((key.charCodeAt(i + 15) & 0xff) << 24), (key.charCodeAt(i + 8) & 0xff) | ((key.charCodeAt(i + 9) & 0xff) << 8) | ((key.charCodeAt(i + 10) & 0xff) << 16) | ((key.charCodeAt(i + 11) & 0xff) << 24), ]; k1 = x64Multiply(k1, c1); k1 = x64Rotl(k1, 31); k1 = x64Multiply(k1, c2); h1 = x64Xor(h1, k1); h1 = x64Rotl(h1, 27); h1 = x64Add(h1, h2); h1 = x64Add(x64Multiply(h1, [0, 5]), [0, 0x52dce729]); k2 = x64Multiply(k2, c2); k2 = x64Rotl(k2, 33); k2 = x64Multiply(k2, c1); h2 = x64Xor(h2, k2); h2 = x64Rotl(h2, 31); h2 = x64Add(h2, h1); h2 = x64Add(x64Multiply(h2, [0, 5]), [0, 0x38495ab5]); } k1 = [0, 0]; k2 = [0, 0]; switch (remainder) { case 15: k2 = x64Xor(k2, x64LeftShift([0, key.charCodeAt(i + 14)], 48)); // fallthrough case 14: k2 = x64Xor(k2, x64LeftShift([0, key.charCodeAt(i + 13)], 40)); // fallthrough case 13: k2 = x64Xor(k2, x64LeftShift([0, key.charCodeAt(i + 12)], 32)); // fallthrough case 12: k2 = x64Xor(k2, x64LeftShift([0, key.charCodeAt(i + 11)], 24)); // fallthrough case 11: k2 = x64Xor(k2, x64LeftShift([0, key.charCodeAt(i + 10)], 16)); // fallthrough case 10: k2 = x64Xor(k2, x64LeftShift([0, key.charCodeAt(i + 9)], 8)); // fallthrough case 9: k2 = x64Xor(k2, [0, key.charCodeAt(i + 8)]); k2 = x64Multiply(k2, c2); k2 = x64Rotl(k2, 33); k2 = x64Multiply(k2, c1); h2 = x64Xor(h2, k2); // fallthrough case 8: k1 = x64Xor(k1, x64LeftShift([0, key.charCodeAt(i + 7)], 56)); // fallthrough case 7: k1 = x64Xor(k1, x64LeftShift([0, key.charCodeAt(i + 6)], 48)); // fallthrough case 6: k1 = x64Xor(k1, x64LeftShift([0, key.charCodeAt(i + 5)], 40)); // fallthrough case 5: k1 = x64Xor(k1, x64LeftShift([0, key.charCodeAt(i + 4)], 32)); // fallthrough case 4: k1 = x64Xor(k1, x64LeftShift([0, key.charCodeAt(i + 3)], 24)); // fallthrough case 3: k1 = x64Xor(k1, x64LeftShift([0, key.charCodeAt(i + 2)], 16)); // fallthrough case 2: k1 = x64Xor(k1, x64LeftShift([0, key.charCodeAt(i + 1)], 8)); // fallthrough case 1: k1 = x64Xor(k1, [0, key.charCodeAt(i)]); k1 = x64Multiply(k1, c1); k1 = x64Rotl(k1, 31); k1 = x64Multiply(k1, c2); h1 = x64Xor(h1, k1); // fallthrough } h1 = x64Xor(h1, [0, key.length]); h2 = x64Xor(h2, [0, key.length]); h1 = x64Add(h1, h2); h2 = x64Add(h2, h1); h1 = x64Fmix(h1); h2 = x64Fmix(h2); h1 = x64Add(h1, h2); h2 = x64Add(h2, h1); return (('00000000' + (h1[0] >>> 0).toString(16)).slice(-8) + ('00000000' + (h1[1] >>> 0).toString(16)).slice(-8) + ('00000000' + (h2[0] >>> 0).toString(16)).slice(-8) + ('00000000' + (h2[1] >>> 0).toString(16)).slice(-8)); } var version = "3.1.2"; function wait(durationMs, resolveWith) { return new Promise(function(resolve) { return setTimeout(resolve, durationMs, resolveWith); }); } function requestIdleCallbackIfAvailable(fallbackTimeout, deadlineTimeout) { if (deadlineTimeout === void 0) { deadlineTimeout = Infinity; } var requestIdleCallback = window.requestIdleCallback; if (requestIdleCallback) { return new Promise(function(resolve) { return requestIdleCallback(function() { return resolve(); }, { timeout: deadlineTimeout }); }); } else { return wait(Math.min(fallbackTimeout, deadlineTimeout)); } } /** * Converts an error object to a plain object that can be used with `JSON.stringify`. * If you just run `JSON.stringify(error)`, you'll get `'{}'`. */ function errorToObject(error) { var _a; return __assign({ name: error.name, message: error.message, stack: (_a = error.stack) === null || _a === void 0 ? void 0 : _a.split('\n') }, error); } /* * This file contains functions to work with pure data only (no browser features, DOM, side effects, etc). */ /** * Does the same as Array.prototype.includes but has better typing */ function includes(haystack, needle) { for (var i = 0, l = haystack.length; i < l; ++i) { if (haystack[i] === needle) { return true; } } return false; } /** * Like `!includes()` but with proper typing */ function excludes(haystack, needle) { return !includes(haystack, needle); } /** * Be careful, NaN can return */ function toInt(value) { return parseInt(value); } /** * Be careful, NaN can return */ function toFloat(value) { return parseFloat(value); } function replaceNaN(value, replacement) { return typeof value === 'number' && isNaN(value) ? replacement : value; } function countTruthy(values) { return values.reduce(function(sum, value) { return sum + (value ? 1 : 0); }, 0); } function round(value, base) { if (base === void 0) { base = 1; } if (Math.abs(base) >= 1) { return Math.round(value / base) * base; } else { // Sometimes when a number is multiplied by a small number, precision is lost, // for example 1234 * 0.0001 === 0.12340000000000001, and it's more precise divide: 1234 / (1 / 0.0001) === 0.1234. var counterBase = 1 / base; return Math.round(value * counterBase) / counterBase; } } /** * Parses a CSS selector into tag name with HTML attributes. * Only single element selector are supported (without operators like space, +, >, etc). * * Multiple values can be returned for each attribute. You decide how to handle them. */ function parseSimpleCssSelector(selector) { var _a, _b; var errorMessage = "Unexpected syntax '" + selector + "'"; var tagMatch = /^\s*([a-z-]*)(.*)$/i.exec(selector); var tag = tagMatch[1] || undefined; var attributes = {}; var partsRegex = /([.:#][\w-]+|\[.+?\])/gi; var addAttribute = function(name, value) { attributes[name] = attributes[name] || []; attributes[name].push(value); }; for (;;) { var match = partsRegex.exec(tagMatch[2]); if (!match) { break; } var part = match[0]; switch (part[0]) { case '.': addAttribute('class', part.slice(1)); break; case '#': addAttribute('id', part.slice(1)); break; case '[': { var attributeMatch = /^\[([\w-]+)([~|^$*]?=("(.*?)"|([\w-]+)))?(\s+[is])?\]$/.exec(part); if (attributeMatch) { addAttribute(attributeMatch[1], (_b = (_a = attributeMatch[4]) !== null && _a !== void 0 ? _a : attributeMatch[5]) !== null && _b !== void 0 ? _b : ''); } else { throw new Error(errorMessage); } break; } default: throw new Error(errorMessage); } } return [tag, attributes]; } /* * Functions to help with features that vary through browsers */ /** * Checks whether the browser is based on Trident (the Internet Explorer engine) without using user-agent. * * Warning for package users: * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk. */ function isTrident() { var w = window; var n = navigator; // The properties are checked to be in IE 10, IE 11 and not to be in other browsers in October 2020 return (countTruthy([ 'MSCSSMatrix' in w, 'msSetImmediate' in w, 'msIndexedDB' in w, 'msMaxTouchPoints' in n, 'msPointerEnabled' in n, ]) >= 4); } /** * Checks whether the browser is based on EdgeHTML (the pre-Chromium Edge engine) without using user-agent. * * Warning for package users: * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk. */ function isEdgeHTML() { // Based on research in October 2020 var w = window; var n = navigator; return (countTruthy(['msWriteProfilerMark' in w, 'MSStream' in w, 'msLaunchUri' in n, 'msSaveBlob' in n]) >= 3 && !isTrident()); } /** * Checks whether the browser is based on Chromium without using user-agent. * * Warning for package users: * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk. */ function isChromium() { // Based on research in October 2020. Tested to detect Chromium 42-86. var w = window; var n = navigator; return (countTruthy([ 'webkitPersistentStorage' in n, 'webkitTemporaryStorage' in n, n.vendor.indexOf('Google') === 0, 'webkitResolveLocalFileSystemURL' in w, 'BatteryManager' in w, 'webkitMediaStream' in w, 'webkitSpeechGrammar' in w, ]) >= 5); } /** * Checks whether the browser is based on mobile or desktop Safari without using user-agent. * All iOS browsers use WebKit (the Safari engine). * * Warning for package users: * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk. */ function isWebKit() { // Based on research in September 2020 var w = window; var n = navigator; return (countTruthy([ 'ApplePayError' in w, 'CSSPrimitiveValue' in w, 'Counter' in w, n.vendor.indexOf('Apple') === 0, 'getStorageUpdates' in n, 'WebKitMediaKeys' in w, ]) >= 4); } /** * Checks whether the WebKit browser is a desktop Safari. * * Warning for package users: * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk. */ function isDesktopSafari() { var w = window; return (countTruthy([ 'safari' in w, !('DeviceMotionEvent' in w), !('ongestureend' in w), !('standalone' in navigator), ]) >= 3); } /** * Checks whether the browser is based on Gecko (Firefox engine) without using user-agent. * * Warning for package users: * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk. */ function isGecko() { var _a, _b; var w = window; // Based on research in September 2020 return (countTruthy([ 'buildID' in navigator, 'MozAppearance' in ((_b = (_a = document.documentElement) === null || _a === void 0 ? void 0 : _a.style) !== null && _b !== void 0 ? _b : {}), 'MediaRecorderErrorEvent' in w, 'mozInnerScreenX' in w, 'CSSMozDocumentRule' in w, 'CanvasCaptureMediaStream' in w, ]) >= 4); } /** * Checks whether the browser is based on Chromium version ≥86 without using user-agent. * It doesn't check that the browser is based on Chromium, there is a separate function for this. */ function isChromium86OrNewer() { // Checked in Chrome 85 vs Chrome 86 both on desktop and Android var w = window; return (countTruthy([!('MediaSettingsRange' in w), 'RTCEncodedAudioFrame' in w, '' + w.Intl === '[object Intl]', '' + w.Reflect === '[object Reflect]', ]) >= 3); } /** * Checks whether the browser is based on WebKit version ≥606 (Safari ≥12) without using user-agent. * It doesn't check that the browser is based on WebKit, there is a separate function for this. * * @link https://en.wikipedia.org/wiki/Safari_version_history#Release_history Safari-WebKit versions map */ function isWebKit606OrNewer() { // Checked in Safari 9–14 var w = window; return (countTruthy([ 'DOMRectList' in w, 'RTCPeerConnectionIceEvent' in w, 'SVGGeometryElement' in w, 'ontransitioncancel' in w, ]) >= 3); } /** * Checks whether the device is an iPad. * It doesn't check that the engine is WebKit and that the WebKit isn't desktop. */ function isIPad() { // Checked on: // Safari on iPadOS (both mobile and desktop modes): 8, 11, 12, 13, 14 // Chrome on iPadOS (both mobile and desktop modes): 11, 12, 13, 14 // Safari on iOS (both mobile and desktop modes): 9, 10, 11, 12, 13, 14 // Chrome on iOS (both mobile and desktop modes): 9, 10, 11, 12, 13, 14 // Before iOS 13. Safari tampers the value in "request desktop site" mode since iOS 13. if (navigator.platform === 'iPad') { return true; } var s = screen; var screenRatio = s.width / s.height; return (countTruthy([ 'MediaSource' in window, !!Element.prototype.webkitRequestFullscreen, screenRatio > 2 / 3 && screenRatio < 3 / 2, ]) >= 2); } /** * Warning for package users: * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk. */ function getFullscreenElement() { var d = document; return d.fullscreenElement || d.msFullscreenElement || d.mozFullScreenElement || d.webkitFullscreenElement || null; } function exitFullscreen() { var d = document; // `call` is required because the function throws an error without a proper "this" context return (d.exitFullscreen || d.msExitFullscreen || d.mozCancelFullScreen || d.webkitExitFullscreen).call(d); } /** * Checks whether the device runs on Android without using user-agent. */ function isAndroid() { var isItChromium = isChromium(); var isItGecko = isGecko(); // Only 2 browser engines are presented on Android. // Actually, there is also Android 4.1 browser, but it's not worth detecting it at the moment. if (!isItChromium && !isItGecko) { return false; } var w = window; // Chrome removes all words "Android" from `navigator` when desktop version is requested // Firefox keeps "Android" in `navigator.appVersion` when desktop version is requested return (countTruthy([ 'onorientationchange' in w, 'orientation' in w, isItChromium && 'SharedWorker' in w, isItGecko && /android/i.test(navigator.appVersion), ]) >= 2); } /** * A deep description: https://fingerprintjs.com/blog/audio-fingerprinting/ * Inspired by and based on https://github.com/cozylife/audio-fingerprint */ function getAudioFingerprint() { return __awaiter(this, void 0, void 0, function() { var w, AudioContext, hashFromIndex, hashToIndex, context, oscillator, compressor, buffer, error_1; return __generator(this, function(_a) { switch (_a.label) { case 0: w = window; AudioContext = w.OfflineAudioContext || w.webkitOfflineAudioContext; if (!AudioContext) { return [2 /*return*/ , -2 /* NotSupported */ ]; } // In some browsers, audio context always stays suspended unless the context is started in response to a user action // (e.g. a click or a tap). It prevents audio fingerprint from being taken at an arbitrary moment of time. // Such browsers are old and unpopular, so the audio fingerprinting is just skipped in them. // See a similar case explanation at https://stackoverflow.com/questions/46363048/onaudioprocess-not-called-on-ios11#46534088 if (doesCurrentBrowserSuspendAudioContext()) { return [2 /*return*/ , -1 /* KnownToSuspend */ ]; } hashFromIndex = 4500; hashToIndex = 5000; context = new AudioContext(1, hashToIndex, 44100); oscillator = context.createOscillator(); oscillator.type = 'triangle'; oscillator.frequency.value = 10000; compressor = context.createDynamicsCompressor(); compressor.threshold.value = -50; compressor.knee.value = 40; compressor.ratio.value = 12; compressor.attack.value = 0; compressor.release.value = 0.25; oscillator.connect(compressor); compressor.connect(context.destination); oscillator.start(0); _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/ , renderAudio(context)]; case 2: buffer = _a.sent(); return [3 /*break*/ , 4]; case 3: error_1 = _a.sent(); if (error_1.name === "timeout" /* Timeout */ || error_1.name === "suspended" /* Suspended */ ) { return [2 /*return*/ , -3 /* Timeout */ ]; } throw error_1; case 4: return [2 /*return*/ , getHash(buffer.getChannelData(0).subarray(hashFromIndex))]; } }); }); } /** * Checks if the current browser is known to always suspend audio context */ function doesCurrentBrowserSuspendAudioContext() { return isWebKit() && !isDesktopSafari() && !isWebKit606OrNewer(); } function renderAudio(context) { var resumeTriesMaxCount = 3; var resumeRetryDelay = 500; var runningTimeout = 1000; return new Promise(function(resolve, reject) { context.oncomplete = function(event) { return resolve(event.renderedBuffer); }; var resumeTriesLeft = resumeTriesMaxCount; var tryResume = function() { context.startRendering(); switch (context.state) { case 'running': setTimeout(function() { return reject(makeInnerError("timeout" /* Timeout */ )); }, runningTimeout); break; // Sometimes the audio context doesn't start after calling `startRendering` (in addition to the cases where // audio context doesn't start at all). A known case is starting an audio context when the browser tab is in // background on iPhone. Retries usually help in this case. case 'suspended': // The audio context can reject starting until the tab is in foreground. Long fingerprint duration // in background isn't a problem, therefore the retry attempts don't count in background. It can lead to // a situation when a fingerprint takes very long time and finishes successfully. FYI, the audio context // can be suspended when `document.hidden === false` and start running after a retry. if (!document.hidden) { resumeTriesLeft--; } if (resumeTriesLeft > 0) { setTimeout(tryResume, resumeRetryDelay); } else { reject(makeInnerError("suspended" /* Suspended */ )); } break; } }; tryResume(); }); } function getHash(signal) { var hash = 0; for (var i = 0; i < signal.length; ++i) { hash += Math.abs(signal[i]); } return hash; } function makeInnerError(name) { var error = new Error(name); error.name = name; return error; } /** * Creates and keeps an invisible iframe while the given function runs. * The given function is called when the iframe is loaded and has a body. * The iframe allows to measure DOM sizes inside itself. * * Notice: passing an initial HTML code doesn't work in IE. * * Warning for package users: * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk. */ function withIframe(action, initialHtml, domPollInterval) { var _a, _b; if (domPollInterval === void 0) { domPollInterval = 50; } return __awaiter(this, void 0, void 0, function() { var d, iframe; return __generator(this, function(_c) { switch (_c.label) { case 0: d = document; _c.label = 1; case 1: if (!!d.body) return [3 /*break*/ , 3]; return [4 /*yield*/ , wait(domPollInterval)]; case 2: _c.sent(); return [3 /*break*/ , 1]; case 3: iframe = d.createElement('iframe'); _c.label = 4; case 4: _c.trys.push([4, , 10, 11]); return [4 /*yield*/ , new Promise(function(resolve, reject) { iframe.onload = resolve; iframe.onerror = reject; var style = iframe.style; style.setProperty('display', 'block', 'important'); // Required for browsers to calculate the layout style.position = 'absolute'; style.top = '0'; style.left = '0'; style.visibility = 'hidden'; d.body.appendChild(iframe); // The order is important here. // The `iframe.srcdoc = ...` expression must go after the `body.appendChild(iframe)` expression, // otherwise the iframe will never load nor fail in WeChat built-in browser. // See https://github.com/fingerprintjs/fingerprintjs/issues/645#issuecomment-828189330 if (initialHtml && 'srcdoc' in iframe) { iframe.srcdoc = initialHtml; } else { iframe.src = 'about:blank'; } })]; case 5: _c.sent(); _c.label = 6; case 6: if (!!((_a = iframe.contentWindow) === null || _a === void 0 ? void 0 : _a.document.body)) return [3 /*break*/ , 8]; return [4 /*yield*/ , wait(domPollInterval)]; case 7: _c.sent(); return [3 /*break*/ , 6]; case 8: return [4 /*yield*/ , action(iframe, iframe.contentWindow)]; case 9: return [2 /*return*/ , _c.sent()]; case 10: (_b = iframe.parentNode) === null || _b === void 0 ? void 0 : _b.removeChild(iframe); return [7 /*endfinally*/ ]; case 11: return [2 /*return*/ ]; } }); }); } /** * Creates a DOM element that matches the given selector. * Only single element selector are supported (without operators like space, +, >, etc). */ function selectorToElement(selector) { var _a = parseSimpleCssSelector(selector), tag = _a[0], attributes = _a[1]; var element = document.createElement(tag !== null && tag !== void 0 ? tag : 'div'); for (var _i = 0, _b = Object.keys(attributes); _i < _b.length; _i++) { var name_1 = _b[_i]; element.setAttribute(name_1, attributes[name_1].join(' ')); } return element; } // We use m or w because these two characters take up the maximum width. // And we use a LLi so that the same matching fonts can get separated. var testString = 'mmMwWLliI0O&1'; // We test using 48px font size, we may use any size. I guess larger the better. var textSize = '48px'; // A font will be compared against all the three default fonts. // And if it doesn't match all 3 then that font is not available. var baseFonts = ['monospace', 'sans-serif', 'serif']; var fontList = [ // This is android-specific font from "Roboto" family 'sans-serif-thin', 'ARNO PRO', 'Agency FB', 'Arabic Typesetting', 'Arial Unicode MS', 'AvantGarde Bk BT', 'BankGothic Md BT', 'Batang', 'Bitstream Vera Sans Mono', 'Calibri', 'Century', 'Century Gothic', 'Clarendon', 'EUROSTILE', 'Franklin Gothic', 'Futura Bk BT', 'Futura Md BT', 'GOTHAM', 'Gill Sans', 'HELV', 'Haettenschweiler', 'Helvetica Neue', 'Humanst521 BT', 'Leelawadee', 'Letter Gothic', 'Levenim MT', 'Lucida Bright', 'Lucida Sans', 'Menlo', 'MS Mincho', 'MS Outlook', 'MS Reference Specialty', 'MS UI Gothic', 'MT Extra', 'MYRIAD PRO', 'Marlett', 'Meiryo UI', 'Microsoft Uighur', 'Minion Pro', 'Monotype Corsiva', 'PMingLiU', 'Pristina', 'SCRIPTINA', 'Segoe UI Light', 'Serifa', 'SimHei', 'Small Fonts', 'Staccato222 BT', 'TRAJAN PRO', 'Univers CE 55 Medium', 'Vrinda', 'ZWAdobeF', ]; // kudos to http://www.lalit.org/lab/javascript-css-font-detect/ function getFonts() { // Running the script in an iframe makes it not affect the page look and not be affected by the page CSS. See: // https://github.com/fingerprintjs/fingerprintjs/issues/592 // https://github.com/fingerprintjs/fingerprintjs/issues/628 return withIframe(function(_, _a) { var document = _a.document; var holder = document.body; holder.style.fontSize = textSize; // div to load spans for the default fonts and the fonts to detect var spansContainer = document.createElement('div'); var defaultWidth = {}; var defaultHeight = {}; // creates a span where the fonts will be loaded var createSpan = function(fontFamily) { var span = document.createElement('span'); var style = span.style; style.position = 'absolute'; style.top = '0'; style.left = '0'; style.fontFamily = fontFamily; span.textContent = testString; spansContainer.appendChild(span); return span; }; // creates a span and load the font to detect and a base font for fallback var createSpanWithFonts = function(fontToDetect, baseFont) { return createSpan("'" + fontToDetect + "'," + baseFont); }; // creates spans for the base fonts and adds them to baseFontsDiv var initializeBaseFontsSpans = function() { return baseFonts.map(createSpan); }; // creates spans for the fonts to detect and adds them to fontsDiv var initializeFontsSpans = function() { // Stores {fontName : [spans for that font]} var spans = {}; var _loop_1 = function(font) { spans[font] = baseFonts.map(function(baseFont) { return createSpanWithFonts(font, baseFont); }); }; for (var _i = 0, fontList_1 = fontList; _i < fontList_1.length; _i++) { var font = fontList_1[_i]; _loop_1(font); } return spans; }; // checks if a font is available var isFontAvailable = function(fontSpans) { return baseFonts.some(function(baseFont, baseFontIndex) { return fontSpans[baseFontIndex].offsetWidth !== defaultWidth[baseFont] || fontSpans[baseFontIndex].offsetHeight !== defaultHeight[baseFont]; }); }; // create spans for base fonts var baseFontsSpans = initializeBaseFontsSpans(); // create spans for fonts to detect var fontsSpans = initializeFontsSpans(); // add all the spans to the DOM holder.appendChild(spansContainer); // get the default width for the three base fonts for (var index = 0; index < baseFonts.length; index++) { defaultWidth[baseFonts[index]] = baseFontsSpans[index].offsetWidth; // width for the default font defaultHeight[baseFonts[index]] = baseFontsSpans[index].offsetHeight; // height for the default font } // check available fonts return fontList.filter(function(font) { return isFontAvailable(fontsSpans[font]); }); }); } function getPlugins() { var rawPlugins = navigator.plugins; if (!rawPlugins) { return undefined; } var plugins = []; // Safari 10 doesn't support iterating navigator.plugins with for...of for (var i = 0; i < rawPlugins.length; ++i) { var plugin = rawPlugins[i]; if (!plugin) { continue; } var mimeTypes = []; for (var j = 0; j < plugin.length; ++j) { var mimeType = plugin[j]; mimeTypes.push({ type: mimeType.type, suffixes: mimeType.suffixes, }); } plugins.push({ name: plugin.name, description: plugin.description, mimeTypes: mimeTypes, }); } return plugins; } // https://www.browserleaks.com/canvas#how-does-it-work function getCanvasFingerprint() { var _a = makeCanvasContext(), canvas = _a[0], context = _a[1]; if (!isSupported(canvas, context)) { return { winding: false, geometry: '', text: '' }; } return { winding: doesSupportWinding(context), geometry: makeGeometryImage(canvas, context), // Text is unstable: // https://github.com/fingerprintjs/fingerprintjs/issues/583 // https://github.com/fingerprintjs/fingerprintjs/issues/103 // Therefore it's extracted into a separate image. text: makeTextImage(canvas, context), }; } function makeCanvasContext() { var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = 1; return [canvas, canvas.getContext('2d')]; } function isSupported(canvas, context) { // TODO: look into: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob return !!(context && canvas.toDataURL); } function doesSupportWinding(context) { // https://web.archive.org/web/20170825024655/http://blogs.adobe.com/webplatform/2013/01/30/winding-rules-in-canvas/ // https://github.com/Modernizr/Modernizr/blob/master/feature-detects/canvas/winding.js context.rect(0, 0, 10, 10); context.rect(2, 2, 6, 6); return !context.isPointInPath(5, 5, 'evenodd'); } function makeTextImage(canvas, context) { // Resizing the canvas cleans it canvas.width = 240; canvas.height = 60; context.textBaseline = 'alphabetic'; context.fillStyle = '#f60'; context.fillRect(100, 1, 62, 20); context.fillStyle = '#069'; // It's important to use explicit built-in fonts in order to exclude the affect of font preferences // (there is a separate entropy source for them). context.font = '11pt "Times New Roman"'; // The choice of emojis has a gigantic impact on rendering performance (especially in FF). // Some newer emojis cause it to slow down 50-200 times. // There must be no text to the right of the emoji, see https://github.com/fingerprintjs/fingerprintjs/issues/574 // A bare emoji shouldn't be used because the canvas will change depending on the script encoding: // https://github.com/fingerprintjs/fingerprintjs/issues/66 // Escape sequence shouldn't be used too because Terser will turn it into a bare unicode. var printedText = "Cwm fjordbank gly " + String.fromCharCode(55357, 56835) /* 😃 */ ; context.fillText(printedText, 2, 15); context.fillStyle = 'rgba(102, 204, 0, 0.2)'; context.font = '18pt Arial'; context.fillText(printedText, 4, 45); return save(canvas); } function makeGeometryImage(canvas, context) { // Resizing the canvas cleans it canvas.width = 122; canvas.height = 110; // Canvas blending // https://web.archive.org/web/20170826194121/http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/ // http://jsfiddle.net/NDYV8/16/ context.globalCompositeOperation = 'multiply'; for (var _i = 0, _a = [ ['#f2f', 40, 40], ['#2ff', 80, 40], ['#ff2', 60, 80], ]; _i < _a.length; _i++) { var _b = _a[_i], color = _b[0], x = _b[1], y = _b[2]; context.fillStyle = color; context.beginPath(); context.arc(x, y, 40, 0, Math.PI * 2, true); context.closePath(); context.fill(); } // Canvas winding // http://blogs.adobe.com/webplatform/2013/01/30/winding-rules-in-canvas/ // http://jsfiddle.net/NDYV8/19/ context.fillStyle = '#f9c'; context.arc(60, 60, 60, 0, Math.PI * 2, true); context.arc(60, 60, 20, 0, Math.PI * 2, true); context.fill('evenodd'); return save(canvas); } function save(canvas) { // TODO: look into: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob return canvas.toDataURL(); } /** * This is a crude and primitive touch screen detection. It's not possible to currently reliably detect the availability * of a touch screen with a JS, without actually subscribing to a touch event. * * @see http://www.stucox.com/blog/you-cant-detect-a-touchscreen/ * @see https://github.com/Modernizr/Modernizr/issues/548 */ function getTouchSupport() { var n = navigator; var maxTouchPoints = 0; var touchEvent; if (n.maxTouchPoints !== undefined) { maxTouchPoints = toInt(n.maxTouchPoints); } else if (n.msMaxTouchPoints !== undefined) { maxTouchPoints = n.msMaxTouchPoints; } try { document.createEvent('TouchEvent'); touchEvent = true; } catch (_) { touchEvent = false; } var touchStart = 'ontouchstart' in window; return { maxTouchPoints: maxTouchPoints, touchEvent: touchEvent, touchStart: touchStart, }; } function getOsCpu() { return navigator.oscpu; } function getLanguages() { var n = navigator; var result = []; var language = n.language || n.userLanguage || n.browserLanguage || n.systemLanguage; if (language !== undefined) { result.push([language]); } if (Array.isArray(n.languages)) { // Starting from Chromium 86, there is only a single value in `navigator.language` in Incognito mode: // the value of `navigator.language`. Therefore the value is ignored in this browser. if (!(isChromium() && isChromium86OrNewer())) { result.push(n.languages); } } else if (typeof n.languages === 'string') { var languages = n.languages; if (languages) { result.push(languages.split(',')); } } return result; } function getColorDepth() { return window.screen.colorDepth; } function getDeviceMemory() { // `navigator.deviceMemory` is a string containing a number in some unidentified cases return replaceNaN(toFloat(navigator.deviceMemory), undefined); } function getScreenResolution() { var s = screen; // Some browsers return screen resolution as strings, e.g. "1200", instead of a number, e.g. 1200. // I suspect it's done by certain plugins that randomize browser properties to prevent fingerprinting. var dimensions = [toInt(s.width), toInt(s.height)]; dimensions.sort().reverse(); return dimensions; } var screenFrameCheckInterval = 2500; var roundingPrecision = 10; // The type is readonly to protect from unwanted mutations var screenFrameBackup; var screenFrameSizeTimeoutId; /** * Starts watching the screen frame size. When a non-zero size appears, the size is saved and the watch is stopped. * Later, when `getScreenFrame` is called, it will return the saved non-zero size if the current size is null. * * This trick is required to mitigate the fact that the screen frame turns null in some cases. * See more on this at https://github.com/fingerprintjs/fingerprintjs/issues/568 */ function watchScreenFrame() { if (screenFrameSizeTimeoutId !== undefined) { return; } var checkScreenFrame = function() { var frameSize = getCurrentScreenFrame(); if (isFrameSizeNull(frameSize)) { screenFrameSizeTimeoutId = setTimeout(checkScreenFrame, screenFrameCheckInterval); } else { screenFrameBackup = frameSize; screenFrameSizeTimeoutId = undefined; } }; checkScreenFrame(); } function getScreenFrame() { return __awaiter(this, void 0, void 0, function() { var frameSize; return __generator(this, function(_a) { switch (_a.label) { case 0: frameSize = getCurrentScreenFrame(); if (!isFrameSizeNull(frameSize)) return [3 /*break*/ , 2]; if (screenFrameBackup) { return [2 /*return*/ , __spreadArrays(screenFrameBackup)]; } if (!getFullscreenElement()) return [3 /*break*/ , 2]; // Some browsers set the screen frame to zero when programmatic fullscreen is on. // There is a chance of getting a non-zero frame after exiting the fullscreen. // See more on this at https://github.com/fingerprintjs/fingerprintjs/issues/568 return [4 /*yield*/ , exitFullscreen()]; case 1: // Some browsers set the screen frame to zero when programmatic fullscreen is on. // There is a chance of getting a non-zero frame after exiting the fullscreen. // See more on this at https://github.com/fingerprintjs/fingerprintjs/issues/568 _a.sent(); frameSize = getCurrentScreenFrame(); _a.label = 2; case 2: if (!isFrameSizeNull(frameSize)) { screenFrameBackup = frameSize; } return [2 /*return*/ , frameSize]; } }); }); } /** * Sometimes the available screen resolution changes a bit, e.g. 1900x1440 → 1900x1439. A possible reason: macOS Dock * shrinks to fit more icons when there is too little space. The rounding is used to mitigate the difference. */ function getRoundedScreenFrame() { return __awaiter(this, void 0, void 0, function() { var processSize, frameSize; return __generator(this, function(_a) { switch (_a.label) { case 0: processSize = function(sideSize) { return (sideSize === null ? null : round(sideSize, roundingPrecision)); }; return [4 /*yield*/ , getScreenFrame() // It might look like I don't know about `for` and `map`. // In fact, such code is used to avoid TypeScript issues without using `as`. ]; case 1: frameSize = _a.sent(); // It might look like I don't know about `for` and `map`. // In fact, such code is used to avoid TypeScript issues without using `as`. return [2 /*return*/ , [processSize(frameSize[0]), processSize(frameSize[1]), processSize(frameSize[2]), processSize(frameSize[3])]]; } }); }); } function getCurrentScreenFrame() { var s = screen; // Some browsers return screen resolution as strings, e.g. "1200", instead of a number, e.g. 1200. // I suspect it's done by certain plugins that randomize browser properties to prevent fingerprinting. // // Some browsers (IE, Edge ≤18) don't provide `screen.availLeft` and `screen.availTop`. The property values are // replaced with 0 in such cases to not lose the entropy from `screen.availWidth` and `screen.availHeight`. return [ replaceNaN(toFloat(s.availTop), null), replaceNaN(toFloat(s.width) - toFloat(s.availWidth) - replaceNaN(toFloat(s.availLeft), 0), null), replaceNaN(toFloat(s.height) - toFloat(s.availHeight) - replaceNaN(toFloat(s.availTop), 0), null), replaceNaN(toFloat(s.availLeft), null), ]; } function isFrameSizeNull(frameSize) { for (var i = 0; i < 4; ++i) { if (frameSize[i]) { return false; } } return true; } function getHardwareConcurrency() { // sometimes hardware concurrency is a string return replaceNaN(toInt(navigator.hardwareConcurrency), undefined); } function getTimezone() { var _a; var DateTimeFormat = (_a = window.Intl) === null || _a === void 0 ? void 0 : _a.DateTimeFormat; if (DateTimeFormat) { var timezone = new DateTimeFormat().resolvedOptions().timeZone; if (timezone) { return timezone; } } // For browsers that don't support timezone names // The minus is intentional because the JS offset is opposite to the real offset var offset = -getTimezoneOffset(); return "UTC" + (offset >= 0 ? '+' : '') + Math.abs(offset); } function getTimezoneOffset() { var currentYear = new Date().getFullYear(); // The timezone offset may change over time due to daylight saving time (DST) shifts. // The non-DST timezone offset is used as the result timezone offset. // Since the DST season differs in the northern and the southern hemispheres, // both January and July timezones offsets are considered. return Math.max( // `getTimezoneOffset` returns a number as a string in some unidentified cases toFloat(new Date(currentYear, 0, 1).getTimezoneOffset()), toFloat(new Date(currentYear, 6, 1).getTimezoneOffset())); } function getSessionStorage() { try { return !!window.sessionStorage; } catch (error) { /* SecurityError when referencing it means it exists */ return true; } } // https://bugzilla.mozilla.org/show_bug.cgi?id=781447 function getLocalStorage() { try { return !!window.localStorage; } catch (e) { /* SecurityError when referencing it means it exists */ return true; } } function getIndexedDB() { // IE and Edge don't allow accessing indexedDB in private mode, therefore IE and Edge will have different // visitor identifier in normal and private modes. if (isTrident() || isEdgeHTML()) { return undefined; } try { return !!window.indexedDB; } catch (e) { /* SecurityError when referencing it means it exists */ return true; } } function getOpenDatabase() { return !!window.openDatabase; } function getCpuClass() { return navigator.cpuClass; } function getPlatform() { // Android Chrome 86 and 87 and Android Firefox 80 and 84 don't mock the platform value when desktop mode is requested var platform = navigator.platform; // iOS mocks the platform value when desktop version is requested: https://github.com/fingerprintjs/fingerprintjs/issues/514 // iPad uses desktop mode by default since iOS 13 // The value is 'MacIntel' on M1 Macs // The value is 'iPhone' on iPod Touch if (platform === 'MacIntel') { if (isWebKit() && !isDesktopSafari()) { return isIPad() ? 'iPad' : 'iPhone'; } } return platform; } function getVendor() { return navigator.vendor || ''; } /** * Checks for browser-specific (not engine specific) global variables to tell browsers with the same engine apart. * Only somewhat popular browsers are considered. */ function getVendorFlavors() { var flavors = []; for (var _i = 0, _a = [ // Blink and some browsers on iOS 'chrome', // Safari on macOS 'safari', // Chrome on iOS (checked in 85 on 13 and 87 on 14) '__crWeb', '__gCrWeb', // Yandex Browser on iOS, macOS and Android (checked in 21.2 on iOS 14, macOS and Android) 'yandex', // Yandex Browser on iOS (checked in 21.2 on 14) '__yb', '__ybro', // Firefox on iOS (checked in 32 on 14) '__firefox__', // Edge on iOS (checked in 46 on 14) '__edgeTrackingPreventionStatistics', 'webkit', // Opera Touch on iOS (checked in 2.6 on 14) 'oprt', // Samsung Internet on Android (checked in 11.1) 'samsungAr', // UC Browser on Android (checked in 12.10 and 13.0) 'ucweb', 'UCShellJava', // Puffin on Android (checked in 9.0) 'puffinDevice', ]; _i < _a.length; _i++) { var key = _a[_i]; var value = window[key]; if (value && typeof value === 'object') { flavors.push(key); } } return flavors.sort(); } /** * navigator.cookieEnabled cannot detect custom or nuanced cookie blocking configurations. For example, when blocking * cookies via the Advanced Privacy Settings in IE9, it always returns true. And there have been issues in the past with * site-specific exceptions. Don't rely on it. * * @see https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cookies.js Taken from here */ function areCookiesEnabled() { var d = document; // Taken from here: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cookies.js // navigator.cookieEnabled cannot detect custom or nuanced cookie blocking configurations. For example, when blocking // cookies via the Advanced Privacy Settings in IE9, it always returns true. And there have been issues in the past // with site-specific exceptions. Don't rely on it. // try..catch because some in situations `document.cookie` is exposed but throws a // SecurityError if you try to access it; e.g. documents created from data URIs // or in sandboxed iframes (depending on flags/context) try { // Create cookie d.cookie = 'cookietest=1; SameSite=Strict;'; var result = d.cookie.indexOf('cookietest=') !== -1; // Delete cookie d.cookie = 'cookietest=1; SameSite=Strict; expires=Thu, 01-Jan-1970 00:00:01 GMT'; return result; } catch (e) { return false; } } /** * Only single element selector are supported (no operators like space, +, >, etc). * `embed` and `position: fixed;` will be considered as blocked anyway because it always has no offsetParent. * Avoid `iframe` and anything with `[src=]` because they produce excess HTTP requests. * * See docs/content_blockers.md to learn how to make the list */ var filters = { abpIndo: [ '#Iklan-Melayang', '#Kolom-Iklan-728', '#SidebarIklan-wrapper', 'a[title="7naga poker" i]', '[title="ALIENBOLA" i]', ], abpvn: [ '#quangcaomb', '.i-said-no-thing-can-stop-me-warning.dark', '.quangcao', '[href^="https://r88.vn/"]', '[href^="https://zbet.vn/"]', ], adBlockFinland: [ '.mainostila', '.sponsorit', '.ylamainos', 'a[href*="/clickthrgh.asp?"]', 'a[href^="https://app.readpeak.com/ads"]', ], adBlockPersian: [ '#navbar_notice_50', 'a[href^="https://iqoption.com/lp/mobile-partner/?aff="]', '.kadr', 'TABLE[width="140px"]', '#divAgahi', ], adBlockWarningRemoval: [ '#adblock_message', '.adblockInfo', '.deadblocker-header-bar', '.no-ad-reminder', '#AdBlockDialog', ], adGuardAnnoyances: ['amp-embed[type="zen"]', '.hs-sosyal', '#cookieconsentdiv', 'div[class^="app_gdpr"]', '.as-oil'], adGuardBase: ['#gads_middle', '.tjads', '.BetterJsPopOverlay', '#ad_300X250', '#bannerfloat22'], adGuardChinese: [ 'a[href*=".123ch.cn"]', 'a[href*=".ttz5.cn"]', 'a[href*=".yabovip2027.com/"]', '.tm3all2h4b', '#j-new-ad', ], adGuardFrench: [ '#div_banniere_pub', 'a[href^="https://secure.securitetotale.fr/"]', 'a[href*="fducks.com/"]', 'a[href^="http://frtyd.com/"]', '.publicite1', ], adGuardGerman: [ '.banneritemwerbung_head_1', '.boxstartwerbung', '.werbung3', 'a[href^="http://www.ichwuerde.com/?ref="]', 'a[href^="http://partners.adklick.de/tracking.php?"]', ], adGuardJapanese: [ '.ad-text-blockA01', '._popIn_infinite_video', '[class^=blogroll_wrapper]', 'a[href^="http://ad2.trafficgate.net/"]', 'a[href^="http://www.rssad.jp/"]', ], adGuardMobile: ['amp-auto-ads', '#mgid_iframe', '.amp_ad', 'amp-sticky-ad', '.plugin-blogroll'], adGuardRussian: [ 'a[href^="https://ya-distrib.ru/r/"]', '[onclick*=".twkv.ru"]', '.reclama', 'div[id^="smi2adblock"]', 'div[id^="AdFox_banner_"]', ], adGuardSocial: [ 'a[href^="//www.stumbleupon.com/submit?url="]', 'a[href^="//telegram.me/share/url?"]', '.etsy-tweet', '#inlineShare', '.popup-social', ], adGuardSpanishPortuguese: [ '#barraPublicidade', '#Publicidade', '#publiEspecial', '#queTooltip', '[href^="http://ads.glispa.com/"]', ], adGuardTrackingProtection: [ 'amp-embed[type="taboola"]', '#qoo-counter', 'a[href^="http://click.hotlog.ru/"]', 'a[href^="http://hitcounter.ru/top/stat.php"]', 'a[href^="http://top.mail.ru/jump"]', ], adGuardTurkish: [ '#backkapat', '#reklami', 'a[href^="http://adserv.ontek.com.tr/"]', 'a[href^="http://izlenzi.com/campaign/"]', 'a[href^="http://www.installads.net/"]', ], bulgarian: ['td#freenet_table_ads', '#newAd', '#ea_intext_div', '.lapni-pop-over', '#xenium_hot_offers'], easyList: ['[lazy-ad="leftthin_banner"]', '#ad_300x250_2', '#interstitialAd', '#wide_ad_unit', '.showcaseAd'], easyListChina: [ 'a[href*=".wensixuetang.com/"]', 'A[href*="/hth107.com/"]', '.appguide-wrap[onclick*="bcebos.com"]', '.frontpageAdvM', '#taotaole', ], easyListCookie: ['#CookieEU', '#__cookies_', '#les_cookies', '.asset_balaNotification', '.gdpr-tab'], easyListCzechSlovak: ['#onlajny-stickers', '#reklamni-box', '.reklama-megaboard', '.sklik', '[id^="sklikReklama"]'], easyListDutch: [ '#advertentie', '#vipAdmarktBannerBlock', '.adstekst', 'a[href^="http://adserver.webads.nl/adclick/"]', '#semilo-lrectangle', ], easyListGermany: [ '#LxWerbeteaser', 'a[href^="http://www.kontakt-vermittler.de/?wm="]', '.werbung301', '.ads_bueroklammer', '#Werbung_Sky', ], easyListItaly: [ '.box_adv_annunci', '.sb-box-pubbliredazionale', 'a[href^="http://affiliazioniads.snai.it/"]', 'a[href^="https://adserver.html.it/"]', 'a[href^="https://affiliazioniads.snai.it/"]', ], easyListLithuania: [ '.reklamos_tarpas', '.reklamos_nuorodos', 'img[alt="Reklaminis skydelis"]', 'img[alt="Dedikuoti.lt serveriai"]', 'img[alt="Hostingas Serveriai.lt"]', ], estonian: ['A[href*="http://pay4results24.eu"]'], fanboyAnnoyances: [ '#feedback-tab', '#taboola-below-article', '.feedburnerFeedBlock', '.widget-feedburner-counter', '[title="Subscribe to our blog"]', ], fanboyAntiFacebook: ['.util-bar-module-firefly-visible'], fanboyEnhancedTrackers: [ '.open.pushModal', '#issuem-leaky-paywall-articles-zero-remaining-nag', 'div[style*="box-shadow: rgb(136, 136, 136) 0px 0px 12px; color: "]', 'div[class$="-hide"][zoompage-fontsize][style="display: block;"]', '.BlockNag__Card', ], fanboySocial: [ '.td-tags-and-social-wrapper-box', '.twitterContainer', '.youtube-social', 'a[title^="Like us on Facebook"]', 'img[alt^="Share on Digg"]', ], frellwitSwedish: [ 'a[href*="casinopro.se"][target="_blank"]', 'a[href*="doktor-se.onelink.me"]', 'article.category-samarbete', 'div.holidAds', 'ul.adsmodern', ], greekAdBlock: [ 'A[href*="adman.otenet.gr/click?"]', 'A[href*="http://axiabanners.exodus.gr/"]', 'A[href*="http://interactive.forthnet.gr/click?"]', 'DIV.agores300', 'TABLE.advright', ], hungarian: [ 'A[href*="ad.eval.hu"]', 'A[href*="ad.netmedia.hu"]', 'A[href*="daserver.ultraweb.hu"]', '#cemp_doboz', '.optimonk-iframe-container', ], iDontCareAboutCookies: [ '.alert-info[data-block-track*="CookieNotice"]', '.ModuleTemplateCookieIndicator', '.o--cookies--container', '.cookie-msg-info-container', '#cookies-policy-sticky', ], icelandicAbp: ['A[href^="/framework/resources/forms/ads.aspx"]'], latvian: [ 'a[href="http://www.salidzini.lv/"][style="display: block; width: 120px; height: 40px; overflow: hidden; position: relative;"]', 'a[href="http://www.salidzini.lv/"][style="display: block; width: 88px; height: 31px; overflow: hidden; position: relative;"]', ], listKr: [ 'a[href*="//kingtoon.slnk.kr"]', 'a[href*="//playdsb.com/kr"]', 'div.logly-lift-adz', 'div[data-widget_id="ml6EJ074"]', 'ins.daum_ddn_area', ], listeAr: [ '.geminiLB1Ad', '.right-and-left-sponsers', 'a[href*=".aflam.info"]', 'a[href*="booraq.org"]', 'a[href*="dubizzle.com/ar/?utm_source="]', ], listeFr: [ 'a[href^="http://promo.vador.com/"]', '#adcontainer_recherche', 'a[href*="weborama.fr/fcgi-bin/"]', '.site-pub-interstitiel', 'div[id^="crt-"][data-criteo-id]', ], officialPolish: [ '#ceneo-placeholder-ceneo-12', '[href^="https://aff.sendhub.pl/"]', 'a[href^="http://advmanager.techfun.pl/redirect/"]', 'a[href^="http://www.trizer.pl/?utm_source"]', 'div#skapiec_ad', ], ro: [ 'a[href^="//afftrk.altex.ro/Counter/Click"]', 'a[href^="/magazin/"]', 'a[href^="https://blackfridaysales.ro/trk/shop/"]', 'a[href^="https://event.2performant.com/events/click"]', 'a[href^="https://l.profitshare.ro/"]', ], ruAd: [ 'a[href*="//febrare.ru/"]', 'a[href*="//utimg.ru/"]', 'a[href*="://chikidiki.ru"]', '#pgeldiz', '.yandex-rtb-block', ], thaiAds: ['a[href*=macau-uta-popup]', '#ads-google-middle_rectangle-group', '.ads300s', '.bumq', '.img-kosana'], webAnnoyancesUltralist: [ '#mod-social-share-2', '#social-tools', '.ctpl-fullbanner', '.zergnet-recommend', '.yt.btn-link.btn-md.btn', ], }; /** Just a syntax sugar */ var filterNames = Object.keys(filters); /** * The returned array order means nothing (it's always sorted alphabetically). * * Notice that the source is slightly unstable. * Safari provides a 2-taps way to disable all content blockers on a page temporarily. * Also content blockers can be disabled permanently for a domain, but it requires 4 taps. * So empty array shouldn't be treated as "no blockers", it should be treated as "no signal". * If you are a website owner, don't make your visitors want to disable content blockers. */ function getDomBlockers(_a) { var debug = (_a === void 0 ? {} : _a).debug; return __awaiter(this, void 0, void 0, function() { var allSelectors, blockedSelectors, activeBlockers; var _b; return __generator(this, function(_c) { switch (_c.label) { case 0: if (!isApplicable()) { return [2 /*return*/ , undefined]; } allSelectors = (_b = []).concat.apply(_b, filterNames.map(function(filterName) { return filters[filterName]; })); return [4 /*yield*/ , getBlockedSelectors(allSelectors)]; case 1: blockedSelectors = _c.sent(); if (debug) { printDebug(blockedSelectors); } activeBlockers = filterNames.filter(function(filterName) { var selectors = filters[filterName]; var blockedCount = countTruthy(selectors.map(function(selector) { return blockedSelectors[selector]; })); return blockedCount > selectors.length * 0.5; }); activeBlockers.sort(); return [2 /*return*/ , activeBlockers]; } }); }); } function isApplicable() { // Safari (desktop and mobile) and all Android browsers keep content blockers in both regular and private mode return isWebKit() || isAndroid(); } function getBlockedSelectors(selectors) { var _a; return __awaiter(this, void 0, void 0, function() { var d, root, elements, blockedSelectors, _i, selectors_1, selector, element, holder, i; return __generator(this, function(_b) { switch (_b.label) { case 0: d = document; root = d.createElement('div'); elements = []; blockedSelectors = {} // Set() isn't used just in case somebody need older browser support ; forceShow(root); // First create all elements that can be blocked. If the DOM steps below are done in a single cycle, // browser will alternate tree modification and layout reading, that is very slow. for (_i = 0, selectors_1 = selectors; _i < selectors_1.length; _i++) { selector = selectors_1[_i]; element = selectorToElement(selector); holder = d.createElement('div') // Protects from unwanted effects of `+` and `~` selectors of filters ; forceShow(holder); holder.appendChild(element); root.appendChild(holder); elements.push(element); } _b.label = 1; case 1: if (!!d.body) return [3 /*break*/ , 3]; return [4 /*yield*/ , wait(50)]; case 2: _b.sent(); return [3 /*break*/ , 1]; case 3: d.body.appendChild(root); try { // Then check which of the elements are blocked for (i = 0; i < selectors.length; ++i) { if (!elements[i].offsetParent) { blockedSelectors[selectors[i]] = true; } } } finally { // Then remove the elements (_a = root.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(root); } return [2 /*return*/ , blockedSelectors]; } }); }); } function forceShow(element) { element.style.setProperty('display', 'block', 'important'); } function printDebug(blockedSelectors) { var message = 'DOM blockers debug:\n```'; for (var _i = 0, filterNames_1 = filterNames; _i < filterNames_1.length; _i++) { var filterName = filterNames_1[_i]; message += "\n" + filterName + ":"; for (var _a = 0, _b = filters[filterName]; _a < _b.length; _a++) { var selector = _b[_a]; message += "\n " + selector + " " + (blockedSelectors[selector] ? '🚫' : '➡️'); } } // console.log is ok here because it's under a debug clause // eslint-disable-next-line no-console console.log(message + "\n```"); } /** * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@media/color-gamut */ function getColorGamut() { // rec2020 includes p3 and p3 includes srgb for (var _i = 0, _a = ['rec2020', 'p3', 'srgb']; _i < _a.length; _i++) { var gamut = _a[_i]; if (matchMedia("(color-gamut: " + gamut + ")").matches) { return gamut; } } return undefined; } /** * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@media/inverted-colors */ function areColorsInverted() { if (doesMatch('inverted')) { return true; } if (doesMatch('none')) { return false; } return undefined; } function doesMatch(value) { return matchMedia("(inverted-colors: " + value + ")").matches; } /** * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@media/forced-colors */ function areColorsForced() { if (doesMatch$1('active')) { return true; } if (doesMatch$1('none')) { return false; } return undefined; } function doesMatch$1(value) { return matchMedia("(forced-colors: " + value + ")").matches; } var maxValueToCheck = 100; /** * If the display is monochrome (e.g. black&white), the value will be ≥0 and will mean the number of bits per pixel. * If the display is not monochrome, the returned value will be 0. * If the browser doesn't support this feature, the returned value will be undefined. * * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@media/monochrome */ function getMonochromeDepth() { if (!matchMedia('(min-monochrome: 0)').matches) { // The media feature isn't supported by the browser return undefined; } // A variation of binary search algorithm can be used here. // But since expected values are very small (≤10), there is no sense in adding the complexity. for (var i = 0; i <= maxValueToCheck; ++i) { if (matchMedia("(max-monochrome: " + i + ")").matches) { return i; } } throw new Error('Too high value'); } /** * @see https://www.w3.org/TR/mediaqueries-5/#prefers-contrast * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-contrast */ function getContrastPreference() { if (doesMatch$2('no-preference')) { return 0 /* None */ ; } // The sources contradict on the keywords. Probably 'high' and 'low' will never be implemented. // Need to check it when all browsers implement the feature. if (doesMatch$2('high') || doesMatch$2('more')) { return 1 /* More */ ; } if (doesMatch$2('low') || doesMatch$2('less')) { return -1 /* Less */ ; } if (doesMatch$2('forced')) { return 10 /* ForcedColors */ ; } return undefined; } function doesMatch$2(value) { return matchMedia("(prefers-contrast: " + value + ")").matches; } /** * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion */ function isMotionReduced() { if (doesMatch$3('reduce')) { return true; } if (doesMatch$3('no-preference')) { return false; } return undefined; } function doesMatch$3(value) { return matchMedia("(prefers-reduced-motion: " + value + ")").matches; } /** * @see https://www.w3.org/TR/mediaqueries-5/#dynamic-range */ function isHDR() { if (doesMatch$4('high')) { return true; } if (doesMatch$4('standard')) { return false; } return undefined; } function doesMatch$4(value) { return matchMedia("(dynamic-range: " + value + ")").matches; } var M = Math; // To reduce the minified code size var fallbackFn = function() { return 0; }; // Native operations var acos = M.acos || fallbackFn; var acosh = M.acosh || fallbackFn; var asin = M.asin || fallbackFn; var asinh = M.asinh || fallbackFn; var atanh = M.atanh || fallbackFn; var atan = M.atan || fallbackFn; var sin = M.sin || fallbackFn; var sinh = M.sinh || fallbackFn; var cos = M.cos || fallbackFn; var cosh = M.cosh || fallbackFn; var tan = M.tan || fallbackFn; var tanh = M.tanh || fallbackFn; var exp = M.exp || fallbackFn; var expm1 = M.expm1 || fallbackFn; var log1p = M.log1p || fallbackFn; // Operation polyfills var powPI = function(value) { return M.pow(M.PI, value); }; var acoshPf = function(value) { return M.log(value + M.sqrt(value * value - 1)); }; var asinhPf = function(value) { return M.log(value + M.sqrt(value * value + 1)); }; var atanhPf = function(value) { return M.log((1 + value) / (1 - value)) / 2; }; var sinhPf = function(value) { return M.exp(value) - 1 / M.exp(value) / 2; }; var coshPf = function(value) { return (M.exp(value) + 1 / M.exp(value)) / 2; }; var expm1Pf = function(value) { return M.exp(value) - 1; }; var tanhPf = function(value) { return (M.exp(2 * value) - 1) / (M.exp(2 * value) + 1); }; var log1pPf = function(value) { return M.log(1 + value); }; /** * @see https://gitlab.torproject.org/legacy/trac/-/issues/13018 * @see https://bugzilla.mozilla.org/show_bug.cgi?id=531915 */ function getMathFingerprint() { // Note: constant values are empirical return { acos: acos(0.123124234234234242), acosh: acosh(1e308), acoshPf: acoshPf(1e154), asin: asin(0.123124234234234242), asinh: asinh(1), asinhPf: asinhPf(1), atanh: atanh(0.5), atanhPf: atanhPf(0.5), atan: atan(0.5), sin: sin(-1e300), sinh: sinh(1), sinhPf: sinhPf(1), cos: cos(10.000000000123), cosh: cosh(1), coshPf: coshPf(1), tan: tan(-1e300), tanh: tanh(1), tanhPf: tanhPf(1), exp: exp(1), expm1: expm1(1), expm1Pf: expm1Pf(1), log1p: log1p(10), log1pPf: log1pPf(10), powPI: powPI(-100), }; } /** * We use m or w because these two characters take up the maximum width. * Also there are a couple of ligatures. */ var defaultText = 'mmMwWLliI0fiflO&1'; /** * Settings of text blocks to measure. The keys are random but persistent words. */ var presets = { /** * The default font. User can change it in desktop Chrome, desktop Firefox, IE 11, * Android Chrome (but only when the size is ≥ than the default) and Android Firefox. */ default: [], /** OS font on macOS. User can change its size and weight. Applies after Safari restart. */ apple: [{ font: '-apple-system-body' }], /** User can change it in desktop Chrome and desktop Firefox. */ serif: [{ fontFamily: 'serif' }], /** User can change it in desktop Chrome and desktop Firefox. */ sans: [{ fontFamily: 'sans-serif' }], /** User can change it in desktop Chrome and desktop Firefox. */ mono: [{ fontFamily: 'monospace' }], /** * Check the minimal allowed font size. User can change it in desktop Chrome, desktop Firefox and desktop Safari. * The height can be 0 in Chrome on a retina display. */ min: [{ fontSize: '1px' }], /** Tells one OS from another in desktop Chrome. */ system: [{ fontFamily: 'system-ui' }], }; /** * The result is a dictionary of the width of the text samples. * Heights aren't included because they give no extra entropy and are unstable. * * The result is very stable in IE 11, Edge 18 and Safari 14. * The result changes when the OS pixel density changes in Chromium 87. The real pixel density is required to solve, * but seems like it's impossible: https://stackoverflow.com/q/1713771/1118709. * The "min" and the "mono" (only on Windows) value may change when the page is zoomed in Firefox 87. */ function getFontPreferences() { return withNaturalFonts(function(document, container) { var elements = {}; var sizes = {}; // First create all elements to measure. If the DOM steps below are done in a single cycle, // browser will alternate tree modification and layout reading, that is very slow. for (var _i = 0, _a = Object.keys(presets); _i < _a.length; _i++) { var key = _a[_i]; var _b = presets[key], _c = _b[0], style = _c === void 0 ? {} : _c, _d = _b[1], text = _d === void 0 ? defaultText : _d; var element = document.createElement('span'); element.textContent = text; element.style.whiteSpace = 'nowrap'; for (var _e = 0, _f = Object.keys(style); _e < _f.length; _e++) { var name_1 = _f[_e]; var value = style[name_1]; if (value !== undefined) { element.style[name_1] = value; } } elements[key] = element; container.appendChild(document.createElement('br')); container.appendChild(element); } // Then measure the created elements for (var _g = 0, _h = Object.keys(presets); _g < _h.length; _g++) { var key = _h[_g]; sizes[key] = elements[key].getBoundingClientRect().width; } return sizes; }); } /** * Creates a DOM environment that provides the most natural font available, including Android OS font. * Measurements of the elements are zoom-independent. * Don't put a content to measure inside an absolutely positioned element. */ function withNaturalFonts(action, containerWidthPx) { if (containerWidthPx === void 0) { containerWidthPx = 4000; } /* * Requirements for Android Chrome to apply the system font size to a text inside an iframe: * - The iframe mustn't have a `display: none;` style; * - The text mustn't be positioned absolutely; * - The text block must be wide enough. * 2560px on some devices in portrait orientation for the biggest font size option (32px); * - There must be much enough text to form a few lines (I don't know the exact numbers); * - The text must have the `text-size-adjust: none` style. Otherwise the text will scale in "Desktop site" mode; * * Requirements for Android Firefox to apply the system font size to a text inside an iframe: * - The iframe document must have a header: ``. * The only way to set it is to use the `srcdoc` attribute of the iframe; * - The iframe content must get loaded before adding extra content with JavaScript; * * https://example.com as the iframe target always inherits Android font settings so it can be used as a reference. * * Observations on how page zoom affects the measurements: * - macOS Safari 11.1, 12.1, 13.1, 14.0: zoom reset + offsetWidth = 100% reliable; * - macOS Safari 11.1, 12.1, 13.1, 14.0: zoom reset + getBoundingClientRect = 100% reliable; * - macOS Safari 14.0: offsetWidth = 5% fluctuation; * - macOS Safari 14.0: getBoundingClientRect = 5% fluctuation; * - iOS Safari 9, 10, 11.0, 12.0: haven't found a way to zoom a page (pinch doesn't change layout); * - iOS Safari 13.1, 14.0: zoom reset + offsetWidth = 100% reliable; * - iOS Safari 13.1, 14.0: zoom reset + getBoundingClientRect = 100% reliable; * - iOS Safari 14.0: offsetWidth = 100% reliable; * - iOS Safari 14.0: getBoundingClientRect = 100% reliable; * - Chrome 42, 65, 80, 87: zoom 1/devicePixelRatio + offsetWidth = 1px fluctuation; * - Chrome 42, 65, 80, 87: zoom 1/devicePixelRatio + getBoundingClientRect = 100% reliable; * - Chrome 87: offsetWidth = 1px fluctuation; * - Chrome 87: getBoundingClientRect = 0.7px fluctuation; * - Firefox 48, 51: offsetWidth = 10% fluctuation; * - Firefox 48, 51: getBoundingClientRect = 10% fluctuation; * - Firefox 52, 53, 57, 62, 66, 67, 68, 71, 75, 80, 84: offsetWidth = width 100% reliable, height 10% fluctuation; * - Firefox 52, 53, 57, 62, 66, 67, 68, 71, 75, 80, 84: getBoundingClientRect = width 100% reliable, height 10% * fluctuation; * - Android Chrome 86: haven't found a way to zoom a page (pinch doesn't change layout); * - Android Firefox 84: font size in accessibility settings changes all the CSS sizes, but offsetWidth and * getBoundingClientRect keep measuring with regular units, so the size reflects the font size setting and doesn't * fluctuate; * - IE 11, Edge 18: zoom 1/devicePixelRatio + offsetWidth = 100% reliable; * - IE 11, Edge 18: zoom 1/devicePixelRatio + getBoundingClientRect = reflects the zoom level; * - IE 11, Edge 18: offsetWidth = 100% reliable; * - IE 11, Edge 18: getBoundingClientRect = 100% reliable; */ return withIframe(function(_, iframeWindow) { var iframeDocument = iframeWindow.document; var iframeBody = iframeDocument.body; var bodyStyle = iframeBody.style; bodyStyle.width = containerWidthPx + "px"; bodyStyle.webkitTextSizeAdjust = bodyStyle.textSizeAdjust = 'none'; // See the big comment above if (isChromium()) { iframeBody.style.zoom = "" + 1 / iframeWindow.devicePixelRatio; } else if (isWebKit()) { iframeBody.style.zoom = 'reset'; } // See the big comment above var linesOfText = iframeDocument.createElement('div'); linesOfText.textContent = __spreadArrays(Array((containerWidthPx / 20) << 0)).map(function() { return 'word'; }).join(' '); iframeBody.appendChild(linesOfText); return action(iframeDocument, iframeBody); }, ''); } /** * The list of entropy sources used to make visitor identifiers. * * This value isn't restricted by Semantic Versioning, i.e. it may be changed without bumping minor or major version of * this package. */ var sources = { // Expected errors and default values must be handled inside the functions. Unexpected errors must be thrown. // The sources run in this exact order. The asynchronous sources are at the start to run in parallel with other sources. fonts: getFonts, domBlockers: getDomBlockers, fontPreferences: getFontPreferences, audio: getAudioFingerprint, screenFrame: getRoundedScreenFrame, osCpu: getOsCpu, languages: getLanguages, colorDepth: getColorDepth, deviceMemory: getDeviceMemory, screenResolution: getScreenResolution, hardwareConcurrency: getHardwareConcurrency, timezone: getTimezone, sessionStorage: getSessionStorage, localStorage: getLocalStorage, indexedDB: getIndexedDB, openDatabase: getOpenDatabase, cpuClass: getCpuClass, platform: getPlatform, plugins: getPlugins, canvas: getCanvasFingerprint, touchSupport: getTouchSupport, vendor: getVendor, vendorFlavors: getVendorFlavors, cookiesEnabled: areCookiesEnabled, colorGamut: getColorGamut, invertedColors: areColorsInverted, forcedColors: areColorsForced, monochrome: getMonochromeDepth, contrast: getContrastPreference, reducedMotion: isMotionReduced, hdr: isHDR, math: getMathFingerprint, }; function ensureErrorWithMessage(error) { return error && typeof error === 'object' && 'message' in error ? error : { message: error }; } /** * Gets a component from the given entropy source. */ function getComponent(source, sourceOptions) { return __awaiter(this, void 0, void 0, function() { var result, startTime, error_1; var _a; return __generator(this, function(_b) { switch (_b.label) { case 0: startTime = Date.now(); _b.label = 1; case 1: _b.trys.push([1, 3, , 4]); _a = {}; return [4 /*yield*/ , source(sourceOptions)]; case 2: result = (_a.value = _b.sent(), _a); return [3 /*break*/ , 4]; case 3: error_1 = _b.sent(); result = { error: ensureErrorWithMessage(error_1) }; return [3 /*break*/ , 4]; case 4: return [2 /*return*/ , __assign(__assign({}, result), { duration: Date.now() - startTime })]; } }); }); } /** * Gets a components list from the given list of entropy sources. * * Warning for package users: * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk. */ function getComponents(sources, sourceOptions, excludeSources) { return __awaiter(this, void 0, void 0, function() { var sourcePromises, components, loopReleaseInterval, lastLoopReleaseTime, _loop_1, _i, _a, sourceKey; return __generator(this, function(_b) { switch (_b.label) { case 0: sourcePromises = []; components = {}; loopReleaseInterval = 16; lastLoopReleaseTime = Date.now(); _loop_1 = function(sourceKey) { var now; return __generator(this, function(_a) { switch (_a.label) { case 0: if (!excludes(excludeSources, sourceKey)) { return [2 /*return*/ , "continue"]; } // Create the keys immediately to keep the component keys order the same as the sources keys order components[sourceKey] = undefined; sourcePromises.push(getComponent(sources[sourceKey], sourceOptions).then(function(component) { components[sourceKey] = component; })); now = Date.now(); if (!(now >= lastLoopReleaseTime + loopReleaseInterval)) return [3 /*break*/ , 2]; lastLoopReleaseTime = now; // Allows asynchronous sources to complete and measure the duration correctly before running the next sources return [4 /*yield*/ , new Promise(function(resolve) { return setTimeout(resolve); })]; case 1: // Allows asynchronous sources to complete and measure the duration correctly before running the next sources _a.sent(); return [3 /*break*/ , 4]; case 2: return [4 /*yield*/ , undefined]; case 3: _a.sent(); _a.label = 4; case 4: return [2 /*return*/ ]; } }); }; _i = 0, _a = Object.keys(sources); _b.label = 1; case 1: if (!(_i < _a.length)) return [3 /*break*/ , 4]; sourceKey = _a[_i]; return [5 /*yield**/ , _loop_1(sourceKey)]; case 2: _b.sent(); _b.label = 3; case 3: _i++; return [3 /*break*/ , 1]; case 4: return [4 /*yield*/ , Promise.all(sourcePromises)]; case 5: _b.sent(); return [2 /*return*/ , components]; } }); }); } /** * Collects entropy components from the built-in sources to make the visitor identifier. */ function getBuiltinComponents(options) { return getComponents(sources, options, []); } function componentsToCanonicalString(components) { var result = ''; for (var _i = 0, _a = Object.keys(components).sort(); _i < _a.length; _i++) { var componentKey = _a[_i]; var component = components[componentKey]; var value = component.error ? 'error' : JSON.stringify(component.value); result += "" + (result ? '|' : '') + componentKey.replace(/([:|\\])/g, '\\$1') + ":" + value; } return result; } function componentsToDebugString(components) { return JSON.stringify(components, function(_key, value) { if (value instanceof Error) { return errorToObject(value); } return value; }, 2); } function hashComponents(components) { return x64hash128(componentsToCanonicalString(components)); } /** * Makes a GetResult implementation that calculates the visitor id hash on demand. * Designed for optimisation. */ function makeLazyGetResult(components) { var visitorIdCache; // A plain class isn't used because its getters and setters aren't enumerable. return { components: components, get visitorId() { if (visitorIdCache === undefined) { visitorIdCache = hashComponents(this.components); } return visitorIdCache; }, set visitorId(visitorId) { visitorIdCache = visitorId; }, version: version, }; } /** * The class isn't exported from the index file to not expose the constructor. * The hiding gives more freedom for future non-breaking updates. */ var OpenAgent = /** @class */ (function() { function OpenAgent() { watchScreenFrame(); } /** * @inheritDoc */ OpenAgent.prototype.get = function(options) { if (options === void 0) { options = {}; } return __awaiter(this, void 0, void 0, function() { var components, result; return __generator(this, function(_a) { switch (_a.label) { case 0: return [4 /*yield*/ , getBuiltinComponents(options)]; case 1: components = _a.sent(); result = makeLazyGetResult(components); if (options.debug) { // console.log is ok here because it's under a debug clause // eslint-disable-next-line no-console console.log("Copy the text below to get the debug data:\n\n```\nversion: " + result.version + "\nuserAgent: " + navigator.userAgent + "\ngetOptions: " + JSON.stringify(options, undefined, 2) + "\nvisitorId: " + result.visitorId + "\ncomponents: " + componentsToDebugString(components) + "\n```"); } return [2 /*return*/ , result]; } }); }); }; return OpenAgent; }()); /** * Builds an instance of Agent and waits a delay required for a proper operation. */ function load(_a) { var _b = (_a === void 0 ? {} : _a).delayFallback, delayFallback = _b === void 0 ? 50 : _b; return __awaiter(this, void 0, void 0, function() { return __generator(this, function(_c) { switch (_c.label) { case 0: // A delay is required to ensure consistent entropy components. // See https://github.com/fingerprintjs/fingerprintjs/issues/254 // and https://github.com/fingerprintjs/fingerprintjs/issues/307 // and https://github.com/fingerprintjs/fingerprintjs/commit/945633e7c5f67ae38eb0fea37349712f0e669b18 // A proper deadline is unknown. Let it be twice the fallback timeout so that both cases have the same average time. return [4 /*yield*/ , requestIdleCallbackIfAvailable(delayFallback, delayFallback * 2)]; case 1: // A delay is required to ensure consistent entropy components. // See https://github.com/fingerprintjs/fingerprintjs/issues/254 // and https://github.com/fingerprintjs/fingerprintjs/issues/307 // and https://github.com/fingerprintjs/fingerprintjs/commit/945633e7c5f67ae38eb0fea37349712f0e669b18 // A proper deadline is unknown. Let it be twice the fallback timeout so that both cases have the same average time. _c.sent(); return [2 /*return*/ , new OpenAgent()]; } }); }); } // The default export is a syntax sugar (`import * as FP from '...' → import FP from '...'`). // It should contain all the public exported values. var index = { load: load, hashComponents: hashComponents, componentsToDebugString: componentsToDebugString }; // import {Ice} from "ice"; /** * 调度终端接口,是单例模式, 通过getInstance()方法获取单例 */ class DispatcherClient { constructor() { this._eventDelegate = { onRegistered: () => { if (this._userDelegate != null) { this._userDelegate.onRegistered(); } this.setRegistState(exports.RegistState.Registed); }, onUnregistered: () => { if (this._userDelegate != null) { this._userDelegate.onUnregistered(); } // alert("unregist"); if (this.registState == exports.RegistState.Registed) { // this.registState = RegistState.Unregisted; this.setRegistState(exports.RegistState.Unregisted); } }, onCallCreated: (callId, videoControl) => { // if (this._userDelegate != null) { // this._userDelegate.onCallCreated(callId, videoControl); // } }, onCallReceived: (id, orgCaller, sessionId, type, caller) => { // if (sessionId != null) { // if (type == "5") { // 会议 // this._conferenceSessionId = sessionId; // this._conferenceCallId = id; // if (caller == this._registOption.userName) { //会议发起者 // this.answerVideo(id, this._conferenceVideoControl); // return; // } else { //会议接受者 // if (this._userDelegate != null) { // this._userDelegate.onConferenceReceiveInvite(); // return; // } // } // } // } // if (orgCaller == "*5*get") { //获取会议成员视频来电 // this.answerVideo(id, this._conferenceMemberVideo); // if (this._userDelegate != null) { // this._userDelegate.onConferenceGetVideo(id, caller, this._conferenceMemberVideo); // } // return; // } // if (this._userDelegate != null) { // this._userDelegate.onCallReceived(id, orgCaller, sessionId, type, caller); // } }, onCallHangup: (callid, remoteNumber) => { // if (this._userDelegate != null) { // this._userDelegate.onCallHangup(callid, remoteNumber); // } }, onMessageReceived: (message) => { // if (this._userDelegate != null) { // this._userDelegate.onMessageReceived("number", message); // } } }; this._domain = "127.0.0.1:5060"; this._userStateEventEmitter = new EventEmitter(); this._registStateEventEmitter = new EventEmitter(); this._userCallStateEventEmitter = new EventEmitter(); this._incomingCallEventEmitter = new EventEmitter(); this._receiveConferenceInviteEventEmitter = new EventEmitter(); this._receiveIntercomInviteEventEmitter = new EventEmitter(); this._receiveBroadcastInviteEventEmitter = new EventEmitter(); this._serverConnectStateEventEmitter = new EventEmitter(); this._gisInfoEventEmitter = new EventEmitter(); this._msgReceivedEventEmitter = new EventEmitter(); this._fileMsgReceivedEventEmitter = new EventEmitter(); this._eventEmitter = new EventEmitter(); this._handleAnswerIncomingCall = new EventEmitter(); this._handleAnswerIncomingConference = new EventEmitter(); this.calls = {}; this.conferences = {}; this.intercoms = {}; this.broadcasts = {}; this.unInitOutgoingCalls = {}; this.unInitOutGoingSubstitue = null; this._tempOutgoingCall = null; // private _tempOutgoningIntercom: IntercomImp = null; this._tempOutgoningBroadcast = null; // get userStateChange(): Emitter{ // return makeEmitter(_userStateEventEmitter); // } this._userRegist = false; this._logger = Logger.getInstance(); this.commonEventString = "event"; this._registState = exports.RegistState.None; this._iceServer = iceAPI.getInstance(); this._iceServer.on(IceEventName.SessionStateChange.toString(), (content) => { this._logger.log("***********" + IceEventName.SessionStateChange.toString()); this._eventEmitter.emit(DispatcherClientEventName.SessionStateChange.toString(), content); let sessionState = JSON.parse(content); let sessionId = sessionState[0].cid; let isVideo = false; if (sessionState[0].isVideo == "2") { isVideo = true; } let callType = iceAPI.convertIceCallType(sessionState[0].type); if (callType == CallType.Conference || callType == CallType.MCUMetting || callType == CallType.Interpose) { this.processConferenceSessionStateChange(callType, sessionState, sessionId, isVideo); return; } else if (callType == CallType.Tempintercom || callType == CallType.Intercom) { let intercom = this.intercoms[sessionId]; if (intercom != null) { intercom.stateice = sessionState[0].state; if (intercom.stateInternal == IntercomState.Terminaled) { delete this.intercoms[sessionId]; } } return; } else if (callType == CallType.Broadcast) { let broadcast = this.broadcasts[sessionId]; if (broadcast != null) { broadcast.stateice = sessionState[0].state; if (broadcast.stateInternal == BroadcastState.Terminaled) { delete this.broadcasts[sessionId]; } } return; } else if (callType == CallType.Monitor) { let monitorConf = this.conferences[sessionId]; if (monitorConf != null) { monitorConf.stateice = sessionState[0].state; if (monitorConf.stateInternal == ConferenceState.Terminaled) { delete this.conferences[sessionId]; } } return; } this.processCallSessionStateChange(sessionState, sessionId, isVideo); }); this._iceServer.on(IceEventName.regStateChange.toString(), (userId, state) => { let onlineState = exports.OnlineState.Offline; switch (state) { case exports.RegistState.Registed: onlineState = exports.OnlineState.Online; break; default: break; } const para = { number: userId, state: onlineState }; this._userStateEventEmitter.emit("event", para); // this._eventEmitter.emit(DispatcherClientEventName.UserOnlineState.toString(), userId, state); }); this._iceServer.on(IceEventName.CallStateChange.toString(), (userNumber, state) => { const para = { userNumber: userNumber, callState: state }; this._userCallStateEventEmitter.emit("event", para); // this._eventEmitter.emit(DispatcherClientEventName.UserCallState.toString(), userNumber, state); }); this._iceServer.on(IceEventName.ServerDisconnect.toString(), () => { this._serverConnectStateEventEmitter.emit(this.commonEventString, exports.ServiceConnectState.DisConnect); }); this._iceServer.on(IceEventName.ServerConnectd.toString(), () => { this._serverConnectStateEventEmitter.emit(this.commonEventString, exports.ServiceConnectState.Connected); }); this._iceServer.on(IceEventName.GisInfo.toString(), (gisinfo) => { this._gisInfoEventEmitter.emit(this.commonEventString, gisinfo); }); this._iceServer.on(IceEventName.MsgReceived.toString(), (msg) => { this._msgReceivedEventEmitter.emit(this.commonEventString, msg); }); this._iceServer.on(IceEventName.FileMsgReceived.toString(), (msg) => { this._fileMsgReceivedEventEmitter.emit(this.commonEventString, msg); }); this._iceServer.on(IceEventName.registKickout.toString(), (msg) => { // this._registStateEventEmitter.emit(this.commonEventString, msg); this.setRegistState(exports.RegistState.ForceKickout); }); this._iceServer.on(IceEventName.pushAudioToRTSP.toString(), (content) => { let result = JSON.parse(content); let sessionId = result.cid; let conf = this.conferences[sessionId]; if (conf != null) { if (result.pushstate == "start") { conf.pushAudioToRTSPState = PushAudioToRTSPState.start; } else if (result.pushstate == "stop") { conf.pushAudioToRTSPState = PushAudioToRTSPState.stop; } } else { let broadcast = this.broadcasts[sessionId]; if (broadcast != null) { if (result.pushstate == "start") { broadcast.pushAudioToRTSPState = PushAudioToRTSPState.start; } else if (result.pushstate == "stop") { broadcast.pushAudioToRTSPState = PushAudioToRTSPState.stop; } } } }); // let uuidKey = "uuid"; // let uuid = this.getCookie(uuidKey); // if (uuid == null || uuid == "") { // uuid = Utils.newUUID(); // this.setCookie(uuidKey, uuid); // } // this.uuid = uuid; // Initialize an agent at application startup. const fpPromise = index.load(); (async() => { // Get the visitor identifier when you need it. const fp = await fpPromise; const result = await fp.get(); // This is the visitor identifier: const visitorId = result.visitorId; console.log("visitorId: " + visitorId); this.uuid = visitorId; LoginInfo.getInstance().uuid = this.uuid; })(); } /** * 获取调度终端接口单例 * @returns 调度终端接口单例 */ static getInstance() { if (DispatcherClient.s_instance == null) { DispatcherClient.s_instance = new DispatcherClient(); } return DispatcherClient.s_instance; } // setEventDelegate(delegate: SphoneDelegate) { // _eventDelegate = delegate; // } setUserDelegate(delegate) { this._userDelegate = delegate; } //#endregion private filed /** * 日志开关 */ set enableLog(v) { Logger.getInstance().enable = v; } setRegistState(v) { if (this._registState != v) { // if (v == RegistState.Registed) { // let options = this._registOption; // this._iceServer.regist(options.ip, options.businesPort, options.userName, this._businessHandler); // } this._registState = v; let para = { state: v }; this._registStateEventEmitter.emit("event", para); } } /** * 获取注册状态 */ get registState() { return this._registState; } /** * 是否已经注册 */ get isRegisted() { if (this._registState == exports.RegistState.Registed) { return true; } return false; } // unAttended: boolean = false; /** * 当前用户注册状态改变事件 * @returns 事件参数 */ get registStateChange() { return makeEmitter(this._registStateEventEmitter); } /** * 相关用户状态改变事件(与当前用户相同的分组下的用户的状态,会推送给当前用户) */ get userOnlineStateChange() { return makeEmitter(this._userStateEventEmitter); } /** * 相关用户呼叫状态改变事件(与当前用户相同的分组下的用户的状态,会推送给当前用户) */ get userCallStateChange() { return makeEmitter(this._userCallStateEventEmitter); } /** * 呼叫来电事件 */ get incomingCall() { return makeEmitter(this._incomingCallEventEmitter); } /** * 会议邀请事件 */ get receiveConferenceInvite() { return makeEmitter(this._receiveConferenceInviteEventEmitter); } /** * 对讲邀请事件 */ get receiveIntercomInvite() { return makeEmitter(this._receiveIntercomInviteEventEmitter); } /** * 广播邀请事件 */ get receiveBroadcastInvite() { return makeEmitter(this._receiveBroadcastInviteEventEmitter); } /** * 业务服务器改变事件 */ get serverConnectStateChanged() { console.log("mainJS中对服务器连接状态改变") return makeEmitter(this._serverConnectStateEventEmitter); } /** * GIS信息推送事件 */ get gisInfoNotify() { return makeEmitter(this._gisInfoEventEmitter); } /** * 消息接收事件 */ get msgReceived() { return makeEmitter(this._msgReceivedEventEmitter); } /** * 文件接收事件 */ get fileMsgReceived() { return makeEmitter(this._fileMsgReceivedEventEmitter); } /** * 手柄接听事件(被叫如果绑定了手柄,当手柄接听的时候会触发这个事件),一般会在这个事件中调用 call的 hangdleRequestVideo实现视频收发 */ get handleAnswerIncomingCall() { return makeEmitter(this._handleAnswerIncomingCall); } /** * 手柄接听事件(如果绑定了手柄,当手柄接听会议的时候会触发这个事件),一般会在这个事件中调用 conference 的 hangdleRequestVideo实现视频收发 */ get handleAnswerIncomingConference() { return makeEmitter(this._handleAnswerIncomingConference); } // /** // * 来电事件 // * @param listener 来电监听 // * (number 来电号码) // */ // onIncomingCall(listener: (call:Call)=> void){ // this._eventEmitter.on( DispatcherClientEventName.IncomingCall.toString(), listener); // } // onRegitStateChange(listener: (state: RegistState)=> void){ // this._eventEmitter.on( DispatcherClientEventName.RegistState.toString(), listener ); // } // onUserOnlineStateChange(listener: (user:string, state: RegistState)=> void){ // this._eventEmitter.on( DispatcherClientEventName.UserOnlineState.toString(), listener ); // } // onUserCallStateChange(listener: (user:string, state: UserCallStateDetail)=> void){ // this._eventEmitter.on( DispatcherClientEventName.UserCallState.toString(), listener ); // } /** * 注册 * @param options 注册参数 */ regist(options) { this._userRegist = true; // _businessHandler = businessHanlder; // _eventDelegate // let userNunmber = "1000"; this._registState = exports.RegistState.None; this._registOption = options; this._serverIP = options.ip; this._domain = this._serverIP; this._userNumber = options.userName; LoginInfo.getInstance().number = options.userName; this._password = options.password; // webSocketServerAlice = "ws://" + _serverIP +":5066"; // webSocketServerAlice = "ws://" + _serverIP + ids; // this.webSocketServerAlice = "wss://" + this._serverIP + ":" + options.port; // this._serverIP = "172.19.2.37"; // options.port = 9443; let resourceUrl = ""; if (options.resourceUrl != null) { resourceUrl = options.resourceUrl; } this.webSocketServerAlice = "wss://" + this._serverIP + ":" + options.port + "/" + resourceUrl; let businessResourceUrl = ""; if (options.businessResourceUrl != null) { businessResourceUrl = options.businessResourceUrl; } this._iceServer.regist(options.ip, options.businesPort, options.userName, this._businessHandler, businessResourceUrl); let aliceUrl = this.getUrlByNumber(options.userName); this.alice = this.buildUser1(this.webSocketServerAlice, aliceUrl, options.userName, null, null, options.userType); this.alice.on(SphoneEventName.IncomingCall.toString(), (para) => { this._logger.warn("sphone incomingCall: " + para.caller + ", " + para.cid); if (para.orgCaller == "*5*get") { // this._conference.answerMemberCall(para.id); return; } let callType = iceAPI.convertIceCallType(para.calltype); if (callType == CallType.Conference || callType == CallType.MCUMetting) { let isMCU = false; if (callType == CallType.MCUMetting) { isMCU = true; } let conf = this.conferences[para.cid]; let processConferenceCall = () => { let conf = this.conferences[para.cid]; if (conf != null && (conf.state != ConferenceState.Leave || conf.isReEnter)) { conf.isMCU = isMCU; conf._callId = para.id; conf.caller = para.caller; conf.isSchedule = para.isScheduleConference; // conf.isVideo = para.isVideo; if (conf.isReEnter) { conf.isReEnter = false; } conf.sipCall = para.invitation; conf.accept(conf._mediaControl, conf.isVideo); // this.alice.answerVideo(conf._callId, conf._mediaControl as HTMLVideoElement); } else { // if (para.caller != LoginInfo.getInstance().currentNumber || para.isScheduleConference) { { if (conf == null) { // this._incomingCallEventEmitter.emit("event", {number: para.caller}); conf = new ConferenceImp(null, null, null, this._iceServer, this.alice); conf.isMCU = isMCU; conf._sessionId = para.cid; this.conferences[para.cid] = conf; } conf._callId = para.id; conf.caller = para.caller; conf.isSchedule = para.isScheduleConference; conf.sipCall = para.invitation; // conf.isVideo = para.isVideo; conf.stateChange.on((para) => { if (para.state == ConferenceState.Terminaled) { delete this.conferences[conf._sessionId]; this._logger.warn("remove conf :" + conf._sessionId); } }); this._receiveConferenceInviteEventEmitter.emit("event", { conference: conf }); // this._eventEmitter.emit(DispatcherClientEventName.IncomingCall.toString() , call); } } }; if (conf == null) { setTimeout(() => { processConferenceCall(); }, 500); } else { processConferenceCall(); } return; } else if (callType == CallType.Tempintercom || callType == CallType.Intercom) { this._logger.warn("incoming temp intercom"); let processConferenceCall = () => { // let intercom = this.intercoms[para.cid]; let intercom = this.intercoms[para.cid]; if (intercom != null && para.caller == this._userNumber) { intercom._callId = para.id; intercom._sessionId = para.cid; this.intercoms[para.cid] = intercom; if (callType == CallType.Tempintercom) { intercom.groupNumber = para.orgCaller.replace("*9*", "").substr(0, para.orgCaller.indexOf("~") - 3); } // this.alice.answerVideo(intercom._callId, intercom._mediaControl as HTMLVideoElement); intercom.accept(intercom._mediaControl); } else { // this._incomingCallEventEmitter.emit("event", {number: para.caller}); intercom = new IntercomImp(null, null, null, this._iceServer, this.alice); intercom._callId = para.id; intercom._sessionId = para.cid; if (callType == CallType.Tempintercom) { intercom.groupNumber = para.orgCaller.replace("*9*", "").substr(0, para.orgCaller.indexOf("~") - 3); } else { intercom.groupNumber = para.orgCaller.replace(para.caller, "").replace("~", ""); } this._logger.warn("intercom groupnumber:" + intercom.groupNumber); this.intercoms[para.cid] = intercom; this._receiveIntercomInviteEventEmitter.emit("event", { intercom: intercom }); // this._eventEmitter.emit(DispatcherClientEventName.IncomingCall.toString() , call); } }; setTimeout(() => { processConferenceCall(); }, 500); return; } else if (callType == CallType.Broadcast) { this._logger.warn("incoming broadcast"); // let intercom = this.intercoms[para.cid]; // let broadcast = this._tempOutgoningBroadcast; // this._tempOutgoningBroadcast = null; let broadcast = this.broadcasts[para.cid]; if (broadcast != null && para.caller == this._userNumber) { broadcast._callId = para.id; broadcast._sessionId = para.cid; broadcast.caller = para.caller; this.broadcasts[para.cid] = broadcast; // this.alice.answerVideo(broadcast._callId, broadcast._mediaControl as HTMLVideoElement); broadcast.accept(broadcast._mediaControl); } else { // this._incomingCallEventEmitter.emit("event", {number: para.caller}); broadcast = new BroadcastImp(null, null, null, this._iceServer, this.alice); broadcast._callId = para.id; broadcast._sessionId = para.cid; broadcast.caller = para.caller; // broadcast.groupNumber = para.orgCaller.replace( para.caller, "" ).replace("~", ""); // this._logger.warn("intercom groupnumber:" + broadcast.groupNumber); this.broadcasts[para.cid] = broadcast; this._receiveBroadcastInviteEventEmitter.emit("event", { broadcast: broadcast }); // this._eventEmitter.emit(DispatcherClientEventName.IncomingCall.toString() , call); } return; } // else if (this._interposConference != null && this._interposConference._interposeCalled == para.caller) { else if (this._interposConference != null && (callType == CallType.Monitor || callType == CallType.Interpose)) { let conf = this._interposConference; conf._callId = para.id; conf._sessionId = para.cid; this.conferences[para.cid] = conf; this._interposConference = null; this._logger.warn("auto answer interpose conf call isvideo: " + conf.isVideo); // this.alice.answerVideo(conf._callId, conf._mediaControl as HTMLVideoElement); let isVideoConf = conf.isVideo; if (callType == CallType.Monitor) { conf.monitorVideoCall = true; isVideoConf = false; } conf.accept(conf._mediaControl, isVideoConf); return; } else if (this._tempOutgoingCall != null && this._tempOutgoingCall.number == para.caller); var call = this.calls[para.cid]; if (call == null) { let otherNumber = para.orgCaller.replace("*5*", ""); this._logger.warn("incomingcall not found in calls otherNumber: " + otherNumber); call = this.unInitOutgoingCalls[otherNumber]; if (call != null) { call._sessionId = para.cid; // call.isVideo = para.isVideo; this.calls[para.cid] = call; this._logger.warn("init session by incomingcall otherNumber: " + otherNumber); delete this.unInitOutgoingCalls[otherNumber]; } else { if (this._tempOutgoingCall != null && para.caller == this._tempOutgoingCall.number) { this._logger.warn("tmp incoming back call"); call = this._tempOutgoingCall; call._sessionId = para.cid; this.calls[para.cid] = call; } } } if (call != null) { call._callId = para.id; // call.isVideo = para.isVideo; // call.answer(call._mediaControl , call.isVideo); call.sipCall = para.invitation; this._logger.warn("auto answer call " + call.number + ", sessionId: " + para.cid); call.answer(call._mediaControl, call.isVideo); // this.alice.answerVideo(call._callId, call._mediaControl as HTMLVideoElement); } else if (this.unInitOutGoingSubstitue != null) { this.unInitOutGoingSubstitue._callId = para.id; this.unInitOutGoingSubstitue._sessionId = para.cid; // call.isVideo = para.isVideo; // call.answer(call._mediaControl , call.isVideo); this.unInitOutGoingSubstitue.sipCall = para.invitation; this._logger.warn("auto answer call unInitOutGoingSubstitue " + this.unInitOutGoingSubstitue.number + ", sessionId: " + para.cid); this.unInitOutGoingSubstitue.answer(this.unInitOutGoingSubstitue._mediaControl, this.unInitOutGoingSubstitue.isVideo); this.unInitOutGoingSubstitue = null; } else { if (para.caller != LoginInfo.getInstance().currentNumber) { // this._incomingCallEventEmitter.emit("event", {number: para.caller}); let call = new CallImp(para.caller, null, this._iceServer, this.alice); this.setCallStateChangeListener(call); call._callId = para.id; call.sipCall = para.invitation; call._sessionId = para.cid; call.callType = callType; // call.isVideo = para.isVideo; this.calls[para.cid] = call; // call.callStateChange.on((para: callStateEventPara)=>{ // if (para.state == CallState.Init) { // // this.calls[call._sessionId] = call; // } // }); //加延迟,因为要等sessionStateChange事件过来更新call里边的经纬度,对方信息等。 let processIncomingCall = () => { this._incomingCallEventEmitter.emit("event", { call: call }); }; setTimeout(() => { processIncomingCall(); }, 500); // this._eventEmitter.emit(DispatcherClientEventName.IncomingCall.toString() , call); } else { console.warn("receive incomingcall self!!"); } } }); return this.repeatRegist(); } /** * 注销 */ unRegist() { this._userRegist = false; this._iceServer.unRegist(); if (this.alice != null) { return this.alice.unregister(); } else { return Promise.resolve(); } } //#region 组织结构用户信息查询 // GetGroupTree() { // let result = this._iceServer.getGroupTree(); // this._logger.log(result); // return result; // } /** * 获取分组(可以获取到分组下的子分组,但是不会获取子用户) * @returns 分组列表 */ getGroups() { return this._iceServer.getRootGroups(); } /** * 获取组详情(包括分组所属的子用户) * @param groupId 分组ID */ getGroupDetailById(groupId) { return this._iceServer.getGroupWithUsersById(groupId); } /** * 获取28281设备以及分组 * @returns 设备分组 */ get28281Groups() { return this._iceServer.get28281Groups(); } /** * 获取指定分组下的监控列表 * @param deviceId 设备ID * @param groupId 组ID * @returns 监控列表 */ getMonitors28281ByGroupId(deviceId, groupId) { return this._iceServer.getMonitors28281ByGroupId(deviceId, groupId); } /** * 获取本地监控 * @returns 本地监控列表 */ getLocalMonitors() { return this._iceServer.getLocalVideos(); } getBusinessClient() { return BusinessClient.getInstance(); } /** * 获取当前用户详情 * @returns {"number":"2003","name":"2003","longitude":0,"latitude":0,"calls":[],"conferences":[]} */ getUserDetail() { return this._iceServer.getUserDetail(); } /** * 获取当前用户详情 * @param number * @returns {"number":"2003","name":"2003","longitude":0,"latitude":0,"calls":[],"conferences":[]} */ getUserDetailByNumber(number) { return this._iceServer.getUserDetailByNumber(number).then((detail) => { return this._iceServer.GetUserSessions(number).then((sessions) => { let calls = new Array(); let conferences = new Array(); sessions.forEach(element => { //if (element.state == Dispatcher.CallState.CallStateConnect) { switch (element.type) { case Dispatcher.CallType.CallTypeSingle: case Dispatcher.CallType.CallTypeSingle2: calls.push({ id: element.cid, called: element.othernum, caller: element.callingnum }); break; case Dispatcher.CallType.CallTypeTemporary: conferences.push({ id: element.cid, name: element.othernum }); break; default: break; } // } }); const userDetail = { number: detail.employeeId, name: detail.name, longitude: detail.longitude, latitude: detail.latitude, calls: calls, conferences: conferences }; return Promise.resolve(userDetail); }); }); } /** * 获取当前用户详情返回JSON * @param number * @returns {\"ret\":\"ok\",\"id\":5622,\"employeeId\":\"2000\",\"password\":\"\",\"employeeLevel\":10,\"departId\":0,\"roleId\":0,\"name\":\"2000\",\"addTime\":\"20160229113618\",\"modifyTime\":\"20210329120415\",\"theState\":1,\"theType\":0,\"remark\":\"\",\"latitude\":0,\"longitude\":0,\"isRecord\":1,\"monName\":\"\",\"monPasswd\":\"123456\",\"monIp\":\"\",\"monPort\":0,\"monFlag\":\"\",\"isVideo\":1,\"nightnumber\":\"\"}" */ getUserDetailByNumber1(number) { return this._iceServer.getUserDetailByNumber1(number); } /** * 获取用户所有会话 * @param number 用户号码 * @returns [{"cid":"AC44E540-2129-4B92-B45E-08868E2AD94C","callingnum":"2004","callingname":"2004","othernum":"2001","othername":"2001","direction":{"_name":"CallDirectOut","_value":1},"state":{"_name":"CallStateConnect","_value":6},"type":{"_name":"CallTypeSingle2","_value":12},"level":10,"isVideo":{"_name":"MediaTypeVideo","_value":2},"RoadParameters":""}] */ getUserSessions(number) { return this._iceServer.GetUserSessions(number); } getOrgId() { return this._iceServer.getUserDetail().then((result) => { // this._logger.warn(JSON.stringify(result)); // this._logger.warn(result.monFlag); return Promise.resolve(result.monFlag); }).catch((error) => { return Promise.reject(error); }); } /** * 获取所有在线用户 * @returns 在线用户的json */ getOnlineUsers() { return this._iceServer.getAllRegistedUsers(); } getOnlineUsersById(ids) { return this._iceServer.getAllRegistedUsersById(ids); } //#endregion 组织结构用户信息查询 /** * 音频呼叫 * @param targetNumber 呼叫号码 * @param remoteVideo 控件 */ makeCallAudio(targetNumber, remoteVideo) { this.makecallInner(false, targetNumber, remoteVideo, null); } /** * * @param number 呼叫号码 * @param mediaControl 呼叫使用的媒体控件 * @param isVideo true是视频呼叫, false是音频呼叫 * @returns 呼叫对象 */ makeCall(number, mediaControl, isVideo) { if (this.unInitOutgoingCalls[number] != null) { // this._logger.error("there is same number call outgoing!"); return Promise.reject("busy, wait moment"); } let call = new CallImp(number, mediaControl, this._iceServer, this.alice); call.isCaller = true; this.setCallStateChangeListener(call); this.unInitOutgoingCalls[number] = call; // call.callStateChange.on((para: callStateEventPara)=>{ // if (para.state == CallState.Init) { // // this.calls[call._sessionId] = call; // } // }); return call.invite(isVideo).then(() => { // this.calls[call._sessionId] = call; return Promise.resolve(call); }).catch((reason) => { delete this.unInitOutgoingCalls[number]; return Promise.reject(reason); }); // this._calls.push(call); } /** * 打开监控 * @param number 号码 * @param mediaControl 视频控件 * @returns 监控对象 */ openMonitor(number, mediaControl) { if (this.unInitOutgoingCalls[number] != null) { this._logger.error("there is same number call outgoing!"); return Promise.reject("busy"); } let call = new CallImp(number, mediaControl, this._iceServer, this.alice); call.offerVideo = false; // call.aquireMdeia = false; this.setCallStateChangeListener(call); this.unInitOutgoingCalls[number] = call; // call.callStateChange.on((para: callStateEventPara)=>{ // if (para.state == CallState.Init) { // // this.calls[call._sessionId] = call; // } // }); return call.invite(true, 1).then(() => { // this.calls[call._sessionId] = call; return Promise.resolve(call); }).catch((reason) => { delete this.unInitOutgoingCalls[number]; return Promise.reject(reason); }); // this._calls.push(call); } /** * 打开智能监控 * @param number 号码 * @param mediaControl 视频控件 * @param isPreCamera 是否是前置摄像头 * @param isAutoAnswer 是否自动应答 * @returns 监控对象 */ openMonitor3g(number, mediaControl, isPreCamera, isAutoAnswer) { if (this.unInitOutgoingCalls[number] != null) { this._logger.error("there is same number call outgoing!"); return Promise.reject("busy"); } let call = new CallImp(number, mediaControl, this._iceServer, this.alice); call.offerVideo = false; this.setCallStateChangeListener(call); this.unInitOutgoingCalls[number] = call; // call.callStateChange.on((para: callStateEventPara)=>{ // if (para.state == CallState.Init) { // // this.calls[call._sessionId] = call; // } // }); return call.open(isPreCamera, isAutoAnswer).then(() => { // this.calls[call._sessionId] = call; return Promise.resolve(call); }).catch((reason) => { delete this.unInitOutgoingCalls[number]; return Promise.reject(reason); }); // this._calls.push(call); } // /** // * 视频接听 // * @param callId id // * @param videoControl 控件 // */ // answerCall(callId: string, mediaControl: HTMLMediaElement, isVideo: boolean) { // this._logger.log(`[${this.alice.id}] call received`); // this.alice.answerVideo(callId, mediaControl as HTMLVideoElement); // // .catch((error: Error) => { // // this._logger.error(`[${alice.id}] failed to answer call`); // // this._logger.error(error); // // alert("Failed to answer call.\n" + error); // // }); // } /** * 开启无人值守 * @param number 值守号码 */ startUnattended(number) { // this.unAttended = true; return this._iceServer.startAttended(number); } /** * 关闭无人值守 */ stopUnattended() { // this.unAttended = false; return this._iceServer.startAttended(""); } /** * 获取无人值守号码 * @returns 无人值守号码 */ getUnattendedState() { return this._iceServer.getUnattendedState(); } /** * 绑定左右话柄 * @param leftPhone 左话柄 * @param rightPhone 右话柄 */ bindPhoneHandle(leftPhone, rightPhone) { return this._iceServer.bindPhoneHandle(leftPhone, rightPhone).then((result) => { this._logger.log("bind left right phone success: " + JSON.stringify(result)); LoginInfo.getInstance().leftPhone = leftPhone; LoginInfo.getInstance().rightPhone = rightPhone; return Promise.resolve(); }).catch((reason) => { this._logger.log("bind left right phone fail: " + JSON.stringify(reason)); return Promise.reject(reason); }); } /** * 左手柄呼叫 * @param number 呼叫号码 * @param mediaControl 呼叫使用的媒体控件 * @param isVideo true是视频呼叫, false是音频呼叫 * @returns 呼叫对象 */ makeCallByLeftPhone(number, mediaControl, isVideo) { let call = new CallImp(number, mediaControl, this._iceServer, this.alice); this.setCallStateChangeListener(call); // call.callStateChange.on((para: callStateEventPara)=>{ // if (para.state == CallState.Init) { // // this.calls[call._sessionId] = call; // } // }); return call.inviteByLeftPhone(isVideo).then(() => { this.calls[call._sessionId] = call; return Promise.resolve(call); }).catch((reason) => { return Promise.reject(reason); }); } /** * 右手柄呼叫 * @param number 呼叫号码 * @param mediaControl 呼叫使用的媒体控件 * @param isVideo true是视频呼叫, false是音频呼叫 * @returns 呼叫对象 */ makeCallByRightPhone(number, isVideo) { this._iceServer.makecallByRightPhone(number, isVideo); } //#region dispatch SubsituteCall(dstNumber, mediaControl, isVideo, cid) { // let call = new CallImp(dstNumber, mediaControl, this._iceServer, this.alice); if (this.unInitOutGoingSubstitue != null) { this._logger.error("there is a substitue call outgoing, wait a moment"); return Promise.reject("busy"); } let call = new CallImp(dstNumber, mediaControl, this._iceServer, this.alice); this.unInitOutGoingSubstitue = call; // call.callStateChange.on((para: callStateEventPara)=>{ // if (para.state == CallState.Init) { // // this.calls[call._sessionId] = call; // } // }); return call.SubsituteCall(cid).then(() => { this.calls[call._sessionId] = call; return Promise.resolve(call); }).catch((reason) => { this.unInitOutGoingSubstitue = null; return Promise.reject(reason); }); // return this._iceServer.SubsituteCall(dstNumber, ""); } /** * 强插 * @param callInfo 呼叫信息 * @param mediaControl 视频控件 * @returns conference 强插之后单呼变成三方会议的对象 */ forceInterposeCall(callInfo, mediaControl) { this._interposConference = new ConferenceImp(mediaControl, null, null, this._iceServer, this.alice); this._interposConference._interposeCalled = callInfo.called; return this._iceServer.forceInterposeCall(callInfo.id, callInfo.caller).then((result) => { return Promise.resolve(this._interposConference); }).catch((reason) => { return Promise.reject(reason); }); } /** * 强拆 * @param callInfo 呼叫信息 * @param mediaControl 视频控件 */ forceRemoveOther(callInfo, mediaControl, number = callInfo.caller) { this._tempOutgoingCall = new CallImp(number, mediaControl, this._iceServer, this.alice); this.setCallStateChangeListener(this._tempOutgoingCall); return this._iceServer.forceRemoveOther(callInfo.id, number).then((result) => { return Promise.resolve(this._tempOutgoingCall); }); } /** * 监听 需要先通过getUserDetailByNumber()方法获取要监听号码的通话信息列表,然后指定要监听的那路通话信息作为第一个参数 * @param callInfo 呼叫信息 * @param mediaControl 视频控件 * @returns conference 监听之后单呼变成三方会议的对象 */ monitorCall(callInfo, mediaControl) { this._interposConference = new ConferenceImp(mediaControl, null, null, this._iceServer, this.alice); this._interposConference._interposeCalled = callInfo.called; return this._iceServer.MonitorCall(callInfo.id, callInfo.caller).then((result) => { return Promise.resolve(this._interposConference); }); } /** * 强断 * @param callInfo 呼叫信息 */ forceRemoveCall(callInfo) { return this._iceServer.forceRemoveCall(callInfo.id, callInfo.caller); } //#endregion dispatch //#region conference /** * 发起会议 * @param members 成员列表 * @param videoControl 控件 * @param isVideo True为视频会议, false为音频会议 * @return 会议对象 */ startConference(members, videoControl, name, isVideo = true) { return this.startConferenceByNumber(members, videoControl, name, isVideo, LoginInfo.getInstance().currentNumber); } // startConferenceByLeftPhone(members: Array, videoControl: HTMLVideoElement, name: string, isVideo: boolean = true) { // return this.startConferenceByNumber(members, videoControl, name, isVideo, LoginInfo.getInstance().leftPhone); // } // startConferenceByRightPhone(members: Array, videoControl: HTMLVideoElement, name: string, isVideo: boolean = true) { // return this.startConferenceByNumber(members, videoControl, name, isVideo, LoginInfo.getInstance().rightPhone); // } enterConference(conferenceId) { return this._iceServer.conferenceAddMember(conferenceId, this._userNumber); } /** * 创建预约会议 * @param members 成员列表 * @param name 主题 * @param isVideo true 视频会议, false 音频会议 * @param startTime 开始时间 * @returns */ createShecduleConference(members, name, isVideo, startTime) { return this._iceServer.createShecduleConf(members, isVideo, startTime, name).then((result) => { this._logger.warn("create scheduel result: " + result); let iceResult = JSON.parse(result); // let isVideo = false; // if (iceResult.media_type == "1") { // isVideo = true; // } // let startTime = new Date(iceResult.start_time); const schedule = { name: iceResult.meeting_name, sessionId: iceResult.meeting_cid, isVideo: isVideo, startTime: startTime, members: members }; return Promise.resolve(schedule); }).catch((reason) => { return Promise.reject(reason); }); } /** * 修改预约会议 * @param scheduleInfo 预约会议信息 * @returns */ modifyShecduleConference(scheduleInfo) { return this._iceServer.fixScheduleConf(scheduleInfo.sessionId, scheduleInfo.members, scheduleInfo.isVideo, scheduleInfo.startTime, scheduleInfo.name); } /** * 获取预约会议 * @returns 预约会议列表 */ getScheduleConferences() { return this._iceServer.getScheduleConf().then((result) => { let jsonConfs = JSON.parse(result); let confs = jsonConfs.meetings; let infos = new Array(); if (confs != null) { confs.forEach(element => { let isVideo = false; if (element.media_type == "2") { isVideo = true; } let startTime = new Date(element.start_time); let members = new Array(); let membersStr = element.members; membersStr.split(",").forEach(member => { members.push(member); }); const schedule = { name: element.meeting_name, sessionId: element.cid, isVideo: isVideo, startTime: startTime, members: members }; infos.push(schedule); }); } return Promise.resolve(infos); }).catch((reason) => { return Promise.reject(reason); }); } /** * 删除预约会议 * @param scheduleInfo 预约会议信息 * @returns */ deleteScheduleConferences(scheduleInfo) { return this._iceServer.deleteScheduleConf(scheduleInfo.sessionId); } //#endregion conference /** * 发起临时对讲 * @param members 成员列表 * @param mediaControl 视频控件 * @param name 对讲组名称可填空 * @param caller 指定发起人,默认是登录的账号,如果配置了左右话柄,并且设置了话柄模式,那么默认发起人是当前选中模式的话柄 * @returns 对讲对象 */ startTempIntercom(members, mediaControl, name, caller = LoginInfo.getInstance().currentNumber) { // let intercom = new IntercomImp(mediaControl, members, name, this._iceServer, this.alice); let tempOutgoningIntercom = new IntercomImp(mediaControl, members, name, this._iceServer, this.alice); return tempOutgoningIntercom.start(caller).then((result) => { tempOutgoningIntercom._sessionId = result.cid; tempOutgoningIntercom.stateChange.on((para) => { if (para.state == IntercomState.Terminaled) { delete this.intercoms[tempOutgoningIntercom._sessionId]; } }); this.intercoms[tempOutgoningIntercom._sessionId] = tempOutgoningIntercom; // this.intercoms[intercom._sessionId] = intercom; return Promise.resolve(tempOutgoningIntercom); }).catch((reason) => { return Promise.reject(reason); }); // return Promise.resolve(this._tempOutgoningIntercom); // this._iceServer.createConference(members, true); } /** * 发起对讲 * @param groupNumber 组号 * @param mediaControl 视频控件 * @param caller 指定发起人,默认是登录的账号,如果配置了左右话柄,并且设置了话柄模式,那么默认发起人是当前选中模式的话柄 * @returns 对讲对象 */ startIntercom(groupNumber, mediaControl, caller = LoginInfo.getInstance().currentNumber) { let tempOutgoningIntercom = new IntercomImp(mediaControl, null, "", this._iceServer, this.alice); tempOutgoningIntercom.groupNumber = groupNumber; // let tmpIntercom = this._tempOutgoingCall; // let intercom = new IntercomImp(mediaControl, null, "", this._iceServer, this.alice); // intercom.groupNumber = groupNumber; return tempOutgoningIntercom.applySpeak(caller).then((result) => { // this.intercoms[intercom._sessionId] = intercom; tempOutgoningIntercom._sessionId = result.cid; tempOutgoningIntercom.stateChange.on((para) => { if (para.state == IntercomState.Terminaled) { delete this.intercoms[tempOutgoningIntercom._sessionId]; } }); this.intercoms[tempOutgoningIntercom._sessionId] = tempOutgoningIntercom; return Promise.resolve(tempOutgoningIntercom); // return Promise.resolve(tmpIntercom); }).catch((reason) => { return Promise.reject(reason); }); // return Promise.resolve(this._tempOutgoningIntercom); } /** * 发起广播 * @param members 成员列表 * @param mediaControl 视频控件 * @param name 广播主题 * @param caller 广播发起者,默认是当前登录用户 * @returns 广播对象 */ startBroadcast(members, mediaControl, name, caller = LoginInfo.getInstance().currentNumber) { // let intercom = new IntercomImp(mediaControl, members, name, this._iceServer, this.alice); this._tempOutgoningBroadcast = new BroadcastImp(mediaControl, members, name, this._iceServer, this.alice); return this._tempOutgoningBroadcast.start(caller).then(() => { this._tempOutgoningBroadcast.stateChange.on((para) => { if (para.state == BroadcastState.Terminaled) { delete this.broadcasts[para.sender.sessionId]; } }); this.broadcasts[this._tempOutgoningBroadcast._sessionId] = this._tempOutgoningBroadcast; let eventObj = this._tempOutgoningBroadcast; this._tempOutgoningBroadcast = null; return Promise.resolve(eventObj); }).catch((reason) => { return Promise.reject(reason); }); // return Promise.resolve(this._tempOutgoningBroadcast); // this._iceServer.createConference(members, true); } // startBroadcastByLeftPhone(members: Array, mediaControl: HTMLMediaElement, name: string) { // return this.startBroadcast(members, mediaControl, name, LoginInfo.getInstance().leftPhone); // } // startBroadcastByRightPhone(members: Array, mediaControl: HTMLMediaElement, name: string) { // return this.startBroadcast(members, mediaControl, name, LoginInfo.getInstance().rightPhone); // } //#region 解码器 /** * 获取解码器 * @returns */ getDecoderDevices() { return this._iceServer.getDecoderDevices(); } /** * 获取解码器详情 * @param decoderId 解码器ID * @returns */ getDecoderDeviceConfig(decoderId) { return this._iceServer.getDecoderDeviceConfig(decoderId); } /** * 获取解码通道状态 * @param decoderId 解码器ID * @param channelId 通道ID * @returns true 为通道被占用, false 为未被占用 */ getDecoderDeviceChannelState(decoderId, channelId) { return this._iceServer.getDecoderChannelState(decoderId, channelId); } /** * 设置解码器分屏信息 * @param decoderId 解码器ID * @param windows "[{ \"WindowNO\": \"16777217\", \"LayerIndex\": \"67108865\", \"Enable\": \"1\", \"WinMode\": \"" + winMode + "\", \"OperateMode\": \"1\", \"x\": \"1920\", \"y\": \"1920\", \"w\": \"1920\", \"h\": \"1920\" }]"; */ setDecoderDeviceWindows(decoderId, windows) { return this._iceServer.setDecoderWindows(decoderId, windows); } //#endregion 解码器 //#region GPS /** * 上传GIS信息 * @param latitude 经度 * @param longitude 纬度 * @param grmc * @returns */ uploadGisInfo(latitude, longitude, grmc) { return this._iceServer.uploadGISInfo(latitude, longitude, grmc); } /** * 订阅指定号码的GIS信息 * 订阅成功后指定号码的GIS信息改变时服务回推送给过来 * @param numbers 订阅的号码列表 * @returns */ setGisTrace(numbers) { return this._iceServer.setGisTrace(numbers); } /** * 取消订阅指定号码的GIS信息 * @param numbers 订阅的号码列表 * @returns */ cancelGisTrace(numbers) { return this._iceServer.cancelGisTrace(numbers); } /** * 获取GIS信息 * @param number 号码 * @returns */ getGisPosition(number) { return this._iceServer.getGisPosition(number); } /** * 获取指定时间段的GIS轨迹信息 * @param number 号码 * @param beginTime 开始时间 * @param endTime 结束时间 * @returns */ getGisHistory(number, beginTime, endTime) { return this._iceServer.getGisHistory(number, beginTime, endTime); } /** * 分页获取指定时间段的GIS轨迹信息 * @param number 号码 * @param beginTime 开始时间 * @param endTime 结束时间 * @param pagesize 每页的个数 * @param pageindex 第几页 * @returns */ getGisHistoryPage(number, beginTime, endTime, pagesize, pageindex) { return this._iceServer.getGisHistoryPage(number, beginTime, endTime, pagesize, pageindex); } /** * 获取指定矩形区域内的用户列表 * @param longmin 最小经度 * @param longmax 最大经度 * @param latmin 最小纬度 * @param latmax 最大纬度 * @param types * @returns */ getGisInfoByRectangle(longmin, longmax, latmin, latmax, types) { return this._iceServer.getGisInfoByRectangle(longmin, longmax, latmin, latmax, types); } /** * 获取指定椭圆区域内的用户列表 * @param longmin 最小经度 * @param longmax 最大经度 * @param latmin 最小纬度 * @param latmax 最大纬度 * @param types * @returns */ getGisInfoByEllipse(longmin, longmax, latmin, latmax, types) { return this._iceServer.getGisInfoByEllipse(longmin, longmax, latmin, latmax, types); } /** * 对天通设备请求离线GIS信息 * @param number 号码 * @returns */ getSmsGis(number) { return this._iceServer.getSmsGis(number); } /** * 多次对天通设备请求离线GIS信息 * @param number 号码 * @param timers 次数 * @returns */ getSmsGisRepeat(number, timers) { return this._iceServer.getSmsGisRepeat(number, timers); } //#endregion GPS //#region message /** * 发送消息 * @param number 号码 * @param message 消息 */ sendMessage(number, message) { var url = this.getUrlByNumber(number); this.alice.message(url, message); } /** * 发送消息给多个人 * @param receivers 多个接受者 * @param message 消息 */ sendGroupMessage(receivers, message) { return this._iceServer.SendMsg(message, receivers); } /** * 获取离线短信 * @param getNumber 号码 * @returns */ getOfflineMsg(getNumber) { return this._iceServer.getOfflineMsg(getNumber); } /** * 设置消息已经接收 * @param msgId 消息ID * @param number 号码 * @returns */ setMessageRecevied(msgId, number) { return this._iceServer.SetMessageRecevied(msgId, number); } /** * 申请上传文件 * @param fileName 文件名称 * @param receivers 接受者 * @param fileType 文件类型 * // 0 FileTypeNone // 1 FileTypeText // 2 FileTypePic // 3 FileTypeVoice // 4 FileTypeVideo // 5 FileTypeGisinfo // 6 FileTypePlayAudio // 7 FileTypeFax // 8 FileTypeOther // 9 FileTypePlayVideo * @returns */ applyUploadFile(fileName, receivers, fileType) { return this._iceServer.ApplyUploadFile(fileName, receivers, fileType); } /** * 设置文件上传状态 * @param fileId 文件ID * @param uploadState 上传状态 1 正在上传 2 下载完成 * @returns */ setUploadFileResult(fileId, uploadState) { return this._iceServer.SetUploadFileResult(fileId, uploadState); } /** * 设置文件以及接受 * @param fileId 文件ID * @param number 接受的号码 * @returns */ setFileReceived(fileId, number) { return this._iceServer.SetFileRecieved(fileId, number); } //#endregion message /** * 获取预案信息 * @returns */ getPlanInfo() { return this._iceServer.getPlanInfo(); } /** * 执行预案 * @param planId 预案ID * @returns */ startPlan(planId) { return this._iceServer.startPlan(planId); } //#region config /** * 设置手柄模式 * */ set handleMode(mode) { LoginInfo.getInstance().handleMode = mode; } /** * 获取手柄模式 */ get handleMode() { return LoginInfo.getInstance().handleMode; } /** * 获取麦克风配置 */ get audioInputDeviceConfig() { return LoginInfo.getInstance().audioInputDeviceConfig; } /** * 设置麦克风配置 */ set audioInputDeviceConfig(config) { LoginInfo.getInstance().audioInputDeviceConfig = config; } /** * 获取摄像头配置 */ get videoInputDeviceConfig() { return LoginInfo.getInstance().videoInputDeviceConfig; } /** * 设置摄像头配置 */ set videoInputDeviceConfig(config) { LoginInfo.getInstance().videoInputDeviceConfig = config; } /** * 获取调度机服务器版本号 * @returns 版本号 */ getServerVersion() { return this._iceServer.getVersion(); } /** * 获取公司名称 * @returns 公司名称 */ getCompanyName() { return this._iceServer.getCompanyName(); } getVersion() { return "2.2.2"; } /** * 预览摄像头 * @param videoControl 视频控件 * @returns */ previewCamera(videoControl) { return this.alice.previewCamera(videoControl); } /** * 获取绑定的左右手柄信息 * @returns */ getBindPhoneInfo() { return { leftPhone: LoginInfo.getInstance().leftPhone, rightPhone: LoginInfo.getInstance().rightPhone }; } //#endregion config enterSession(sessionId) { return this._iceServer.conferenceAddMember(sessionId, LoginInfo.getInstance().currentNumber); } // /** // * 获取录音录像服务器信息 // */ // get recordServerInfo(){ // return LoginInfo.getInstance().recordServer; // } forceKickout() { return this._iceServer.forceKickOut(this._userNumber); } /** * 获取用户登录状态 * @param number 号码 * @returns {"RegistState":"online","CurrentUUID":A46AAE93-26B7-4E6A-93F1-CD9FD7365701"} {"RegistState":"offline"} */ getLoginState(number = LoginInfo.getInstance().currentNumber) { return this._iceServer.getLoginState(number); } /** * 强制登录(当调用注册方法,返回重复注册的事件的时候,可以调用这个方法强制提出已经登录的用户,然后自己登录) */ forceLogin() { this.forceKickout().then((success) => { if (success) { return this.regist(this._registOption); } else { return Promise.reject(); } }).catch((reason) => { return Promise.reject(reason); }); } /** * 发起播放指定音频文件的广播 * @param fileId 文件ID * @param playCount 重复播放次数 * @param members 成员列表 * @returns */ startFileBroadcast(fileId, playCount, members) { return this._iceServer.startFileBroadcast(fileId, playCount, members); } getFileBroadcastState(empolyeeId) { return this._iceServer.getFileBroadcastState(empolyeeId); } //#region private method startConferenceByNumber(members, videoControl, name, isVideo = true, caller = LoginInfo.getInstance().number) { let conf = new ConferenceImp(videoControl, members, name, this._iceServer, this.alice, isVideo); conf.isCaller = true; return conf.start(caller).then(() => { this.conferences[conf._sessionId] = conf; conf.stateChange.on((para) => { if (para.state == ConferenceState.Terminaled) { delete this.conferences[conf._sessionId]; } }); // this._conference = conf; return Promise.resolve(conf); }).catch((reason) => { return Promise.reject(reason); }); // this._iceServer.createConference(members, true); } printConfs() { let result = " "; for (const key in this.conferences) { if (Object.prototype.hasOwnProperty.call(this.conferences, key)) { const element = this.conferences[key]; result += ","; if (element != null) { result += element._sessionId; } else { result += "null"; } } } return result; } getUrlByNumber(number) { return "sip:" + number + "@" + this._domain; } makecallInner(isVideo, targetNumber, remoteVideo, remoteAudio) { //_iceServer.makecall("20001", true); //const nameBob1 = "3003"; const uriBob1 = this.getUrlByNumber(targetNumber); const options = { sessionDescriptionHandlerOptions: { constraints: { audio: true, video: isVideo } } }; this.alice.call1(uriBob1, null, remoteVideo, remoteAudio, options, { requestDelegate: { onReject: (response) => { // this._logger.warn(`[${user.id}] INVITE rejected`); // let message = `Session invitation to "${targetDisplay}" rejected.\n`; // message += `Reason: ${response.message.reasonPhrase}\n`; // message += `Perhaps "${targetDisplay}" is not connected or registered?\n`; // message += `Or perhaps "${targetDisplay}" did not grant access to video?\n`; // alert(message); } } }) .catch((error) => { // this._logger.error(`[${user.id}] failed to begin session`); this._logger.error(error); alert("Failed to begin session.\n" + error); }); } makecall(targetNumber, videoControl) { //_iceServer.makecall("20001", true); //const nameBob1 = "3003"; const uriBob1 = this.getUrlByNumber(targetNumber); const options = { sessionDescriptionHandlerOptions: { constraints: { audio: true, video: true } } }; this.alice.call1(uriBob1, null, videoControl, null, options, { requestDelegate: { onReject: (response) => { // this._logger.warn(`[${user.id}] INVITE rejected`); // let message = `Session invitation to "${targetDisplay}" rejected.\n`; // message += `Reason: ${response.message.reasonPhrase}\n`; // message += `Perhaps "${targetDisplay}" is not connected or registered?\n`; // message += `Or perhaps "${targetDisplay}" did not grant access to video?\n`; // alert(message); } } }) .catch((error) => { // this._logger.error(`[${user.id}] failed to begin session`); this._logger.error(error); alert("Failed to begin session.\n" + error); }); } iceMakecall(targetNumber) { this._iceServer.makecall(targetNumber.toString(), true); } /** * 挂断 * @param callId id */ hangup(callId) { this.alice.hangup1(callId); } /** * 发起会议 * @param members 成员列表 * @param videoControl 控件 */ createConference(members, videoControl) { this._conferenceVideoControl = videoControl; this._iceServer.createConference(members, true); } /** * 接收视频会议邀请,加入会议 * @param videoContrl 控件 */ acceptConference(videoContrl) { this.answerVideo(this._conferenceCallId, videoContrl); } /** * 拒绝加入会议邀请 */ rejectConference() { this.hangup(this._conferenceCallId); } async applySpeakClick() { this._iceServer.applySpeak("20001"); } async releaseSpeakClick() { this._iceServer.releaseSpeak("20001"); } /** * 结束会议 */ endConference() { this._iceServer.endConference(this._conferenceSessionId); } /** * 添加会议成员 * @param member 要添加成员 */ async conferenceAddMember(member) { this._iceServer.conferenceAddMember(this._conferenceSessionId, member); } /** * 踢出会议成员 * @param memeber 要踢出会议都成员 */ conferenceDeleteMember(memeber) { this._iceServer.conferenceDeleteMember(this._conferenceSessionId, memeber); } /** * 获取会议成员视频 * @param member 要获取视频的成员 * @param videoContrl 控件 */ conferenceGetVideo(member, videoContrl) { this._conferenceMemberVideo = videoContrl; this._iceServer.conferenceGetVideo(this._conferenceSessionId, member); } /** * 推送指定成员的视频到会议 * @param member 要推送视频都成员 */ conferencePushMember(member) { this._iceServer.conferencePushMember(this._conferenceSessionId, member); } setCallStateChangeListener(call) { call.callStateChange.on((para) => { if (para.state == CallState.Release) { this._logger.warn("remove call "); let callImp = para.sender; delete this.calls[callImp._sessionId]; } }); } makecallWithControl(targetNumber, localVideo, remoteVideo, remoteAudio) { //_iceServer.makecall("20001", true); //const nameBob1 = "3003"; const uriBob1 = this.getUrlByNumber(targetNumber); const options = { sessionDescriptionHandlerOptions: { constraints: { audio: true, video: false } } }; this.alice.call1(uriBob1, localVideo, remoteVideo, remoteAudio, options, { requestDelegate: { onReject: (response) => { // this._logger.warn(`[${user.id}] INVITE rejected`); // let message = `Session invitation to "${targetDisplay}" rejected.\n`; // message += `Reason: ${response.message.reasonPhrase}\n`; // message += `Perhaps "${targetDisplay}" is not connected or registered?\n`; // message += `Or perhaps "${targetDisplay}" did not grant access to video?\n`; // alert(message); } } }) .catch((error) => { // this._logger.error(`[${user.id}] failed to begin session`); this._logger.error(error); alert("Failed to begin session.\n" + error); }); } /** * 视频呼叫 * @param targetNumber 呼叫号码 * @param remoteVideo 控件 */ makeCallVideo(targetNumber, remoteVideo) { this.makecallInner(true, targetNumber, remoteVideo, null); } connect() { // if (!this._userRegist || this.registState == RegistState.Registed) { if (!this._userRegist) { return; } // this.alice.disconnect(); return this.alice.connect() .then(() => { // startButton.disabled = true; // stopButton.disabled = false; // registerButton.disabled = false; //beginAlice.disabled = false; // alice.register( // undefined, // { // An example of how to get access to a SIP response message for custom handling // requestDelegate: { // onReject: (response) => { // this._logger.warn(`[${alice.id}] REGISTER rejected`); // let message = `Registration of "${response.message.to.uri.aor}" rejected.\n`; // message += `Reason: ${response.message.reasonPhrase}\n`; // alert(message); // } // } // }) // .then(() => { // // registerButton.disabled = true; // }) // .catch((error: Error) => { // this._logger.error(`[${alice.id}] failed to register`); // this._logger.error(error); // alert("Failed to register.\n" + error); // }); this.registInner(); }) .catch((error) => { this._logger.warn(`[${this.alice.id}] failed to connect`); this._logger.warn(error); // alert("Failed to connect.\n" + error); this.setRegistState(exports.RegistState.ConnectError); // this._eventEmitter.emit( DispatcherClientEventName.RegistState.toString(), RegistState.ConnectError ); }); } registInner() { DispatcherClient.getInstance().alice.register({ extraHeaders: ["auth-uuid: " + this.uuid] }, { requestDelegate: { onReject: (response) => { DispatcherClient.getInstance()._logger.warn(`[${DispatcherClient.getInstance().alice.id}] REGISTER rejected`); // let message = `Registration of "${response.message.to.uri.aor}" rejected.\n`; let message = `Registration of rejected.\n`; message += `Reason: ${response.message.reasonPhrase}\n`; message += `Reason: ${response.message.statusCode}\n`; // alert(message); let registError = exports.RegistState.OtherError; switch (response.message.statusCode) { case 403: registError = exports.RegistState.PasswordError; break; case 404: registError = exports.RegistState.UserNotExist; break; case 405: registError = exports.RegistState.RepeatLogin; break; case 406: registError = exports.RegistState.TypeError; break; case 502: case 504: registError = exports.RegistState.ConnectError; break; default: if (response.message.statusCode >= 500 && response.message.statusCode <= 599) { registError = exports.RegistState.ServerError; } break; } // DispatcherClient.getInstance().registState = registError; this.setRegistState(registError); } } }) .then(() => { // registerButton.disabled = true; }) .catch((error) => { DispatcherClient.getInstance()._logger.warn(`[${DispatcherClient.getInstance().alice.id}] failed to register`); DispatcherClient.getInstance()._logger.warn(error); // alert("Failed to register.\n" + error); }); } repeatRegist() { return DispatcherClient.getInstance().connect(); // setTimeout(DispatcherClient.getInstance().repeatRegist, 1000 * 10); } /** * 视频接听 * @param callId id * @param videoControl 控件 */ answerVideo(callId, videoControl) { this._logger.log(`[${this.alice.id}] call received`); this.alice.answerVideo(callId, videoControl); // .catch((error: Error) => { // this._logger.error(`[${alice.id}] failed to answer call`); // this._logger.error(error); // alert("Failed to answer call.\n" + error); // }); } /** * 音频接听 * @param callId id * @param control 控件 */ answerAudio(callId, control) { this._logger.log(`[${this.alice.id}] call received`); this.alice.answerAudio(callId, control); // .catch((error: Error) => { // this._logger.error(`[${alice.id}] failed to answer call`); // this._logger.error(error); // alert("Failed to answer call.\n" + error); // }); } decline(callId) { this.alice.declineById(callId); } buildUser1(webSocketServer, aor, displayName, videoLocalElement, videoRemoteElement, userType) { this._logger.log(`Creating "${name}" <${aor}>...`); let uaString = "sip"; if (userType == RegUserType.APPDevice) { uaString = "xyphone"; } else if (userType == RegUserType.Dispatcher) { uaString = "xyplat"; } // SimpleUser options const options = { aor, media: { constraints: { audio: true, video: true }, local: { video: videoLocalElement }, remote: { video: videoRemoteElement, audio: videoRemoteElement } }, userAgentOptions: { displayName, authorizationPassword: this._password, sessionDescriptionHandlerFactoryOptions: { //       constraints: { //         audio: true,  video: false //       } // RTCOfferOptions: { // offerToReceiveAudio: false, offerToReceiveVideo : false // } }, hackWssInTransport: true, userAgentString: uaString, logLevel: "debug" } }; // Create SimpleUser // const user = new SimpleUser(webSocketServer, options); const user = new Sphone(webSocketServer, options); // SimpleUser delegate // const delegate: SphoneDelegate = { // onCallCreated: makeCallCreatedCallback1(user), // onCallReceived: makeCallReceivedCallback(user), // onCallHangup: (SessionId: string | undefined) => { // return 0; // }, // // onCallHangup: makeCallHangupCallback1(user, beginButton, endButton), // onRegistered: makeRegisteredCallback1(user), // onUnregistered: makeUnregisteredCallback1(user) // }; // user.delegate = delegate; user.delegate = this._eventDelegate; return user; } changeCallCid(sessionState) { this._logger.warn("sessionStateChange session not found in calls"); let frontCid = sessionState[0].frontcid1; let frontCid2 = sessionState[0].frontcid2; let preCid; let call = null; if (frontCid != null && frontCid != "") { call = this.calls[frontCid]; if (call == null) { if (frontCid2 != null && frontCid2 != "") { call = this.calls[frontCid2]; if (call != null) { preCid = frontCid2; } } } else { preCid = frontCid; } } if (call != null) { this._logger.warn("sessionStateChange update cid by frontcid"); let otherNumber = sessionState[0].othernum; let sessionId = sessionState[0].cid; call._sessionId = sessionId; call.number = otherNumber; delete this.calls[preCid]; this.calls[sessionId] = call; this._iceServer.getKeyframe(sessionId, otherNumber).then(() => { this._logger.warn("getkeyframe success"); }).catch((reason) => { this._logger.warn("getkeyframe fail: " + reason); }); } return call; } processCallSessionStateChange(sessionState, sessionId, isVideo) { let otherNumber = sessionState[0].othernum; let call = this.calls[sessionId]; if (call == null) { call = this.changeCallCid(sessionState); } if (call == null) { call = this.unInitOutgoingCalls[otherNumber]; if (call == null); else { this._logger.warn(" init call by sessionStateChange "); call._sessionId = sessionId; this.calls[sessionId] = this.unInitOutgoingCalls[otherNumber]; delete this.unInitOutgoingCalls[otherNumber]; } } call.isVideo = isVideo; call.callstate = sessionState[0].state; try { call.otherLatitude = sessionState[0].lat; call.otherLongitude = sessionState[0].lon; call.otherMark = sessionState[0].otherremark; call.otherName = sessionState[0].othername; call.otherUserType = iceAPI.getUserTypeByIceCode(Number.parseInt(sessionState[0].othertype)); let direction = CallDirection.Out; if (sessionState[0].direction == "2") { direction = CallDirection.In; } call.otherDirection = direction; } catch (error) {} if (call.state == CallState.Release); else if (call.state == CallState.Connect) { if (sessionState[0].callingnum == LoginInfo.getInstance().leftPhone || sessionState[0].callingnum == LoginInfo.getInstance().rightPhone) { this._logger.log("callout by handanswer, request send video"); if (call.isCaller) { call.requestSendVideo(); } else { if (call._isSendVideo) { this._handleAnswerIncomingCall.emit(this.commonEventString, call); } } } } } processConferenceSessionStateChange(callType, sessionState, sessionId, isVideo) { let conf = this.conferences[sessionId]; if (conf != null) { this._logger.log("conference session state change found conference in confs"); if (callType == CallType.Interpose) { this._logger.warn("interpose conf sessionstatechange set caller myself!"); conf.caller = LoginInfo.getInstance().number; } conf.stateice = sessionState[0].state; conf.isVideo = isVideo; if (conf.state == ConferenceState.Terminaled || conf.state == ConferenceState.Kickout) { delete this.conferences[sessionId]; this._logger.warn("remove conf :" + conf._sessionId); } else if (conf.state == ConferenceState.Connected) { if (sessionState[0].callingnum == LoginInfo.getInstance().leftPhone || sessionState[0].callingnum == LoginInfo.getInstance().rightPhone) { // this._iceServer.requestSendVideoByJson(conf._sessionId); if (conf.isCaller) { this._logger.log("session state change conf is caller, auto requestSendVideo"); conf.requestSendVideo(); } else { if (conf._isSendVideo) { this._handleAnswerIncomingConference.emit(this.commonEventString, conf); } } } } } else { this._logger.warn("conference session state change not found conference sessionid " + this.printConfs()); let frontCid = sessionState[0].frontcid1; if (frontCid != null && frontCid != "") { let call = this.calls[frontCid]; if (call != null) { this._logger.warn("call change to conference by frontcid"); let conf = new ConferenceImp(call._mediaControl, null, null, this._iceServer, this.alice); conf._callId = call._callId; conf._sessionId = sessionId; this.conferences[sessionId] = conf; delete this.calls[frontCid]; call.becomeConference(conf); } } if (sessionState[0].state == "6") { if (sessionState[0].callingnum == LoginInfo.getInstance().leftPhone || sessionState[0].callingnum == LoginInfo.getInstance().rightPhone) { //start conference by handle this._logger.log(" session state change start conference by handle"); // this._iceServer.requestSendVideoByJson(conf._sessionId); // conf.requestSendVideo(); // this._incomingCallEventEmitter.emit("event", {number: para.caller}); let conf1 = new ConferenceImp(null, null, null, this._iceServer, this.alice); let isMCU = false; if (callType == CallType.MCUMetting) { isMCU = true; } conf1.isMCU = isMCU; conf1._sessionId = sessionId; this.conferences[sessionId] = conf1; this._logger.warn("add conf :" + conf1._sessionId); conf1.caller = ""; conf1.isSchedule = false; conf1.isVideo = isVideo; conf1.stateChange.on((para) => { if (para.state == ConferenceState.Terminaled) { let sender = para.sender; delete this.conferences[(sender._sessionId)]; this._logger.warn("remove conf :" + sender._sessionId); } }); // call.isVideo = para.isVideo; // if (this.conferences[sessionId] != null) { // this._logger.error("handle answer incoming conf error, maybe preincoming call not hangup"); // } this._handleAnswerIncomingConference.emit(this.commonEventString, conf1); } } } } setCookie(name, value) { var Days = 30; var exp = new Date(); exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); document.cookie = name + "=" + escape(value) + ";expires=" + exp.toUTCString(); } getCookie(name) { var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); if (arr = document.cookie.match(reg)) return unescape(arr[2]); else return null; } } (function(RegistState) { /** * 0 无 */ RegistState[RegistState["None"] = 0] = "None"; /** * 1 已注册 */ RegistState[RegistState["Registed"] = 1] = "Registed"; /** * 2 已注销 */ RegistState[RegistState["Unregisted"] = 2] = "Unregisted"; /** * 3 连接错误 */ RegistState[RegistState["ConnectError"] = 3] = "ConnectError"; /** * 4 密码错误 */ RegistState[RegistState["PasswordError"] = 4] = "PasswordError"; /** * 5 用户名不存在 */ RegistState[RegistState["UserNotExist"] = 5] = "UserNotExist"; /** * 6 服务器错误 */ RegistState[RegistState["ServerError"] = 6] = "ServerError"; /** * 7 其他错误 */ RegistState[RegistState["OtherError"] = 7] = "OtherError"; /** * 8 重复登录 */ RegistState[RegistState["RepeatLogin"] = 8] = "RepeatLogin"; /** * 9 账号类型错误 */ RegistState[RegistState["TypeError"] = 9] = "TypeError"; /** * 10 被强制下线 */ RegistState[RegistState["ForceKickout"] = 10] = "ForceKickout"; /** * 20 天通在线 */ RegistState[RegistState["TTOnline"] = 20] = "TTOnline"; })(exports.RegistState || (exports.RegistState = {})); (function(ServiceConnectState) { /** * 断开 */ ServiceConnectState[ServiceConnectState["DisConnect"] = 0] = "DisConnect"; /** * 连接 */ ServiceConnectState[ServiceConnectState["Connected"] = 1] = "Connected"; })(exports.ServiceConnectState || (exports.ServiceConnectState = {})); (function(OnlineState) { /** * 在线 */ OnlineState[OnlineState["Online"] = 0] = "Online"; /** * 离线 */ OnlineState[OnlineState["Offline"] = 1] = "Offline"; })(exports.OnlineState || (exports.OnlineState = {})); /** * 内部使用 */ var DispatcherClientEventName; (function(DispatcherClientEventName) { DispatcherClientEventName[DispatcherClientEventName["IncomingCall"] = 0] = "IncomingCall"; DispatcherClientEventName[DispatcherClientEventName["SessionStateChange"] = 1] = "SessionStateChange"; DispatcherClientEventName[DispatcherClientEventName["RegistState"] = 2] = "RegistState"; DispatcherClientEventName[DispatcherClientEventName["UserOnlineState"] = 3] = "UserOnlineState"; DispatcherClientEventName[DispatcherClientEventName["UserCallState"] = 4] = "UserCallState"; DispatcherClientEventName[DispatcherClientEventName["GisInfo"] = 5] = "GisInfo"; })(DispatcherClientEventName || (DispatcherClientEventName = {})); (function(HandleMode) { /** * 普通模式,不使用手柄 */ HandleMode[HandleMode["Normal"] = 0] = "Normal"; /** * 左手柄 */ HandleMode[HandleMode["Left"] = 1] = "Left"; /** * 右手柄 */ HandleMode[HandleMode["Right"] = 2] = "Right"; })(exports.HandleMode || (exports.HandleMode = {})); //#endregion subtype exports.DispatcherClient = DispatcherClient; return exports; }({}, ice));