hs-cti.es6.umd.js 166 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243
  1. /*!
  2. - Name HS_CTI
  3. - FileName hs-cti
  4. - Version 1.0.9
  5. - JS Standard es6
  6. - Author platformfe
  7. - Built on 2024/11/28 18:49:11
  8. - GitHub
  9. - Branch dev_20241128
  10. - CommitID 706fd026818c33cacadf0fd94aabd0180a36d19a
  11. - CommitMessage fix: 修改逻辑
  12. */
  13. (function (global, factory) {
  14. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('sip.js'), require('socket.io-client')) :
  15. typeof define === 'function' && define.amd ? define(['exports', 'sip.js', 'socket.io-client'], factory) :
  16. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.HS_CTI = {}, global.SIP, global.io));
  17. })(this, (function (exports, sip_js, io) { 'use strict';
  18. /******************************************************************************
  19. Copyright (c) Microsoft Corporation.
  20. Permission to use, copy, modify, and/or distribute this software for any
  21. purpose with or without fee is hereby granted.
  22. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  23. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  24. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  25. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  26. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  27. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29. ***************************************************************************** */
  30. /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
  31. function __decorate(decorators, target, key, desc) {
  32. var c = arguments.length,
  33. r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
  34. d;
  35. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  36. return c > 3 && r && Object.defineProperty(target, key, r), r;
  37. }
  38. function __awaiter(thisArg, _arguments, P, generator) {
  39. function adopt(value) {
  40. return value instanceof P ? value : new P(function (resolve) {
  41. resolve(value);
  42. });
  43. }
  44. return new (P || (P = Promise))(function (resolve, reject) {
  45. function fulfilled(value) {
  46. try {
  47. step(generator.next(value));
  48. } catch (e) {
  49. reject(e);
  50. }
  51. }
  52. function rejected(value) {
  53. try {
  54. step(generator["throw"](value));
  55. } catch (e) {
  56. reject(e);
  57. }
  58. }
  59. function step(result) {
  60. result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
  61. }
  62. step((generator = generator.apply(thisArg, _arguments || [])).next());
  63. });
  64. }
  65. typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
  66. var e = new Error(message);
  67. return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
  68. };
  69. /**
  70. * A session manager for SIP.js sessions.
  71. * @public
  72. */
  73. class SessionManagerPlus {
  74. /**
  75. * Constructs a new instance of the `SessionManager` class.
  76. * @param server - SIP WebSocket Server URL.
  77. * @param options - Options bucket. See {@link Web.SessionManagerOptions} for details.
  78. */
  79. constructor(server, options = {}) {
  80. /** Delegate. */
  81. Object.defineProperty(this, "delegate", {
  82. enumerable: true,
  83. configurable: true,
  84. writable: true,
  85. value: void 0
  86. });
  87. /** Sessions being managed. */
  88. Object.defineProperty(this, "managedSessions", {
  89. enumerable: true,
  90. configurable: true,
  91. writable: true,
  92. value: []
  93. });
  94. /** User agent which created sessions being managed. */
  95. Object.defineProperty(this, "userAgent", {
  96. enumerable: true,
  97. configurable: true,
  98. writable: true,
  99. value: void 0
  100. });
  101. Object.defineProperty(this, "logger", {
  102. enumerable: true,
  103. configurable: true,
  104. writable: true,
  105. value: void 0
  106. });
  107. Object.defineProperty(this, "options", {
  108. enumerable: true,
  109. configurable: true,
  110. writable: true,
  111. value: void 0
  112. });
  113. Object.defineProperty(this, "optionsPingFailure", {
  114. enumerable: true,
  115. configurable: true,
  116. writable: true,
  117. value: false
  118. });
  119. Object.defineProperty(this, "optionsPingRequest", {
  120. enumerable: true,
  121. configurable: true,
  122. writable: true,
  123. value: void 0
  124. });
  125. Object.defineProperty(this, "optionsPingRunning", {
  126. enumerable: true,
  127. configurable: true,
  128. writable: true,
  129. value: false
  130. });
  131. Object.defineProperty(this, "optionsPingTimeout", {
  132. enumerable: true,
  133. configurable: true,
  134. writable: true,
  135. value: void 0
  136. });
  137. Object.defineProperty(this, "registrationAttemptTimeout", {
  138. enumerable: true,
  139. configurable: true,
  140. writable: true,
  141. value: void 0
  142. });
  143. Object.defineProperty(this, "registerer", {
  144. enumerable: true,
  145. configurable: true,
  146. writable: true,
  147. value: void 0
  148. });
  149. Object.defineProperty(this, "registererOptions", {
  150. enumerable: true,
  151. configurable: true,
  152. writable: true,
  153. value: void 0
  154. });
  155. Object.defineProperty(this, "registererRegisterOptions", {
  156. enumerable: true,
  157. configurable: true,
  158. writable: true,
  159. value: void 0
  160. });
  161. Object.defineProperty(this, "shouldBeConnected", {
  162. enumerable: true,
  163. configurable: true,
  164. writable: true,
  165. value: false
  166. });
  167. Object.defineProperty(this, "shouldBeRegistered", {
  168. enumerable: true,
  169. configurable: true,
  170. writable: true,
  171. value: false
  172. });
  173. Object.defineProperty(this, "attemptingReconnection", {
  174. enumerable: true,
  175. configurable: true,
  176. writable: true,
  177. value: false
  178. });
  179. // Delegate
  180. this.delegate = options.delegate;
  181. // Copy options
  182. this.options = Object.assign({
  183. aor: '',
  184. autoStop: true,
  185. delegate: {},
  186. iceStopWaitingOnServerReflexive: false,
  187. managedSessionFactory: this.managedSessionFactory,
  188. maxSimultaneousSessions: 2,
  189. media: {},
  190. optionsPingInterval: -1,
  191. optionsPingRequestURI: '',
  192. reconnectionAttempts: 3,
  193. reconnectionDelay: 3,
  194. registrationRetry: false,
  195. registrationRetryInterval: 3,
  196. registerGuard: null,
  197. registererOptions: {},
  198. registererRegisterOptions: {},
  199. sendDTMFUsingSessionDescriptionHandler: false,
  200. userAgentOptions: {}
  201. }, SessionManagerPlus.stripUndefinedProperties(options));
  202. // UserAgentOptions
  203. const userAgentOptions = Object.assign({}, options.userAgentOptions);
  204. // Transport
  205. if (!userAgentOptions.transportConstructor) {
  206. userAgentOptions.transportConstructor = sip_js.Web.Transport;
  207. }
  208. // TransportOptions
  209. if (!userAgentOptions.transportOptions) {
  210. userAgentOptions.transportOptions = {
  211. server
  212. };
  213. }
  214. // URI
  215. if (!userAgentOptions.uri) {
  216. // If an AOR was provided, convert it to a URI
  217. if (options.aor) {
  218. const uri = sip_js.UserAgent.makeURI(options.aor);
  219. if (!uri) {
  220. throw new Error(`Failed to create valid URI from ${options.aor}`);
  221. }
  222. userAgentOptions.uri = uri;
  223. }
  224. }
  225. // UserAgent
  226. this.userAgent = new sip_js.UserAgent(userAgentOptions);
  227. // UserAgent's delegate
  228. this.userAgent.delegate = {
  229. // Handle connection with server established
  230. onConnect: () => {
  231. this.logger.log(`Connected`);
  232. if (this.delegate && this.delegate.onServerConnect) {
  233. this.delegate.onServerConnect();
  234. }
  235. // Attempt to register if we are supposed to be registered
  236. if (this.shouldBeRegistered) {
  237. this.register();
  238. }
  239. // Start OPTIONS pings if we are to be pinging
  240. if (this.options.optionsPingInterval > 0) {
  241. this.optionsPingStart();
  242. }
  243. },
  244. // Handle connection with server lost
  245. onDisconnect: error => __awaiter(this, void 0, void 0, function* () {
  246. var _a, _b, _c, _d;
  247. this.logger.log(`Disconnected`);
  248. // Stop OPTIONS ping if need be.
  249. let optionsPingFailure = false;
  250. if (this.options.optionsPingInterval > 0) {
  251. optionsPingFailure = this.optionsPingFailure;
  252. this.optionsPingFailure = false;
  253. this.optionsPingStop();
  254. }
  255. // If the user called `disconnect` a graceful cleanup will be done therein.
  256. // Only cleanup if network/server dropped the connection.
  257. // Only reconnect if network/server dropped the connection
  258. if (error || optionsPingFailure) {
  259. // There is no transport at this point, so we are not expecting to be able to
  260. // send messages much less get responses. So just dispose of everything without
  261. // waiting for anything to succeed.
  262. if (this.registerer) {
  263. this.logger.log(`Disposing of registerer...`);
  264. this.registerer.dispose().catch(e => {
  265. this.logger.debug(`Error occurred disposing of registerer after connection with server was lost.`);
  266. this.logger.debug(e.toString());
  267. });
  268. this.registerer = undefined;
  269. }
  270. this.managedSessions.slice().map(el => el.session).forEach(session => __awaiter(this, void 0, void 0, function* () {
  271. this.logger.log(`Disposing of session...`);
  272. session.dispose().catch(e => {
  273. this.logger.debug(`Error occurred disposing of a session after connection with server was lost.`);
  274. this.logger.debug(e.toString());
  275. });
  276. }));
  277. // Attempt to reconnect if we are supposed to be connected.
  278. if (this.shouldBeConnected) {
  279. (_b = (_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onReconnectStart) === null || _b === void 0 ? void 0 : _b.call(_a);
  280. this.attemptReconnection();
  281. }
  282. } else {
  283. // Let delgate know we have disconnected
  284. (_d = (_c = this.delegate) === null || _c === void 0 ? void 0 : _c.onServerDisconnect) === null || _d === void 0 ? void 0 : _d.call(_c, error);
  285. }
  286. }),
  287. // Handle incoming invitations
  288. onInvite: invitation => {
  289. this.logger.log(`[${invitation.id}] Received INVITE`);
  290. // Guard against a maximum number of pre-existing sessions.
  291. // An incoming INVITE request may be received at any time and/or while in the process
  292. // of sending an outgoing INVITE request. So we reject any incoming INVITE in those cases.
  293. const maxSessions = this.options.maxSimultaneousSessions;
  294. if (maxSessions !== 0 && this.managedSessions.length > maxSessions) {
  295. this.logger.warn(`[${invitation.id}] Session already in progress, rejecting INVITE...`);
  296. invitation.reject().then(() => {
  297. this.logger.log(`[${invitation.id}] Rejected INVITE`);
  298. }).catch(error => {
  299. this.logger.error(`[${invitation.id}] Failed to reject INVITE`);
  300. this.logger.error(error.toString());
  301. });
  302. return;
  303. }
  304. // Use our configured constraints as options for any Inviter created as result of a REFER
  305. const referralInviterOptions = {
  306. sessionDescriptionHandlerOptions: {
  307. constraints: this.constraints
  308. }
  309. };
  310. // Initialize our session
  311. this.initSession(invitation, referralInviterOptions);
  312. // Delegate
  313. if (this.delegate && this.delegate.onCallReceived) {
  314. this.delegate.onCallReceived(invitation);
  315. } else {
  316. this.logger.warn(`[${invitation.id}] No handler available, rejecting INVITE...`);
  317. invitation.reject().then(() => {
  318. this.logger.log(`[${invitation.id}] Rejected INVITE`);
  319. }).catch(error => {
  320. this.logger.error(`[${invitation.id}] Failed to reject INVITE`);
  321. this.logger.error(error.toString());
  322. });
  323. }
  324. },
  325. // Handle incoming messages
  326. onMessage: message => {
  327. message.accept().then(() => {
  328. if (this.delegate && this.delegate.onMessageReceived) {
  329. this.delegate.onMessageReceived(message);
  330. }
  331. });
  332. },
  333. // Handle incoming notifications
  334. onNotify: notification => {
  335. notification.accept().then(() => {
  336. if (this.delegate && this.delegate.onNotificationReceived) {
  337. this.delegate.onNotificationReceived(notification);
  338. }
  339. });
  340. }
  341. };
  342. // RegistererOptions
  343. this.registererOptions = Object.assign({}, options.registererOptions);
  344. // RegistererRegisterOptions
  345. this.registererRegisterOptions = Object.assign({}, options.registererRegisterOptions);
  346. // Retry registration on failure or rejection.
  347. if (this.options.registrationRetry) {
  348. // If the register request is rejected, try again...
  349. this.registererRegisterOptions.requestDelegate = this.registererRegisterOptions.requestDelegate || {};
  350. const existingOnReject = this.registererRegisterOptions.requestDelegate.onReject;
  351. this.registererRegisterOptions.requestDelegate.onReject = response => {
  352. existingOnReject && existingOnReject(response);
  353. // If at first we don't succeed, try try again...
  354. this.attemptRegistration();
  355. };
  356. }
  357. // Use the SIP.js logger
  358. this.logger = this.userAgent.getLogger('sip.SessionManager');
  359. // Monitor network connectivity and attempt reconnection and reregistration when we come online
  360. window.addEventListener('online', () => {
  361. this.logger.log(`Online`);
  362. if (this.shouldBeConnected) {
  363. this.connect();
  364. }
  365. });
  366. // NOTE: The autoStop option does not currently work as one likley expects.
  367. // This code is here because the "autoStop behavior" and this assoicated
  368. // implemenation has been a recurring request. So instead of removing
  369. // the implementation again (because it doesn't work) and then having
  370. // to explain agian the issue over and over again to those who want it,
  371. // we have included it here to break that cycle. The implementation is
  372. // harmless and serves to provide an explaination for those interested.
  373. if (this.options.autoStop) {
  374. // Standard operation workflow will resume after this callback exits, meaning
  375. // that any asynchronous operations are likely not going to be finished, especially
  376. // if they are guaranteed to not be executed in the current tick (promises fall
  377. // under this category, they will never be resolved synchronously by design).
  378. window.addEventListener('beforeunload', () => __awaiter(this, void 0, void 0, function* () {
  379. this.shouldBeConnected = false;
  380. this.shouldBeRegistered = false;
  381. if (this.userAgent.state !== sip_js.UserAgentState.Stopped) {
  382. // The stop() method returns a promise which will not resolve before the page unloads.
  383. yield this.userAgent.stop();
  384. }
  385. }));
  386. }
  387. }
  388. /**
  389. * Strip properties with undefined values from options.
  390. * This is a work around while waiting for missing vs undefined to be addressed (or not)...
  391. * https://github.com/Microsoft/TypeScript/issues/13195
  392. * @param options - Options to reduce
  393. */
  394. static stripUndefinedProperties(options) {
  395. return Object.keys(options).reduce((object, key) => {
  396. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  397. if (options[key] !== undefined) {
  398. object[key] = options[key];
  399. }
  400. return object;
  401. }, {});
  402. }
  403. /**
  404. * The local media stream. Undefined if call not answered.
  405. * @param session - Session to get the media stream from.
  406. */
  407. getLocalMediaStream(session) {
  408. const hsh = session.sessionDescriptionHandler;
  409. if (!hsh) {
  410. return undefined;
  411. }
  412. if (!(hsh instanceof sip_js.Web.SessionDescriptionHandler)) {
  413. throw new Error('Session description handler not instance of web SessionDescriptionHandler');
  414. }
  415. return hsh.localMediaStream;
  416. }
  417. /**
  418. * The remote media stream. Undefined if call not answered.
  419. * @param session - Session to get the media stream from.
  420. */
  421. getRemoteMediaStream(session) {
  422. const hsh = session.sessionDescriptionHandler;
  423. if (!hsh) {
  424. return undefined;
  425. }
  426. if (!(hsh instanceof sip_js.Web.SessionDescriptionHandler)) {
  427. throw new Error('Session description handler not instance of web SessionDescriptionHandler');
  428. }
  429. return hsh.remoteMediaStream;
  430. }
  431. /**
  432. * The local audio track, if available.
  433. * @param session - Session to get track from.
  434. * @deprecated Use localMediaStream and get track from the stream.
  435. */
  436. getLocalAudioTrack(session) {
  437. var _a;
  438. return (_a = this.getLocalMediaStream(session)) === null || _a === void 0 ? void 0 : _a.getTracks().find(track => track.kind === 'audio');
  439. }
  440. /**
  441. * The local video track, if available.
  442. * @param session - Session to get track from.
  443. * @deprecated Use localMediaStream and get track from the stream.
  444. */
  445. getLocalVideoTrack(session) {
  446. var _a;
  447. return (_a = this.getLocalMediaStream(session)) === null || _a === void 0 ? void 0 : _a.getTracks().find(track => track.kind === 'video');
  448. }
  449. /**
  450. * The remote audio track, if available.
  451. * @param session - Session to get track from.
  452. * @deprecated Use remoteMediaStream and get track from the stream.
  453. */
  454. getRemoteAudioTrack(session) {
  455. var _a;
  456. return (_a = this.getRemoteMediaStream(session)) === null || _a === void 0 ? void 0 : _a.getTracks().find(track => track.kind === 'audio');
  457. }
  458. /**
  459. * The remote video track, if available.
  460. * @param session - Session to get track from.
  461. * @deprecated Use remoteMediaStream and get track from the stream.
  462. */
  463. getRemoteVideoTrack(session) {
  464. var _a;
  465. return (_a = this.getRemoteMediaStream(session)) === null || _a === void 0 ? void 0 : _a.getTracks().find(track => track.kind === 'video');
  466. }
  467. /**
  468. * Connect.
  469. * @remarks
  470. * If not started, starts the UserAgent connecting the WebSocket Transport.
  471. * Otherwise reconnects the UserAgent's WebSocket Transport.
  472. * Attempts will be made to reconnect as needed.
  473. */
  474. connect() {
  475. return __awaiter(this, void 0, void 0, function* () {
  476. this.logger.log(`Connecting UserAgent...`);
  477. this.shouldBeConnected = true;
  478. if (this.userAgent.state !== sip_js.UserAgentState.Started) {
  479. return this.userAgent.start();
  480. }
  481. return this.userAgent.reconnect();
  482. });
  483. }
  484. /**
  485. * Disconnect.
  486. * @remarks
  487. * If not stopped, stops the UserAgent disconnecting the WebSocket Transport.
  488. */
  489. disconnect() {
  490. return __awaiter(this, void 0, void 0, function* () {
  491. this.logger.log(`Disconnecting UserAgent...`);
  492. if (this.userAgent.state === sip_js.UserAgentState.Stopped) {
  493. return Promise.resolve();
  494. }
  495. this.shouldBeConnected = false;
  496. this.shouldBeRegistered = false;
  497. this.registerer = undefined;
  498. return this.userAgent.stop();
  499. });
  500. }
  501. /**
  502. * Return true if transport is connected.
  503. */
  504. isConnected() {
  505. return this.userAgent.isConnected();
  506. }
  507. /**
  508. * Start receiving incoming calls.
  509. * @remarks
  510. * Send a REGISTER request for the UserAgent's AOR.
  511. * Resolves when the REGISTER request is sent, otherwise rejects.
  512. * Attempts will be made to re-register as needed.
  513. */
  514. register(registererRegisterOptions) {
  515. return __awaiter(this, void 0, void 0, function* () {
  516. this.logger.log(`Registering UserAgent...`);
  517. this.shouldBeRegistered = true;
  518. if (registererRegisterOptions !== undefined) {
  519. this.registererRegisterOptions = Object.assign({}, registererRegisterOptions);
  520. }
  521. if (!this.registerer) {
  522. this.registerer = new sip_js.Registerer(this.userAgent, this.registererOptions);
  523. this.registerer.stateChange.addListener(state => {
  524. switch (state) {
  525. case sip_js.RegistererState.Initial:
  526. break;
  527. case sip_js.RegistererState.Registered:
  528. if (this.delegate && this.delegate.onRegistered) {
  529. this.delegate.onRegistered();
  530. }
  531. break;
  532. case sip_js.RegistererState.Unregistered:
  533. if (this.delegate && this.delegate.onUnregistered) {
  534. this.delegate.onUnregistered();
  535. }
  536. // If we transition to an unregister state, attempt to get back to a registered state.
  537. if (this.shouldBeRegistered) {
  538. this.attemptRegistration();
  539. }
  540. break;
  541. case sip_js.RegistererState.Terminated:
  542. break;
  543. default:
  544. throw new Error('Unknown registerer state.');
  545. }
  546. });
  547. }
  548. return this.attemptRegistration(true);
  549. });
  550. }
  551. /**
  552. * Stop receiving incoming calls.
  553. * @remarks
  554. * Send an un-REGISTER request for the UserAgent's AOR.
  555. * Resolves when the un-REGISTER request is sent, otherwise rejects.
  556. */
  557. unregister(registererUnregisterOptions) {
  558. return __awaiter(this, void 0, void 0, function* () {
  559. this.logger.log(`Unregistering UserAgent...`);
  560. this.shouldBeRegistered = false;
  561. if (!this.registerer) {
  562. this.logger.warn(`No registerer to unregister.`);
  563. return Promise.resolve();
  564. }
  565. return this.registerer.unregister(registererUnregisterOptions).then(() => {
  566. return;
  567. });
  568. });
  569. }
  570. /**
  571. * Make an outgoing call.
  572. * @remarks
  573. * Send an INVITE request to create a new Session.
  574. * Resolves when the INVITE request is sent, otherwise rejects.
  575. * Use `onCallAnswered` delegate method to determine if Session is established.
  576. * @param destination - The target destination to call. A SIP address to send the INVITE to.
  577. * @param inviterOptions - Optional options for Inviter constructor.
  578. * @param inviterInviteOptions - Optional options for Inviter.invite().
  579. */
  580. call(destination, inviterOptions, inviterInviteOptions) {
  581. return __awaiter(this, void 0, void 0, function* () {
  582. this.logger.log(`Beginning Session...`);
  583. // Guard against a maximum number of pre-existing sessions.
  584. // An incoming INVITE request may be received at any time and/or while in the process
  585. // of sending an outgoing INVITE request. So we reject any incoming INVITE in those cases.
  586. const maxSessions = this.options.maxSimultaneousSessions;
  587. if (maxSessions !== 0 && this.managedSessions.length > maxSessions) {
  588. return Promise.reject(new Error('Maximum number of sessions already exists.'));
  589. }
  590. const target = sip_js.UserAgent.makeURI(destination);
  591. if (!target) {
  592. return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`));
  593. }
  594. // Use our configured constraints as InviterOptions if none provided
  595. if (!inviterOptions) {
  596. inviterOptions = {};
  597. }
  598. if (!inviterOptions.sessionDescriptionHandlerOptions) {
  599. inviterOptions.sessionDescriptionHandlerOptions = {};
  600. }
  601. if (!inviterOptions.sessionDescriptionHandlerOptions.constraints) {
  602. inviterOptions.sessionDescriptionHandlerOptions.constraints = this.constraints;
  603. }
  604. // If utilizing early media, add a handler to catch 183 Session Progress
  605. // messages and then to play the associated remote media (the early media).
  606. if (inviterOptions.earlyMedia) {
  607. inviterInviteOptions = inviterInviteOptions || {};
  608. inviterInviteOptions.requestDelegate = inviterInviteOptions.requestDelegate || {};
  609. const existingOnProgress = inviterInviteOptions.requestDelegate.onProgress;
  610. inviterInviteOptions.requestDelegate.onProgress = response => {
  611. if (response.message.statusCode === 183) {
  612. this.setupRemoteMedia(inviter);
  613. }
  614. existingOnProgress && existingOnProgress(response);
  615. };
  616. }
  617. // TODO: Any existing onSessionDescriptionHandler is getting clobbered here.
  618. // If we get a server reflexive candidate, stop waiting on ICE gathering to complete.
  619. // The candidate is a server reflexive candidate; the ip indicates an intermediary
  620. // address assigned by the STUN server to represent the candidate's peer anonymously.
  621. if (this.options.iceStopWaitingOnServerReflexive) {
  622. inviterOptions.delegate = inviterOptions.delegate || {};
  623. inviterOptions.delegate.onSessionDescriptionHandler = sessionDescriptionHandler => {
  624. if (!(sessionDescriptionHandler instanceof sip_js.Web.SessionDescriptionHandler)) {
  625. throw new Error('Session description handler not instance of SessionDescriptionHandler');
  626. }
  627. sessionDescriptionHandler.peerConnectionDelegate = {
  628. onicecandidate: event => {
  629. var _a;
  630. if (((_a = event.candidate) === null || _a === void 0 ? void 0 : _a.type) === 'srflx') {
  631. this.logger.log(`[${inviter.id}] Found srflx ICE candidate, stop waiting...`);
  632. // In sip.js > 0.20.1 this cast should be removed as iceGatheringComplete will be public
  633. const hsh = sessionDescriptionHandler;
  634. hsh.iceGatheringComplete();
  635. }
  636. }
  637. };
  638. };
  639. }
  640. // Create a new Inviter for the outgoing Session
  641. const inviter = new sip_js.Inviter(this.userAgent, target, inviterOptions);
  642. // Send INVITE
  643. return this.sendInvite(inviter, inviterOptions, inviterInviteOptions).then(() => {
  644. return inviter;
  645. });
  646. });
  647. }
  648. /**
  649. * Hangup a call.
  650. * @param session - Session to hangup.
  651. * @remarks
  652. * Send a BYE request, CANCEL request or reject response to end the current Session.
  653. * Resolves when the request/response is sent, otherwise rejects.
  654. * Use `onCallHangup` delegate method to determine if and when call is ended.
  655. */
  656. hangup(session) {
  657. return __awaiter(this, void 0, void 0, function* () {
  658. this.logger.log(`[${session.id}] Hangup...`);
  659. if (!this.sessionExists(session)) {
  660. return Promise.reject(new Error('Session does not exist.'));
  661. }
  662. return this.terminate(session);
  663. });
  664. }
  665. /**
  666. * Answer an incoming call.
  667. * @param session - Session to answer.
  668. * @remarks
  669. * Accept an incoming INVITE request creating a new Session.
  670. * Resolves with the response is sent, otherwise rejects.
  671. * Use `onCallAnswered` delegate method to determine if and when call is established.
  672. * @param invitationAcceptOptions - Optional options for Inviter.accept().
  673. */
  674. answer(session, invitationAcceptOptions) {
  675. return __awaiter(this, void 0, void 0, function* () {
  676. this.logger.log(`[${session.id}] Accepting Invitation...`);
  677. if (!this.sessionExists(session)) {
  678. return Promise.reject(new Error('Session does not exist.'));
  679. }
  680. if (!(session instanceof sip_js.Invitation)) {
  681. return Promise.reject(new Error('Session not instance of Invitation.'));
  682. }
  683. // Use our configured constraints as InvitationAcceptOptions if none provided
  684. if (!invitationAcceptOptions) {
  685. invitationAcceptOptions = {};
  686. }
  687. if (!invitationAcceptOptions.sessionDescriptionHandlerOptions) {
  688. invitationAcceptOptions.sessionDescriptionHandlerOptions = {};
  689. }
  690. if (!invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints) {
  691. invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints = this.constraints;
  692. }
  693. return session.accept(invitationAcceptOptions);
  694. });
  695. }
  696. /**
  697. * Decline an incoming call.
  698. * @param session - Session to decline.
  699. * @remarks
  700. * Reject an incoming INVITE request.
  701. * Resolves with the response is sent, otherwise rejects.
  702. * Use `onCallHangup` delegate method to determine if and when call is ended.
  703. */
  704. decline(session) {
  705. return __awaiter(this, void 0, void 0, function* () {
  706. this.logger.log(`[${session.id}] Rejecting Invitation...`);
  707. if (!this.sessionExists(session)) {
  708. return Promise.reject(new Error('Session does not exist.'));
  709. }
  710. if (!(session instanceof sip_js.Invitation)) {
  711. return Promise.reject(new Error('Session not instance of Invitation.'));
  712. }
  713. return session.reject();
  714. });
  715. }
  716. /**
  717. * Hold call
  718. * @param session - Session to hold.
  719. * @remarks
  720. * Send a re-INVITE with new offer indicating "hold".
  721. * Resolves when the re-INVITE request is sent, otherwise rejects.
  722. * Use `onCallHold` delegate method to determine if request is accepted or rejected.
  723. * See: https://tools.ietf.org/html/rfc6337
  724. */
  725. hold(session) {
  726. return __awaiter(this, void 0, void 0, function* () {
  727. this.logger.log(`[${session.id}] Holding session...`);
  728. return this.setHold(session, true);
  729. });
  730. }
  731. /**
  732. * Unhold call.
  733. * @param session - Session to unhold.
  734. * @remarks
  735. * Send a re-INVITE with new offer indicating "unhold".
  736. * Resolves when the re-INVITE request is sent, otherwise rejects.
  737. * Use `onCallHold` delegate method to determine if request is accepted or rejected.
  738. * See: https://tools.ietf.org/html/rfc6337
  739. */
  740. unhold(session) {
  741. return __awaiter(this, void 0, void 0, function* () {
  742. this.logger.log(`[${session.id}] Unholding session...`);
  743. return this.setHold(session, false);
  744. });
  745. }
  746. /**
  747. * Hold state.
  748. * @param session - Session to check.
  749. * @remarks
  750. * True if session is on hold.
  751. */
  752. isHeld(session) {
  753. const managedSession = this.sessionManaged(session);
  754. return managedSession ? managedSession.held : false;
  755. }
  756. /**
  757. * Mute call.
  758. * @param session - Session to mute.
  759. * @remarks
  760. * Disable sender's media tracks.
  761. */
  762. mute(session) {
  763. this.logger.log(`[${session.id}] Disabling media tracks...`);
  764. this.setMute(session, true);
  765. }
  766. /**
  767. * Unmute call.
  768. * @param session - Session to unmute.
  769. * @remarks
  770. * Enable sender's media tracks.
  771. */
  772. unmute(session) {
  773. this.logger.log(`[${session.id}] Enabling media tracks...`);
  774. this.setMute(session, false);
  775. }
  776. /**
  777. * Mute state.
  778. * @param session - Session to check.
  779. * @remarks
  780. * True if sender's media track is disabled.
  781. */
  782. isMuted(session) {
  783. const managedSession = this.sessionManaged(session);
  784. return managedSession ? managedSession.muted : false;
  785. }
  786. /**
  787. * Send DTMF.
  788. * @param session - Session to send on.
  789. * @remarks
  790. * Send an INFO request with content type application/dtmf-relay.
  791. * @param tone - Tone to send.
  792. */
  793. sendDTMF(session, tone) {
  794. return __awaiter(this, void 0, void 0, function* () {
  795. this.logger.log(`[${session.id}] Sending DTMF...`);
  796. // Validate tone
  797. if (!/^[0-9A-D#*,]$/.exec(tone)) {
  798. return Promise.reject(new Error('Invalid DTMF tone.'));
  799. }
  800. if (!this.sessionExists(session)) {
  801. return Promise.reject(new Error('Session does not exist.'));
  802. }
  803. this.logger.log(`[${session.id}] Sending DTMF tone: ${tone}`);
  804. if (this.options.sendDTMFUsingSessionDescriptionHandler) {
  805. if (!session.sessionDescriptionHandler) {
  806. return Promise.reject(new Error('Session desciption handler undefined.'));
  807. }
  808. if (!session.sessionDescriptionHandler.sendDtmf(tone)) {
  809. return Promise.reject(new Error('Failed to send DTMF'));
  810. }
  811. return Promise.resolve();
  812. } else {
  813. // As RFC 6086 states, sending DTMF via INFO is not standardized...
  814. //
  815. // Companies have been using INFO messages in order to transport
  816. // Dual-Tone Multi-Frequency (DTMF) tones. All mechanisms are
  817. // proprietary and have not been standardized.
  818. // https://tools.ietf.org/html/rfc6086#section-2
  819. //
  820. // It is however widely supported based on this draft:
  821. // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00
  822. // The UA MUST populate the "application/dtmf-relay" body, as defined
  823. // earlier, with the button pressed and the duration it was pressed
  824. // for. Technically, this actually requires the INFO to be generated
  825. // when the user *releases* the button, however if the user has still
  826. // not released a button after 5 seconds, which is the maximum duration
  827. // supported by this mechanism, the UA should generate the INFO at that
  828. // time.
  829. // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00#section-5.3
  830. const dtmf = tone;
  831. const duration = 2000;
  832. const body = {
  833. contentDisposition: 'render',
  834. contentType: 'application/dtmf-relay',
  835. content: 'Signal=' + dtmf + '\r\nDuration=' + duration
  836. };
  837. const requestOptions = {
  838. body
  839. };
  840. return session.info({
  841. requestOptions
  842. }).then(() => {
  843. return;
  844. });
  845. }
  846. });
  847. }
  848. /**
  849. * Transfer.
  850. * @param session - Session with the transferee to transfer.
  851. * @param target - The referral target.
  852. * @remarks
  853. * If target is a Session this is an attended transfer completion (REFER with Replaces),
  854. * otherwise this is a blind transfer (REFER). Attempting an attended transfer
  855. * completion on a call that has not been answered will be rejected. To implement
  856. * an attended transfer with early completion, hangup the call with the target
  857. * and execute a blind transfer to the target.
  858. */
  859. transfer(session, target, options) {
  860. return __awaiter(this, void 0, void 0, function* () {
  861. this.logger.log(`[${session.id}] Referring session...`);
  862. if (target instanceof sip_js.Session) {
  863. return session.refer(target, options).then(() => {
  864. return;
  865. });
  866. }
  867. const uri = sip_js.UserAgent.makeURI(target);
  868. if (!uri) {
  869. return Promise.reject(new Error(`Failed to create a valid URI from "${target}"`));
  870. }
  871. return session.refer(uri, options).then(() => {
  872. return;
  873. });
  874. });
  875. }
  876. /**
  877. * Send a message.
  878. * @remarks
  879. * Send a MESSAGE request.
  880. * @param destination - The target destination for the message. A SIP address to send the MESSAGE to.
  881. */
  882. message(destination, message) {
  883. return __awaiter(this, void 0, void 0, function* () {
  884. this.logger.log(`Sending message...`);
  885. const target = sip_js.UserAgent.makeURI(destination);
  886. if (!target) {
  887. return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`));
  888. }
  889. return new sip_js.Messager(this.userAgent, target, message).message();
  890. });
  891. }
  892. /** Media constraints. */
  893. get constraints() {
  894. let constraints = {
  895. audio: true,
  896. video: false
  897. }; // default to audio only calls
  898. if (this.options.media.constraints) {
  899. constraints = Object.assign({}, this.options.media.constraints);
  900. }
  901. return constraints;
  902. }
  903. /**
  904. * Attempt reconnection up to `reconnectionAttempts` times.
  905. * @param reconnectionAttempt - Current attempt number.
  906. */
  907. attemptReconnection(reconnectionAttempt = 1) {
  908. var _a, _b;
  909. const reconnectionAttempts = this.options.reconnectionAttempts;
  910. const reconnectionDelay = this.options.reconnectionDelay;
  911. if (!this.shouldBeConnected) {
  912. this.logger.log(`Should not be connected currently`);
  913. return; // If intentionally disconnected, don't reconnect.
  914. }
  915. if (this.attemptingReconnection) {
  916. this.logger.log(`Reconnection attempt already in progress`);
  917. }
  918. if (reconnectionAttempt > reconnectionAttempts) {
  919. this.logger.log(`Reconnection maximum attempts reached`);
  920. (_b = (_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onReconnectFailed) === null || _b === void 0 ? void 0 : _b.call(_a);
  921. return;
  922. }
  923. if (reconnectionAttempt === 1) {
  924. this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying`);
  925. } else {
  926. this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying in ${reconnectionDelay} seconds`);
  927. }
  928. this.attemptingReconnection = true;
  929. setTimeout(() => {
  930. if (!this.shouldBeConnected) {
  931. this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - aborted`);
  932. this.attemptingReconnection = false;
  933. return; // If intentionally disconnected, don't reconnect.
  934. }
  935. this.userAgent.reconnect().then(() => {
  936. this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - succeeded`);
  937. this.attemptingReconnection = false;
  938. }).catch(error => {
  939. this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - failed`);
  940. this.logger.error(error.message);
  941. this.attemptingReconnection = false;
  942. this.attemptReconnection(++reconnectionAttempt);
  943. });
  944. }, reconnectionAttempt === 1 ? 0 : reconnectionDelay * 1000);
  945. }
  946. /**
  947. * Register to receive calls.
  948. * @param withoutDelay - If true attempt immediately, otherwise wait `registrationRetryInterval`.
  949. */
  950. attemptRegistration(withoutDelay = false) {
  951. this.logger.log(`Registration attempt ${withoutDelay ? 'without delay' : ''}`);
  952. if (!this.shouldBeRegistered) {
  953. this.logger.log(`Should not be registered currently`);
  954. return Promise.resolve();
  955. }
  956. // It only makes sense to have one attempt in progress at a time.
  957. // Perhaps we shall (or should) try once again.
  958. if (this.registrationAttemptTimeout !== undefined) {
  959. this.logger.log(`Registration attempt already in progress`);
  960. return Promise.resolve();
  961. }
  962. // Helper function to send the register request.
  963. const _register = () => {
  964. // If we do not have a registerer, it is not worth trying to register.
  965. if (!this.registerer) {
  966. this.logger.log(`Registerer undefined`);
  967. return Promise.resolve();
  968. }
  969. // If the WebSocket transport is not connected, it is not worth trying to register.
  970. // Perhpas we shall (or should) try once we are connected.
  971. if (!this.isConnected()) {
  972. this.logger.log(`User agent not connected`);
  973. return Promise.resolve();
  974. }
  975. // If the UserAgent is stopped, it is not worth trying to register.
  976. // Perhaps we shall (or should) try once the UserAgent is running.
  977. if (this.userAgent.state === sip_js.UserAgentState.Stopped) {
  978. this.logger.log(`User agent stopped`);
  979. return Promise.resolve();
  980. }
  981. // If no guard defined, we are good to proceed without any further ado.
  982. if (!this.options.registerGuard) {
  983. return this.registerer.register(this.registererRegisterOptions).then(() => {
  984. return;
  985. });
  986. }
  987. // Otherwise check to make sure the guard does not want us halt.
  988. return this.options.registerGuard().catch(error => {
  989. this.logger.log(`Register guard rejected will making registration attempt`);
  990. throw error;
  991. }).then(halt => {
  992. if (halt || !this.registerer) {
  993. return Promise.resolve();
  994. }
  995. return this.registerer.register(this.registererRegisterOptions).then(() => {
  996. return;
  997. });
  998. });
  999. };
  1000. // Compute an amount of time in seconds to wait before sending another register request.
  1001. // This is a small attempt to avoid DOS attacking our own backend in the event that a
  1002. // relatively large number of clients sychonously keep retrying register reqeusts.
  1003. // This is known to happen when the backend goes down for a period and all clients
  1004. // are attempting to register again - the backend gets slammed with synced reqeusts.
  1005. const computeRegistrationTimeout = lowerBound => {
  1006. const upperBound = lowerBound * 2;
  1007. return 1000 * (Math.random() * (upperBound - lowerBound) + lowerBound);
  1008. };
  1009. // Send register request after a delay
  1010. return new Promise((resolve, reject) => {
  1011. this.registrationAttemptTimeout = setTimeout(() => {
  1012. _register().then(() => {
  1013. this.registrationAttemptTimeout = undefined;
  1014. resolve();
  1015. }).catch(error => {
  1016. this.registrationAttemptTimeout = undefined;
  1017. if (error instanceof sip_js.RequestPendingError) {
  1018. resolve();
  1019. } else {
  1020. reject(error);
  1021. }
  1022. });
  1023. }, withoutDelay ? 0 : computeRegistrationTimeout(this.options.registrationRetryInterval));
  1024. });
  1025. }
  1026. /** Helper function to remove media from html elements. */
  1027. cleanupMedia(session) {
  1028. const managedSession = this.sessionManaged(session);
  1029. if (!managedSession) {
  1030. throw new Error('Managed session does not exist.');
  1031. }
  1032. if (managedSession.mediaLocal) {
  1033. if (managedSession.mediaLocal.video) {
  1034. managedSession.mediaLocal.video.srcObject = null;
  1035. managedSession.mediaLocal.video.pause();
  1036. }
  1037. }
  1038. if (managedSession.mediaRemote) {
  1039. if (managedSession.mediaRemote.audio) {
  1040. managedSession.mediaRemote.audio.srcObject = null;
  1041. managedSession.mediaRemote.audio.pause();
  1042. }
  1043. if (managedSession.mediaRemote.video) {
  1044. managedSession.mediaRemote.video.srcObject = null;
  1045. managedSession.mediaRemote.video.pause();
  1046. }
  1047. }
  1048. }
  1049. /** Helper function to enable/disable media tracks. */
  1050. enableReceiverTracks(session, enable) {
  1051. if (!this.sessionExists(session)) {
  1052. throw new Error('Session does not exist.');
  1053. }
  1054. const sessionDescriptionHandler = session.sessionDescriptionHandler;
  1055. if (!(sessionDescriptionHandler instanceof sip_js.Web.SessionDescriptionHandler)) {
  1056. throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");
  1057. }
  1058. sessionDescriptionHandler.enableReceiverTracks(enable);
  1059. }
  1060. /** Helper function to enable/disable media tracks. */
  1061. enableSenderTracks(session, enable) {
  1062. if (!this.sessionExists(session)) {
  1063. throw new Error('Session does not exist.');
  1064. }
  1065. const sessionDescriptionHandler = session.sessionDescriptionHandler;
  1066. if (!(sessionDescriptionHandler instanceof sip_js.Web.SessionDescriptionHandler)) {
  1067. throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");
  1068. }
  1069. sessionDescriptionHandler.enableSenderTracks(enable);
  1070. }
  1071. /**
  1072. * Setup session delegate and state change handler.
  1073. * @param session - Session to setup.
  1074. * @param referralInviterOptions - Options for any Inviter created as result of a REFER.
  1075. */
  1076. initSession(session, referralInviterOptions) {
  1077. // Add the session
  1078. this.sessionAdd(session);
  1079. // Call session created callback
  1080. if (this.delegate && this.delegate.onCallCreated) {
  1081. this.delegate.onCallCreated(session);
  1082. }
  1083. // Setup session state change handler
  1084. session.stateChange.addListener(state => {
  1085. this.logger.log(`[${session.id}] Session state changed to ${state}`);
  1086. switch (state) {
  1087. case sip_js.SessionState.Initial:
  1088. break;
  1089. case sip_js.SessionState.Establishing:
  1090. break;
  1091. case sip_js.SessionState.Established:
  1092. this.setupLocalMedia(session);
  1093. this.setupRemoteMedia(session);
  1094. if (this.delegate && this.delegate.onCallAnswered) {
  1095. this.delegate.onCallAnswered(session);
  1096. }
  1097. break;
  1098. case sip_js.SessionState.Terminating:
  1099. // fall through
  1100. case sip_js.SessionState.Terminated:
  1101. // This will already have executed if/when we fall
  1102. // through from Terminating and thus the managed
  1103. // session may already have been cleaned up.
  1104. if (this.sessionExists(session)) {
  1105. this.cleanupMedia(session);
  1106. this.sessionRemove(session);
  1107. if (this.delegate && this.delegate.onCallHangup) {
  1108. this.delegate.onCallHangup(session);
  1109. }
  1110. }
  1111. break;
  1112. default:
  1113. throw new Error('Unknown session state.');
  1114. }
  1115. });
  1116. // TODO: Any existing onInfo or onRefer delegate gets clobbered here.
  1117. // Setup delegate
  1118. session.delegate = session.delegate || {};
  1119. session.delegate.onInfo = info => {
  1120. // As RFC 6086 states, sending DTMF via INFO is not standardized...
  1121. //
  1122. // Companies have been using INFO messages in order to transport
  1123. // Dual-Tone Multi-Frequency (DTMF) tones. All mechanisms are
  1124. // proprietary and have not been standardized.
  1125. // https://tools.ietf.org/html/rfc6086#section-2
  1126. //
  1127. // It is however widely supported based on this draft:
  1128. // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00
  1129. var _a;
  1130. // FIXME: TODO: We should reject correctly...
  1131. //
  1132. // If a UA receives an INFO request associated with an Info Package that
  1133. // the UA has not indicated willingness to receive, the UA MUST send a
  1134. // 469 (Bad Info Package) response (see Section 11.6), which contains a
  1135. // Recv-Info header field with Info Packages for which the UA is willing
  1136. // to receive INFO requests.
  1137. // https://tools.ietf.org/html/rfc6086#section-4.2.2
  1138. // No delegate
  1139. if (((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onCallDTMFReceived) === undefined) {
  1140. info.reject();
  1141. return;
  1142. }
  1143. // Invalid content type
  1144. const contentType = info.request.getHeader('content-type');
  1145. if (!contentType || !/^application\/dtmf-relay/i.exec(contentType)) {
  1146. info.reject();
  1147. return;
  1148. }
  1149. // Invalid body
  1150. const body = info.request.body.split('\r\n', 2);
  1151. if (body.length !== 2) {
  1152. info.reject();
  1153. return;
  1154. }
  1155. // Invalid tone
  1156. let tone;
  1157. const toneRegExp = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;
  1158. if (body[0] !== undefined && toneRegExp.test(body[0])) {
  1159. tone = body[0].replace(toneRegExp, '$2');
  1160. }
  1161. if (!tone) {
  1162. info.reject();
  1163. return;
  1164. }
  1165. // Invalid duration
  1166. let duration;
  1167. const durationRegExp = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;
  1168. if (body[1] !== undefined && durationRegExp.test(body[1])) {
  1169. duration = parseInt(body[1].replace(durationRegExp, '$2'), 10);
  1170. }
  1171. if (!duration) {
  1172. info.reject();
  1173. return;
  1174. }
  1175. info.accept().then(() => {
  1176. if (this.delegate && this.delegate.onCallDTMFReceived) {
  1177. if (!tone || !duration) {
  1178. throw new Error('Tone or duration undefined.');
  1179. }
  1180. this.delegate.onCallDTMFReceived(session, tone, duration);
  1181. }
  1182. }).catch(error => {
  1183. this.logger.error(error.message);
  1184. });
  1185. };
  1186. session.delegate.onRefer = referral => {
  1187. referral.accept().then(() => this.sendInvite(referral.makeInviter(referralInviterOptions), referralInviterOptions)).catch(error => {
  1188. this.logger.error(error.message);
  1189. });
  1190. };
  1191. }
  1192. /**
  1193. * Periodically send OPTIONS pings and disconnect when a ping fails.
  1194. * @param requestURI - Request URI to target
  1195. * @param fromURI - From URI
  1196. * @param toURI - To URI
  1197. */
  1198. optionsPingRun(requestURI, fromURI, toURI) {
  1199. // Guard against nvalid interval
  1200. if (this.options.optionsPingInterval < 1) {
  1201. throw new Error('Invalid options ping interval.');
  1202. }
  1203. // Guard against sending a ping when there is one outstanading
  1204. if (this.optionsPingRunning) {
  1205. return;
  1206. }
  1207. this.optionsPingRunning = true;
  1208. // Setup next ping to run in future
  1209. this.optionsPingTimeout = setTimeout(() => {
  1210. this.optionsPingTimeout = undefined;
  1211. // If ping succeeds...
  1212. const onPingSuccess = () => {
  1213. // record success or failure
  1214. this.optionsPingFailure = false;
  1215. // if we are still running, queue up the next ping
  1216. if (this.optionsPingRunning) {
  1217. this.optionsPingRunning = false;
  1218. this.optionsPingRun(requestURI, fromURI, toURI);
  1219. }
  1220. };
  1221. // If ping fails...
  1222. const onPingFailure = () => {
  1223. this.logger.error('OPTIONS ping failed');
  1224. // record success or failure
  1225. this.optionsPingFailure = true;
  1226. // stop running
  1227. this.optionsPingRunning = false;
  1228. // disconnect the transport
  1229. this.userAgent.transport.disconnect().catch(error => this.logger.error(error));
  1230. };
  1231. // Create an OPTIONS request message
  1232. const core = this.userAgent.userAgentCore;
  1233. const message = core.makeOutgoingRequestMessage('OPTIONS', requestURI, fromURI, toURI, {});
  1234. // Send the request message
  1235. this.optionsPingRequest = core.request(message, {
  1236. onAccept: () => {
  1237. this.optionsPingRequest = undefined;
  1238. onPingSuccess();
  1239. },
  1240. onReject: response => {
  1241. this.optionsPingRequest = undefined;
  1242. // Ping fails on following responses...
  1243. // - 408 Request Timeout (no response was received)
  1244. // - 503 Service Unavailable (a transport layer error occured)
  1245. if (response.message.statusCode === 408 || response.message.statusCode === 503) {
  1246. onPingFailure();
  1247. } else {
  1248. onPingSuccess();
  1249. }
  1250. }
  1251. });
  1252. }, this.options.optionsPingInterval * 1000);
  1253. }
  1254. /**
  1255. * Start sending OPTIONS pings.
  1256. */
  1257. optionsPingStart() {
  1258. this.logger.log(`OPTIONS pings started`);
  1259. // Create the URIs needed to send OPTIONS pings
  1260. let requestURI, fromURI, toURI;
  1261. if (this.options.optionsPingRequestURI) {
  1262. // Use whatever specific RURI is provided.
  1263. requestURI = sip_js.UserAgent.makeURI(this.options.optionsPingRequestURI);
  1264. if (!requestURI) {
  1265. throw new Error('Failed to create Request URI.');
  1266. }
  1267. // Use the user agent's contact URI for From and To URIs
  1268. fromURI = this.userAgent.contact.uri.clone();
  1269. toURI = this.userAgent.contact.uri.clone();
  1270. } else if (this.options.aor) {
  1271. // Otherwise use the AOR provided to target the assocated registrar server.
  1272. const uri = sip_js.UserAgent.makeURI(this.options.aor);
  1273. if (!uri) {
  1274. throw new Error('Failed to create URI.');
  1275. }
  1276. requestURI = uri.clone();
  1277. requestURI.user = undefined; // target the registrar server
  1278. fromURI = uri.clone();
  1279. toURI = uri.clone();
  1280. } else {
  1281. this.logger.error('You have enabled sending OPTIONS pings and as such you must provide either ' + 'a) an AOR to register, or b) an RURI to use for the target of the OPTIONS ping requests. ');
  1282. return;
  1283. }
  1284. // Send the OPTIONS pings
  1285. this.optionsPingRun(requestURI, fromURI, toURI);
  1286. }
  1287. /**
  1288. * Stop sending OPTIONS pings.
  1289. */
  1290. optionsPingStop() {
  1291. this.logger.log(`OPTIONS pings stopped`);
  1292. this.optionsPingRunning = false;
  1293. this.optionsPingFailure = false;
  1294. if (this.optionsPingRequest) {
  1295. this.optionsPingRequest.dispose();
  1296. this.optionsPingRequest = undefined;
  1297. }
  1298. if (this.optionsPingTimeout) {
  1299. clearTimeout(this.optionsPingTimeout);
  1300. this.optionsPingTimeout = undefined;
  1301. }
  1302. }
  1303. /** Helper function to init send then send invite. */
  1304. sendInvite(inviter, inviterOptions, inviterInviteOptions) {
  1305. return __awaiter(this, void 0, void 0, function* () {
  1306. // Initialize our session
  1307. this.initSession(inviter, inviterOptions);
  1308. // Send the INVITE
  1309. return inviter.invite(inviterInviteOptions).then(() => {
  1310. this.logger.log(`[${inviter.id}] Sent INVITE`);
  1311. });
  1312. });
  1313. }
  1314. managedSessionFactory(_sessionManagerPlus, session) {
  1315. return {
  1316. session,
  1317. held: false,
  1318. muted: false
  1319. };
  1320. }
  1321. /** Helper function to add a session to the ones we are managing. */
  1322. sessionAdd(session) {
  1323. const managedSession = this.managedSessionFactory(this, session);
  1324. this.managedSessions.push(managedSession);
  1325. }
  1326. /** Helper function to check if the session is one we are managing. */
  1327. sessionExists(session) {
  1328. return this.sessionManaged(session) !== undefined;
  1329. }
  1330. /** Helper function to check if the session is one we are managing. */
  1331. sessionManaged(session) {
  1332. return this.managedSessions.find(el => el.session.id === session.id);
  1333. }
  1334. /** Helper function to remoce a session from the ones we are managing. */
  1335. sessionRemove(session) {
  1336. this.managedSessions = this.managedSessions.filter(el => el.session.id !== session.id);
  1337. }
  1338. /**
  1339. * Puts Session on hold.
  1340. * @param session - The session to set.
  1341. * @param hold - Hold on if true, off if false.
  1342. */
  1343. setHold(session, hold) {
  1344. return __awaiter(this, void 0, void 0, function* () {
  1345. if (!this.sessionExists(session)) {
  1346. return Promise.reject(new Error('Session does not exist.'));
  1347. }
  1348. // Just resolve if we are already in correct state
  1349. if (this.isHeld(session) === hold) {
  1350. return Promise.resolve();
  1351. }
  1352. const sessionDescriptionHandler = session.sessionDescriptionHandler;
  1353. if (!(sessionDescriptionHandler instanceof sip_js.Web.SessionDescriptionHandler)) {
  1354. throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");
  1355. }
  1356. const options = {
  1357. requestDelegate: {
  1358. onAccept: () => {
  1359. const managedSession = this.sessionManaged(session);
  1360. if (managedSession !== undefined) {
  1361. managedSession.held = hold;
  1362. this.enableReceiverTracks(session, !managedSession.held);
  1363. this.enableSenderTracks(session, !managedSession.held && !managedSession.muted);
  1364. if (this.delegate && this.delegate.onCallHold) {
  1365. this.delegate.onCallHold(session, managedSession.held);
  1366. }
  1367. }
  1368. },
  1369. onReject: () => {
  1370. this.logger.warn(`[${session.id}] Re-invite request was rejected`);
  1371. const managedSession = this.sessionManaged(session);
  1372. if (managedSession !== undefined) {
  1373. managedSession.held = !hold; // this was preemptively set so undo on failure
  1374. this.enableReceiverTracks(session, !managedSession.held);
  1375. this.enableSenderTracks(session, !managedSession.held && !managedSession.muted);
  1376. if (this.delegate && this.delegate.onCallHold) {
  1377. this.delegate.onCallHold(session, managedSession.held);
  1378. }
  1379. }
  1380. }
  1381. }
  1382. };
  1383. // Session properties used to pass options to the SessionDescriptionHandler:
  1384. //
  1385. // 1) Session.sessionDescriptionHandlerOptions
  1386. // hsH options for the initial INVITE transaction.
  1387. // - Used in all cases when handling the initial INVITE transaction as either UAC or UAS.
  1388. // - May be set directly at anytime.
  1389. // - May optionally be set via constructor option.
  1390. // - May optionally be set via options passed to Inviter.invite() or Invitation.accept().
  1391. //
  1392. // 2) Session.sessionDescriptionHandlerOptionsReInvite
  1393. // hsH options for re-INVITE transactions.
  1394. // - Used in all cases when handling a re-INVITE transaction as either UAC or UAS.
  1395. // - May be set directly at anytime.
  1396. // - May optionally be set via constructor option.
  1397. // - May optionally be set via options passed to Session.invite().
  1398. const sessionDescriptionHandlerOptions = session.sessionDescriptionHandlerOptionsReInvite;
  1399. sessionDescriptionHandlerOptions.hold = hold;
  1400. session.sessionDescriptionHandlerOptionsReInvite = sessionDescriptionHandlerOptions;
  1401. // Preemptively and optimistically set held state (but do not call delegate).
  1402. const managedSession = this.sessionManaged(session);
  1403. if (!managedSession) {
  1404. throw new Error('Managed session is undefiend.');
  1405. }
  1406. managedSession.held = hold;
  1407. // Send re-INVITE
  1408. return session.invite(options).then(() => {
  1409. // Preemptively enable/disable tracks
  1410. const managedSession = this.sessionManaged(session);
  1411. if (managedSession !== undefined) {
  1412. this.enableReceiverTracks(session, !managedSession.held);
  1413. this.enableSenderTracks(session, !managedSession.held && !managedSession.muted);
  1414. }
  1415. }).catch(error => {
  1416. managedSession.held = !hold; // was preemptively set so undo on failure
  1417. if (error instanceof sip_js.RequestPendingError) {
  1418. this.logger.error(`[${session.id}] A hold request is already in progress.`);
  1419. }
  1420. throw error;
  1421. });
  1422. });
  1423. }
  1424. /**
  1425. * Puts Session on mute.
  1426. * @param session - The session to mute.
  1427. * @param mute - Mute on if true, off if false.
  1428. */
  1429. setMute(session, mute) {
  1430. if (!this.sessionExists(session)) {
  1431. this.logger.warn(`[${session.id}] A session is required to enabled/disable media tracks`);
  1432. return;
  1433. }
  1434. if (session.state !== sip_js.SessionState.Established) {
  1435. this.logger.warn(`[${session.id}] An established session is required to enable/disable media tracks`);
  1436. return;
  1437. }
  1438. const managedSession = this.sessionManaged(session);
  1439. if (managedSession !== undefined) {
  1440. managedSession.muted = mute;
  1441. this.enableSenderTracks(session, !managedSession.held && !managedSession.muted);
  1442. }
  1443. }
  1444. /** Helper function to attach local media to html elements. */
  1445. setupLocalMedia(session) {
  1446. const managedSession = this.sessionManaged(session);
  1447. if (!managedSession) {
  1448. throw new Error('Managed session does not exist.');
  1449. }
  1450. // Get the local media element, if any, from the and configuraiton options
  1451. // and save the info with the managed session so we can clean it up later.
  1452. const mediaLocal = typeof this.options.media.local === 'function' ? this.options.media.local(session) : this.options.media.local;
  1453. managedSession.mediaLocal = mediaLocal;
  1454. const mediaElement = mediaLocal === null || mediaLocal === void 0 ? void 0 : mediaLocal.video;
  1455. if (mediaElement) {
  1456. const localStream = this.getLocalMediaStream(session);
  1457. if (!localStream) {
  1458. throw new Error('Local media stream undefiend.');
  1459. }
  1460. mediaElement.srcObject = localStream;
  1461. mediaElement.volume = 0;
  1462. mediaElement.play().catch(error => {
  1463. this.logger.error(`[${session.id}] Failed to play local media`);
  1464. this.logger.error(error.message);
  1465. });
  1466. }
  1467. }
  1468. /** Helper function to attach remote media to html elements. */
  1469. setupRemoteMedia(session) {
  1470. const managedSession = this.sessionManaged(session);
  1471. if (!managedSession) {
  1472. throw new Error('Managed session does not exist.');
  1473. }
  1474. // Get the remote media element, if any, from the and configuraiton options
  1475. // and save the info with the managed session so we can clean it up later.
  1476. const mediaRemote = typeof this.options.media.remote === 'function' ? this.options.media.remote(session) : this.options.media.remote;
  1477. managedSession.mediaRemote = mediaRemote;
  1478. const mediaElement = (mediaRemote === null || mediaRemote === void 0 ? void 0 : mediaRemote.video) || (mediaRemote === null || mediaRemote === void 0 ? void 0 : mediaRemote.audio);
  1479. if (mediaElement) {
  1480. const remoteStream = this.getRemoteMediaStream(session);
  1481. if (!remoteStream) {
  1482. throw new Error('Remote media stream undefiend.');
  1483. }
  1484. mediaElement.autoplay = true; // Safari hack, because you cannot call .play() from a non user action
  1485. mediaElement.srcObject = remoteStream;
  1486. mediaElement.play().catch(error => {
  1487. this.logger.error(`[${session.id}] Failed to play remote media`);
  1488. this.logger.error(error.message);
  1489. });
  1490. remoteStream.onaddtrack = () => {
  1491. this.logger.log(`Remote media onaddtrack`);
  1492. mediaElement.load(); // Safari hack, as it doesn't work otheriwse
  1493. mediaElement.play().catch(error => {
  1494. this.logger.error(`[${session.id}] Failed to play remote media`);
  1495. this.logger.error(error.message);
  1496. });
  1497. };
  1498. }
  1499. }
  1500. /**
  1501. * End a session.
  1502. * @param session - The session to terminate.
  1503. * @remarks
  1504. * Send a BYE request, CANCEL request or reject response to end the current Session.
  1505. * Resolves when the request/response is sent, otherwise rejects.
  1506. * Use `onCallHangup` delegate method to determine if and when Session is terminated.
  1507. */
  1508. terminate(session) {
  1509. return __awaiter(this, void 0, void 0, function* () {
  1510. this.logger.log(`[${session.id}] Terminating...`);
  1511. switch (session.state) {
  1512. case sip_js.SessionState.Initial:
  1513. if (session instanceof sip_js.Inviter) {
  1514. return session.cancel().then(() => {
  1515. this.logger.log(`[${session.id}] Inviter never sent INVITE (canceled)`);
  1516. });
  1517. } else if (session instanceof sip_js.Invitation) {
  1518. return session.reject().then(() => {
  1519. this.logger.log(`[${session.id}] Invitation rejected (sent 480)`);
  1520. });
  1521. } else {
  1522. throw new Error('Unknown session type.');
  1523. }
  1524. case sip_js.SessionState.Establishing:
  1525. if (session instanceof sip_js.Inviter) {
  1526. return session.cancel().then(() => {
  1527. this.logger.log(`[${session.id}] Inviter canceled (sent CANCEL)`);
  1528. });
  1529. } else if (session instanceof sip_js.Invitation) {
  1530. return session.reject().then(() => {
  1531. this.logger.log(`[${session.id}] Invitation rejected (sent 480)`);
  1532. });
  1533. } else {
  1534. throw new Error('Unknown session type.');
  1535. }
  1536. case sip_js.SessionState.Established:
  1537. return session.bye().then(() => {
  1538. this.logger.log(`[${session.id}] Session ended (sent BYE)`);
  1539. });
  1540. case sip_js.SessionState.Terminating:
  1541. break;
  1542. case sip_js.SessionState.Terminated:
  1543. break;
  1544. default:
  1545. throw new Error('Unknown state');
  1546. }
  1547. this.logger.log(`[${session.id}] Terminating in state ${session.state}, no action taken`);
  1548. return Promise.resolve();
  1549. });
  1550. }
  1551. }
  1552. /**
  1553. * A simple SIP user class.
  1554. * @remarks
  1555. * While this class is completely functional for simple use cases, it is not intended
  1556. * to provide an interface which is suitable for most (must less all) applications.
  1557. * While this class has many limitations (for example, it only handles a single concurrent session),
  1558. * it is, however, intended to serve as a simple example of using the SIP.js API.
  1559. * @public
  1560. */
  1561. class SimpleUserPlus {
  1562. /**
  1563. * Constructs a new instance of the `SimpleUser` class.
  1564. * @param server - SIP WebSocket Server URL.
  1565. * @param options - Options bucket. See {@link SimpleUserOptions} for details.
  1566. */
  1567. constructor(server, options = {}) {
  1568. /** Delegate. */
  1569. Object.defineProperty(this, "delegate", {
  1570. enumerable: true,
  1571. configurable: true,
  1572. writable: true,
  1573. value: void 0
  1574. });
  1575. Object.defineProperty(this, "logger", {
  1576. enumerable: true,
  1577. configurable: true,
  1578. writable: true,
  1579. value: void 0
  1580. });
  1581. Object.defineProperty(this, "options", {
  1582. enumerable: true,
  1583. configurable: true,
  1584. writable: true,
  1585. value: void 0
  1586. });
  1587. Object.defineProperty(this, "session", {
  1588. enumerable: true,
  1589. configurable: true,
  1590. writable: true,
  1591. value: undefined
  1592. });
  1593. Object.defineProperty(this, "sessionManager", {
  1594. enumerable: true,
  1595. configurable: true,
  1596. writable: true,
  1597. value: void 0
  1598. });
  1599. // Delegate
  1600. this.delegate = options.delegate;
  1601. // Copy options
  1602. this.options = Object.assign({}, options);
  1603. // Session manager options
  1604. const sessionManagerOptions = {
  1605. aor: this.options.aor,
  1606. delegate: {
  1607. onCallAnswered: () => {
  1608. var _a, _b;
  1609. return (_b = (_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onCallAnswered) === null || _b === void 0 ? void 0 : _b.call(_a);
  1610. },
  1611. onCallCreated: session => {
  1612. var _a, _b, _c, _d;
  1613. this.session = session;
  1614. (_b = (_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onCallBegin) === null || _b === void 0 ? void 0 : _b.call(_a, session);
  1615. (_d = (_c = this.delegate) === null || _c === void 0 ? void 0 : _c.onCallCreated) === null || _d === void 0 ? void 0 : _d.call(_c);
  1616. },
  1617. onCallReceived: session => {
  1618. var _a, _b, _c, _d;
  1619. (_b = (_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onCallReceived) === null || _b === void 0 ? void 0 : _b.call(_a);
  1620. (_d = (_c = this.delegate) === null || _c === void 0 ? void 0 : _c.onInvite) === null || _d === void 0 ? void 0 : _d.call(_c, session);
  1621. },
  1622. onCallHangup: () => {
  1623. var _a, _b;
  1624. this.session = undefined;
  1625. ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onCallHangup) && ((_b = this.delegate) === null || _b === void 0 ? void 0 : _b.onCallHangup());
  1626. },
  1627. onCallHold: (_s, held) => {
  1628. var _a, _b;
  1629. return (_b = (_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onCallHold) === null || _b === void 0 ? void 0 : _b.call(_a, held);
  1630. },
  1631. onCallDTMFReceived: (_s, tone, dur) => {
  1632. var _a, _b;
  1633. return (_b = (_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onCallDTMFReceived) === null || _b === void 0 ? void 0 : _b.call(_a, tone, dur);
  1634. },
  1635. onMessageReceived: message => {
  1636. var _a, _b;
  1637. return (_b = (_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onMessageReceived) === null || _b === void 0 ? void 0 : _b.call(_a, message.request.body);
  1638. },
  1639. onRegistered: () => {
  1640. var _a, _b;
  1641. return (_b = (_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onRegistered) === null || _b === void 0 ? void 0 : _b.call(_a);
  1642. },
  1643. onUnregistered: () => {
  1644. var _a, _b;
  1645. return (_b = (_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onUnregistered) === null || _b === void 0 ? void 0 : _b.call(_a);
  1646. },
  1647. onServerConnect: () => {
  1648. var _a, _b;
  1649. return (_b = (_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onServerConnect) === null || _b === void 0 ? void 0 : _b.call(_a);
  1650. },
  1651. onServerDisconnect: () => {
  1652. var _a, _b;
  1653. return (_b = (_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onServerDisconnect) === null || _b === void 0 ? void 0 : _b.call(_a);
  1654. },
  1655. onReconnectFailed: () => {
  1656. var _a, _b;
  1657. return (_b = (_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onReconnectFailed) === null || _b === void 0 ? void 0 : _b.call(_a);
  1658. },
  1659. onReconnectStart: () => {
  1660. var _a, _b;
  1661. return (_b = (_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onReconnectStart) === null || _b === void 0 ? void 0 : _b.call(_a);
  1662. }
  1663. },
  1664. maxSimultaneousSessions: 1,
  1665. media: this.options.media,
  1666. optionsPingInterval: this.options.optionsPingInterval,
  1667. optionsPingRequestURI: this.options.aor,
  1668. reconnectionAttempts: this.options.reconnectionAttempts,
  1669. reconnectionDelay: this.options.reconnectionDelay,
  1670. registererOptions: this.options.registererOptions,
  1671. sendDTMFUsingSessionDescriptionHandler: this.options.sendDTMFUsingSessionDescriptionHandler,
  1672. userAgentOptions: this.options.userAgentOptions
  1673. };
  1674. this.sessionManager = new SessionManagerPlus(server, sessionManagerOptions);
  1675. this.sessionManager.userAgent.stateChange.addListener(state => {
  1676. var _a, _b;
  1677. (_b = (_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onUserAgentStateChange) === null || _b === void 0 ? void 0 : _b.call(_a, state);
  1678. });
  1679. // Use the SIP.js logger
  1680. this.logger = this.sessionManager.userAgent.getLogger('sip.SimpleUser');
  1681. }
  1682. /**
  1683. * Instance identifier.
  1684. * @internal
  1685. */
  1686. get id() {
  1687. return this.options.userAgentOptions && this.options.userAgentOptions.displayName || 'Anonymous';
  1688. }
  1689. /** The local media stream. Undefined if call not answered. */
  1690. get localMediaStream() {
  1691. return this.session && this.sessionManager.getLocalMediaStream(this.session);
  1692. }
  1693. /** The remote media stream. Undefined if call not answered. */
  1694. get remoteMediaStream() {
  1695. return this.session && this.sessionManager.getRemoteMediaStream(this.session);
  1696. }
  1697. /**
  1698. * The local audio track, if available.
  1699. * @deprecated Use localMediaStream and get track from the stream.
  1700. */
  1701. get localAudioTrack() {
  1702. return this.session && this.sessionManager.getLocalAudioTrack(this.session);
  1703. }
  1704. /**
  1705. * The local video track, if available.
  1706. * @deprecated Use localMediaStream and get track from the stream.
  1707. */
  1708. get localVideoTrack() {
  1709. return this.session && this.sessionManager.getLocalVideoTrack(this.session);
  1710. }
  1711. /**
  1712. * The remote audio track, if available.
  1713. * @deprecated Use remoteMediaStream and get track from the stream.
  1714. */
  1715. get remoteAudioTrack() {
  1716. return this.session && this.sessionManager.getRemoteAudioTrack(this.session);
  1717. }
  1718. /**
  1719. * The remote video track, if available.
  1720. * @deprecated Use remoteMediaStream and get track from the stream.
  1721. */
  1722. get remoteVideoTrack() {
  1723. return this.session && this.sessionManager.getRemoteVideoTrack(this.session);
  1724. }
  1725. /**
  1726. * Connect.
  1727. * @remarks
  1728. * Start the UserAgent's WebSocket Transport.
  1729. */
  1730. connect() {
  1731. this.logger.log(`[${this.id}] Connecting UserAgent...`);
  1732. return this.sessionManager.connect();
  1733. }
  1734. /**
  1735. * Disconnect.
  1736. * @remarks
  1737. * Stop the UserAgent's WebSocket Transport.
  1738. */
  1739. disconnect() {
  1740. this.logger.log(`[${this.id}] Disconnecting UserAgent...`);
  1741. return this.sessionManager.disconnect();
  1742. }
  1743. /**
  1744. * Return true if connected.
  1745. */
  1746. isConnected() {
  1747. return this.sessionManager.isConnected();
  1748. }
  1749. /**
  1750. * Start receiving incoming calls.
  1751. * @remarks
  1752. * Send a REGISTER request for the UserAgent's AOR.
  1753. * Resolves when the REGISTER request is sent, otherwise rejects.
  1754. */
  1755. register(registererRegisterOptions) {
  1756. this.logger.log(`[${this.id}] Registering UserAgent...`);
  1757. return this.sessionManager.register(registererRegisterOptions);
  1758. }
  1759. /**
  1760. * Stop receiving incoming calls.
  1761. * @remarks
  1762. * Send an un-REGISTER request for the UserAgent's AOR.
  1763. * Resolves when the un-REGISTER request is sent, otherwise rejects.
  1764. */
  1765. unregister(registererUnregisterOptions) {
  1766. this.logger.log(`[${this.id}] Unregistering UserAgent...`);
  1767. return this.sessionManager.unregister(registererUnregisterOptions);
  1768. }
  1769. /**
  1770. * Make an outgoing call.
  1771. * @remarks
  1772. * Send an INVITE request to create a new Session.
  1773. * Resolves when the INVITE request is sent, otherwise rejects.
  1774. * Use `onCallAnswered` delegate method to determine if Session is established.
  1775. * @param destination - The target destination to call. A SIP address to send the INVITE to.
  1776. * @param inviterOptions - Optional options for Inviter constructor.
  1777. * @param inviterInviteOptions - Optional options for Inviter.invite().
  1778. */
  1779. call(destination, inviterOptions, inviterInviteOptions) {
  1780. this.logger.log(`[${this.id}] Beginning Session...`);
  1781. if (this.session) {
  1782. return Promise.reject(new Error('Session already exists.'));
  1783. }
  1784. return this.sessionManager.call(destination, inviterOptions, inviterInviteOptions).then(() => {
  1785. return;
  1786. });
  1787. }
  1788. /**
  1789. * Hangup a call.
  1790. * @remarks
  1791. * Send a BYE request, CANCEL request or reject response to end the current Session.
  1792. * Resolves when the request/response is sent, otherwise rejects.
  1793. * Use `onCallHangup` delegate method to determine if and when call is ended.
  1794. */
  1795. hangup() {
  1796. this.logger.log(`[${this.id}] Hangup...`);
  1797. if (!this.session) {
  1798. return Promise.reject(new Error('Session does not exist.'));
  1799. }
  1800. return this.sessionManager.hangup(this.session).then(() => {
  1801. this.session = undefined;
  1802. });
  1803. }
  1804. /**
  1805. * Answer an incoming call.
  1806. * @remarks
  1807. * Accept an incoming INVITE request creating a new Session.
  1808. * Resolves with the response is sent, otherwise rejects.
  1809. * Use `onCallAnswered` delegate method to determine if and when call is established.
  1810. * @param invitationAcceptOptions - Optional options for Inviter.accept().
  1811. */
  1812. answer(invitationAcceptOptions) {
  1813. this.logger.log(`[${this.id}] Accepting Invitation...`);
  1814. if (!this.session) {
  1815. return Promise.reject(new Error('Session does not exist.'));
  1816. }
  1817. return this.sessionManager.answer(this.session, invitationAcceptOptions);
  1818. }
  1819. /**
  1820. * Decline an incoming call.
  1821. * @remarks
  1822. * Reject an incoming INVITE request.
  1823. * Resolves with the response is sent, otherwise rejects.
  1824. * Use `onCallHangup` delegate method to determine if and when call is ended.
  1825. */
  1826. decline() {
  1827. this.logger.log(`[${this.id}] rejecting Invitation...`);
  1828. if (!this.session) {
  1829. return Promise.reject(new Error('Session does not exist.'));
  1830. }
  1831. return this.sessionManager.decline(this.session);
  1832. }
  1833. /**
  1834. * Hold call
  1835. * @remarks
  1836. * Send a re-INVITE with new offer indicating "hold".
  1837. * Resolves when the re-INVITE request is sent, otherwise rejects.
  1838. * Use `onCallHold` delegate method to determine if request is accepted or rejected.
  1839. * See: https://tools.ietf.org/html/rfc6337
  1840. */
  1841. hold() {
  1842. this.logger.log(`[${this.id}] holding session...`);
  1843. if (!this.session) {
  1844. return Promise.reject(new Error('Session does not exist.'));
  1845. }
  1846. return this.sessionManager.hold(this.session);
  1847. }
  1848. /**
  1849. * Unhold call.
  1850. * @remarks
  1851. * Send a re-INVITE with new offer indicating "unhold".
  1852. * Resolves when the re-INVITE request is sent, otherwise rejects.
  1853. * Use `onCallHold` delegate method to determine if request is accepted or rejected.
  1854. * See: https://tools.ietf.org/html/rfc6337
  1855. */
  1856. unhold() {
  1857. this.logger.log(`[${this.id}] unholding session...`);
  1858. if (!this.session) {
  1859. return Promise.reject(new Error('Session does not exist.'));
  1860. }
  1861. return this.sessionManager.unhold(this.session);
  1862. }
  1863. /**
  1864. * Hold state.
  1865. * @remarks
  1866. * True if session is on hold.
  1867. */
  1868. isHeld() {
  1869. return this.session ? this.sessionManager.isHeld(this.session) : false;
  1870. }
  1871. /**
  1872. * Mute call.
  1873. * @remarks
  1874. * Disable sender's media tracks.
  1875. */
  1876. mute() {
  1877. this.logger.log(`[${this.id}] disabling media tracks...`);
  1878. return this.session && this.sessionManager.mute(this.session);
  1879. }
  1880. /**
  1881. * Unmute call.
  1882. * @remarks
  1883. * Enable sender's media tracks.
  1884. */
  1885. unmute() {
  1886. this.logger.log(`[${this.id}] enabling media tracks...`);
  1887. return this.session && this.sessionManager.unmute(this.session);
  1888. }
  1889. /**
  1890. * Mute state.
  1891. * @remarks
  1892. * True if sender's media track is disabled.
  1893. */
  1894. isMuted() {
  1895. return this.session ? this.sessionManager.isMuted(this.session) : false;
  1896. }
  1897. /**
  1898. * Send DTMF.
  1899. * @remarks
  1900. * Send an INFO request with content type application/dtmf-relay.
  1901. * @param tone - Tone to send.
  1902. */
  1903. sendDTMF(tone) {
  1904. this.logger.log(`[${this.id}] sending DTMF...`);
  1905. if (!this.session) {
  1906. return Promise.reject(new Error('Session does not exist.'));
  1907. }
  1908. return this.sessionManager.sendDTMF(this.session, tone);
  1909. }
  1910. /**
  1911. * Send a message.
  1912. * @remarks
  1913. * Send a MESSAGE request.
  1914. * @param destination - The target destination for the message. A SIP address to send the MESSAGE to.
  1915. */
  1916. message(destination, message) {
  1917. this.logger.log(`[${this.id}] sending message...`);
  1918. return this.sessionManager.message(destination, message);
  1919. }
  1920. }
  1921. let has = Object.prototype.hasOwnProperty,
  1922. prefix = '~';
  1923. /**
  1924. * Constructor to create a storage for our `EE` objects.
  1925. * An `Events` instance is a plain object whose properties are event names.
  1926. *
  1927. * @constructor
  1928. * @private
  1929. */
  1930. // eslint-disable-next-line @typescript-eslint/no-empty-function
  1931. function Events() {}
  1932. //
  1933. // We try to not inherit from `Object.prototype`. In some engines creating an
  1934. // instance in this way is faster than calling `Object.create(null)` directly.
  1935. // If `Object.create(null)` is not supported we prefix the event names with a
  1936. // character to make sure that the built-in object properties are not
  1937. // overridden or used as an attack vector.
  1938. //
  1939. if (Object.create) {
  1940. Events.prototype = Object.create(null);
  1941. //
  1942. // This hack is needed because the `__proto__` property is still inherited in
  1943. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  1944. //
  1945. // eslint-disable-next-line no-const-assign
  1946. if (!new Events().__proto__) prefix = false;
  1947. }
  1948. /**
  1949. * Representation of a single event listener.
  1950. *
  1951. * @param {Function} fn The listener function.
  1952. * @param {*} context The context to invoke the listener with.
  1953. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  1954. * @constructor
  1955. * @private
  1956. */
  1957. function EE(fn, context, once) {
  1958. this.fn = fn;
  1959. this.context = context;
  1960. this.once = once || false;
  1961. }
  1962. /**
  1963. * Add a listener for a given event.
  1964. *
  1965. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  1966. * @param {(String|Symbol)} event The event name.
  1967. * @param {Function} fn The listener function.
  1968. * @param {*} context The context to invoke the listener with.
  1969. * @param {Boolean} once Specify if the listener is a one-time listener.
  1970. * @returns {EventEmitter}
  1971. * @private
  1972. */
  1973. function addListener(emitter, event, fn, context, once) {
  1974. if (typeof fn !== 'function') {
  1975. throw new TypeError('The listener must be a function');
  1976. }
  1977. const listener = new EE(fn, context || emitter, once),
  1978. evt = prefix ? prefix + event : event;
  1979. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);else emitter._events[evt] = [emitter._events[evt], listener];
  1980. return emitter;
  1981. }
  1982. /**
  1983. * Clear event by name.
  1984. *
  1985. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  1986. * @param {(String|Symbol)} evt The Event name.
  1987. * @private
  1988. */
  1989. function clearEvent(emitter, evt) {
  1990. if (--emitter._eventsCount === 0) emitter._events = new Events();else delete emitter._events[evt];
  1991. }
  1992. /**
  1993. * Minimal `EventEmitter` interface that is molded against the Node.js
  1994. * `EventEmitter` interface.
  1995. *
  1996. * @constructor
  1997. * @public
  1998. */
  1999. function EventEmitter() {
  2000. this._events = new Events();
  2001. this._eventsCount = 0;
  2002. }
  2003. /**
  2004. * Return an array listing the events for which the emitter has registered
  2005. * listeners.
  2006. *
  2007. * @returns {Array}
  2008. * @public
  2009. */
  2010. EventEmitter.prototype.eventNames = function eventNames() {
  2011. let names = [],
  2012. events,
  2013. name;
  2014. if (this._eventsCount === 0) return names;
  2015. for (name in events = this._events) {
  2016. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  2017. }
  2018. if (Object.getOwnPropertySymbols) {
  2019. return names.concat(Object.getOwnPropertySymbols(events));
  2020. }
  2021. return names;
  2022. };
  2023. /**
  2024. * Return the listeners registered for a given event.
  2025. *
  2026. * @param {(String|Symbol)} event The event name.
  2027. * @returns {Array} The registered listeners.
  2028. * @public
  2029. */
  2030. EventEmitter.prototype.listeners = function listeners(event) {
  2031. const evt = prefix ? prefix + event : event,
  2032. handlers = this._events[evt];
  2033. if (!handlers) return [];
  2034. if (handlers.fn) return [handlers.fn];
  2035. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  2036. ee[i] = handlers[i].fn;
  2037. }
  2038. return ee;
  2039. };
  2040. /**
  2041. * Return the number of listeners listening to a given event.
  2042. *
  2043. * @param {(String|Symbol)} event The event name.
  2044. * @returns {Number} The number of listeners.
  2045. * @public
  2046. */
  2047. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  2048. const evt = prefix ? prefix + event : event,
  2049. listeners = this._events[evt];
  2050. if (!listeners) return 0;
  2051. if (listeners.fn) return 1;
  2052. return listeners.length;
  2053. };
  2054. /**
  2055. * Calls each of the listeners registered for a given event.
  2056. *
  2057. * @param {(String|Symbol)} event The event name.
  2058. * @returns {Boolean} `true` if the event had listeners, else `false`.
  2059. * @public
  2060. */
  2061. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  2062. const evt = prefix ? prefix + event : event;
  2063. if (!this._events[evt]) return false;
  2064. let listeners = this._events[evt],
  2065. len = arguments.length,
  2066. args,
  2067. i;
  2068. if (listeners.fn) {
  2069. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  2070. switch (len) {
  2071. case 1:
  2072. return listeners.fn.call(listeners.context), true;
  2073. case 2:
  2074. return listeners.fn.call(listeners.context, a1), true;
  2075. case 3:
  2076. return listeners.fn.call(listeners.context, a1, a2), true;
  2077. case 4:
  2078. return listeners.fn.call(listeners.context, a1, a2, a3), true;
  2079. case 5:
  2080. return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  2081. case 6:
  2082. return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  2083. }
  2084. for (i = 1, args = new Array(len - 1); i < len; i++) {
  2085. args[i - 1] = arguments[i];
  2086. }
  2087. listeners.fn.apply(listeners.context, args);
  2088. } else {
  2089. let length = listeners.length,
  2090. j;
  2091. for (i = 0; i < length; i++) {
  2092. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  2093. switch (len) {
  2094. case 1:
  2095. listeners[i].fn.call(listeners[i].context);
  2096. break;
  2097. case 2:
  2098. listeners[i].fn.call(listeners[i].context, a1);
  2099. break;
  2100. case 3:
  2101. listeners[i].fn.call(listeners[i].context, a1, a2);
  2102. break;
  2103. case 4:
  2104. listeners[i].fn.call(listeners[i].context, a1, a2, a3);
  2105. break;
  2106. default:
  2107. if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) {
  2108. args[j - 1] = arguments[j];
  2109. }
  2110. listeners[i].fn.apply(listeners[i].context, args);
  2111. }
  2112. }
  2113. }
  2114. return true;
  2115. };
  2116. /**
  2117. * Add a listener for a given event.
  2118. *
  2119. * @param {(String|Symbol)} event The event name.
  2120. * @param {Function} fn The listener function.
  2121. * @param {*} [context=this] The context to invoke the listener with.
  2122. * @returns {EventEmitter} `this`.
  2123. * @public
  2124. */
  2125. EventEmitter.prototype.on = function on(event, fn, context) {
  2126. return addListener(this, event, fn, context, false);
  2127. };
  2128. /**
  2129. * Add a one-time listener for a given event.
  2130. *
  2131. * @param {(String|Symbol)} event The event name.
  2132. * @param {Function} fn The listener function.
  2133. * @param {*} [context=this] The context to invoke the listener with.
  2134. * @returns {EventEmitter} `this`.
  2135. * @public
  2136. */
  2137. EventEmitter.prototype.once = function once(event, fn, context) {
  2138. return addListener(this, event, fn, context, true);
  2139. };
  2140. /**
  2141. * Remove the listeners of a given event.
  2142. *
  2143. * @param {(String|Symbol)} event The event name.
  2144. * @param {Function} fn Only remove the listeners that match this function.
  2145. * @param {*} context Only remove the listeners that have this context.
  2146. * @param {Boolean} once Only remove one-time listeners.
  2147. * @returns {EventEmitter} `this`.
  2148. * @public
  2149. */
  2150. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  2151. const evt = prefix ? prefix + event : event;
  2152. if (!this._events[evt]) return this;
  2153. if (!fn) {
  2154. clearEvent(this, evt);
  2155. return this;
  2156. }
  2157. const listeners = this._events[evt];
  2158. if (listeners.fn) {
  2159. if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
  2160. clearEvent(this, evt);
  2161. }
  2162. } else {
  2163. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  2164. if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
  2165. events.push(listeners[i]);
  2166. }
  2167. }
  2168. //
  2169. // Reset the array, or remove it completely if we have no more listeners.
  2170. //
  2171. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;else clearEvent(this, evt);
  2172. }
  2173. return this;
  2174. };
  2175. /**
  2176. * Remove all listeners, or those of the specified event.
  2177. *
  2178. * @param {(String|Symbol)} [event] The event name.
  2179. * @returns {EventEmitter} `this`.
  2180. * @public
  2181. */
  2182. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  2183. let evt;
  2184. if (event) {
  2185. evt = prefix ? prefix + event : event;
  2186. if (this._events[evt]) clearEvent(this, evt);
  2187. } else {
  2188. this._events = new Events();
  2189. this._eventsCount = 0;
  2190. }
  2191. return this;
  2192. };
  2193. //
  2194. // Alias methods names because people roll like that.
  2195. //
  2196. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  2197. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  2198. //
  2199. // Expose the prefix.
  2200. //
  2201. EventEmitter.prefixed = prefix;
  2202. //
  2203. // Allow `EventEmitter` to be imported as module namespace.
  2204. //
  2205. EventEmitter.EventEmitter = EventEmitter;
  2206. //
  2207. // Expose the module.
  2208. //
  2209. if ('undefined' !== typeof module) {
  2210. module.exports = EventEmitter;
  2211. }
  2212. /** 将小驼峰式字符串转换为小写下划线格式
  2213. * @param {string}
  2214. * @returns {string}
  2215. */
  2216. function upperCamelToLowerSnake(s) {
  2217. s = s.replace(/\s/g, '');
  2218. s = s.replace(/([A-Z])/g, '_$1');
  2219. s = s.toLowerCase();
  2220. s = s.replace(/^_/, '');
  2221. s = s.replace(/_$/, '');
  2222. return s;
  2223. }
  2224. /**
  2225. * 获取时间戳字符串
  2226. * @returns {string} 年-月-日 时:分:秒.毫秒
  2227. */
  2228. const getDateTime = () => {
  2229. const timestamp = Date.now();
  2230. const date = new Date(timestamp);
  2231. const year = date.getFullYear();
  2232. const month = String(date.getMonth() + 1).padStart(2, '0');
  2233. const day = String(date.getDate()).padStart(2, '0');
  2234. const hours = String(date.getHours()).padStart(2, '0');
  2235. const minutes = String(date.getMinutes()).padStart(2, '0');
  2236. const seconds = String(date.getSeconds()).padStart(2, '0');
  2237. const milliseconds = String(date.getMilliseconds()).padStart(3, '0');
  2238. const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
  2239. return formattedDateTime;
  2240. };
  2241. /** @enum LoggerLevels 日志输出等级 */
  2242. exports.LoggerLevels = void 0;
  2243. (function (LoggerLevels) {
  2244. LoggerLevels[LoggerLevels["error"] = 0] = "error";
  2245. LoggerLevels[LoggerLevels["warn"] = 1] = "warn";
  2246. LoggerLevels[LoggerLevels["log"] = 2] = "log";
  2247. LoggerLevels[LoggerLevels["debug"] = 3] = "debug";
  2248. })(exports.LoggerLevels || (exports.LoggerLevels = {}));
  2249. /** @class Logger 通用的日志模块 */
  2250. class Logger {
  2251. constructor(level, category, label) {
  2252. Object.defineProperty(this, "_level", {
  2253. enumerable: true,
  2254. configurable: true,
  2255. writable: true,
  2256. value: void 0
  2257. });
  2258. Object.defineProperty(this, "category", {
  2259. enumerable: true,
  2260. configurable: true,
  2261. writable: true,
  2262. value: void 0
  2263. });
  2264. Object.defineProperty(this, "label", {
  2265. enumerable: true,
  2266. configurable: true,
  2267. writable: true,
  2268. value: void 0
  2269. });
  2270. this._level = level;
  2271. this.category = category;
  2272. this.label = label;
  2273. }
  2274. error(content) {
  2275. this.genericLog(exports.LoggerLevels.error, content);
  2276. }
  2277. warn(content) {
  2278. this.genericLog(exports.LoggerLevels.warn, content);
  2279. }
  2280. log(content) {
  2281. this.genericLog(exports.LoggerLevels.log, content);
  2282. }
  2283. debug(content) {
  2284. this.genericLog(exports.LoggerLevels.debug, content);
  2285. }
  2286. genericLog(levelToLog, content) {
  2287. if (this._level >= levelToLog) {
  2288. this.print(levelToLog, this.category, this.label, content);
  2289. }
  2290. }
  2291. print(levelToLog, category, label, content) {
  2292. if (typeof content === 'string') {
  2293. const prefix = [getDateTime()];
  2294. if (label) {
  2295. prefix.push(label);
  2296. }
  2297. content = prefix.concat(content).join(' | ');
  2298. }
  2299. switch (levelToLog) {
  2300. case exports.LoggerLevels.error:
  2301. console.error(`%c${category}`, 'color: blue;', content);
  2302. break;
  2303. case exports.LoggerLevels.warn:
  2304. console.warn(`%c${category}`, 'color: blue;', content);
  2305. break;
  2306. case exports.LoggerLevels.log:
  2307. console.log(`%c${category}`, 'color: blue;', content);
  2308. break;
  2309. case exports.LoggerLevels.debug:
  2310. console.debug(`%c${category}`, 'color: blue;', content);
  2311. break;
  2312. }
  2313. }
  2314. get level() {
  2315. return this._level;
  2316. }
  2317. set level(newLevel) {
  2318. if (newLevel >= 0 && newLevel <= 3) {
  2319. this._level = newLevel;
  2320. } else if (newLevel > 3) {
  2321. this._level = 3;
  2322. // eslint-disable-next-line no-prototype-builtins
  2323. } else if (exports.LoggerLevels.hasOwnProperty(newLevel)) {
  2324. this._level = newLevel;
  2325. } else {
  2326. this.error("invalid 'level' parameter value: " + JSON.stringify(newLevel));
  2327. }
  2328. }
  2329. }
  2330. /**
  2331. * @enum {string} CTI 初始化场景
  2332. * Manual: 手动外呼
  2333. * Robot: 机器人外呼
  2334. * Monitor: 监听
  2335. * Predictive: 预测式外呼
  2336. */
  2337. exports.Scene = void 0;
  2338. (function (Scene) {
  2339. Scene["Manual"] = "manual";
  2340. Scene["Robot"] = "robot";
  2341. Scene["Monitor"] = "monitor";
  2342. Scene["Predictive"] = "predictive";
  2343. Scene["Wechat"] = "wechat";
  2344. })(exports.Scene || (exports.Scene = {}));
  2345. /**
  2346. * @enum {string} CTI 监听场景
  2347. * All: 不区分场景
  2348. * Manual: 手动外呼
  2349. * Robot: 机器人外呼
  2350. * Predictive: 预测式外呼
  2351. */
  2352. exports.MonitorScene = void 0;
  2353. (function (MonitorScene) {
  2354. MonitorScene["All"] = "all";
  2355. MonitorScene["Manual"] = "manual";
  2356. MonitorScene["Robot"] = "robot";
  2357. MonitorScene["Predictive"] = "predictive";
  2358. })(exports.MonitorScene || (exports.MonitorScene = {}));
  2359. /**
  2360. * @interface {} 初始化 SD_CTI 需要的参数
  2361. * loggerLevel: 日志等级
  2362. * password: 临时的鉴权字符串,由业务方写死传进来
  2363. * scene: CTI 初始化场景
  2364. * monitorScene: 监听场景
  2365. * env: 环境变量
  2366. */
  2367. /**
  2368. * @enum {string} Socket 状态
  2369. * Initial: 初始状态
  2370. * Connecting: Socket 开始建立连接
  2371. * Connected: Socket 建立连接成功
  2372. * Ready: 向 IM 发送第一个上行 login 消息收到成功回调
  2373. * Terminated: Socket 连接断开、各种 Socket 错误流转到本状态
  2374. */
  2375. exports.SocketStatus = void 0;
  2376. (function (SocketStatus) {
  2377. SocketStatus["Initial"] = "Initial";
  2378. SocketStatus["Connecting"] = "Connecting";
  2379. SocketStatus["Connected"] = "Connected";
  2380. SocketStatus["Ready"] = "Ready";
  2381. SocketStatus["ReTry"] = "ReTry";
  2382. SocketStatus["Terminated"] = "Terminated";
  2383. })(exports.SocketStatus || (exports.SocketStatus = {}));
  2384. /**
  2385. * @enum {string} SIP 状态
  2386. * Initial: 初始状态
  2387. * Started: SIP 的 User Agent 创建成功
  2388. * Connecting: SIP 底层 Socket 传输 TransportState.Connecting
  2389. * Connected: SIP 底层 Socket 传输 TransportState.Connected
  2390. * Ready: SIP Registerer 监听注册状态 RegistererState.Registered
  2391. * Terminated: SIP Socket 断开、注册失败等各种错误、主动断开连接流转到本状态
  2392. */
  2393. exports.SIPStatus = void 0;
  2394. (function (SIPStatus) {
  2395. SIPStatus["Initial"] = "Initial";
  2396. SIPStatus["Started"] = "Started";
  2397. SIPStatus["Connecting"] = "Connecting";
  2398. SIPStatus["Connected"] = "Connected";
  2399. SIPStatus["Ready"] = "Ready";
  2400. SIPStatus["ReTry"] = "ReTry";
  2401. SIPStatus["Terminated"] = "Terminated";
  2402. })(exports.SIPStatus || (exports.SIPStatus = {}));
  2403. /**
  2404. * @enum {string} CTI 状态
  2405. * Initial: 初始状态
  2406. * Ready: SocketStatus Ready && SIPStatus Ready
  2407. * Terminated: SocketStatus Terminated || SIPStatus Terminated || 正常调用 unInit 方法卸载
  2408. */
  2409. exports.CTIStatus = void 0;
  2410. (function (CTIStatus) {
  2411. CTIStatus["Initial"] = "Initial";
  2412. CTIStatus["Ready"] = "Ready";
  2413. CTIStatus["ReTry"] = "ReTry";
  2414. CTIStatus["Terminated"] = "Terminated";
  2415. })(exports.CTIStatus || (exports.CTIStatus = {}));
  2416. /**
  2417. * @enum {string} 通话状态
  2418. * 为了防止人工外呼方法被二次调用引发预期以外的问题,增加此状态的流转
  2419. * Started: 外呼已开始,此状态下不允许再次发起外呼
  2420. * Stopped: 外呼已结束,此状态下可以再次发起外呼
  2421. */
  2422. exports.CallStatus = void 0;
  2423. (function (CallStatus) {
  2424. CallStatus["Started"] = "Started";
  2425. CallStatus["Stopped"] = "Stopped";
  2426. })(exports.CallStatus || (exports.CallStatus = {}));
  2427. /**
  2428. * @enum {string} Session 状态
  2429. * CTI 目前只有 Invitation(接受会话)的场景,Inviter (主动发起会话)暂时没有
  2430. */
  2431. exports.SessionStatus = void 0;
  2432. (function (SessionStatus) {
  2433. /**
  2434. * If `Inviter`, INVITE not sent yet.
  2435. * If `Invitation`, SDK 收到 INVITE 通话请求,但尚未处理.
  2436. */
  2437. SessionStatus["Initial"] = "Initial";
  2438. /**
  2439. * If `Inviter`, sent INVITE and waiting for a final response.
  2440. * If `Invitation`, received INVITE and attempting to send 200 final response (but has not sent it yet).
  2441. */
  2442. SessionStatus["Establishing"] = "Establishing";
  2443. /**
  2444. * If `Inviter`, sent INVITE and received 200 final response and sent ACK.
  2445. * If `Invitation`, SDK 完成接受 INVITE 并发送 200 OK 确认接起,同时接通本地语音流.
  2446. */
  2447. SessionStatus["Established"] = "Established";
  2448. /**
  2449. * If `Inviter`, sent INVITE, sent CANCEL and now waiting for 487 final response to ACK (or 200 to ACK & BYE).
  2450. * If `Invitation`, received INVITE, sent 200 final response and now waiting on ACK and upon receipt will attempt BYE
  2451. * (as the protocol specification requires, before sending a BYE we must receive the ACK - so we are waiting).
  2452. */
  2453. SessionStatus["Terminating"] = "Terminating";
  2454. /**
  2455. * If `Inviter`, sent INVITE and received non-200 final response (or sent/received BYE after receiving 200).
  2456. * If `Invitation`, SDK 收到 BYE 信令,发送 200 OK 挂断确认,会话结束.
  2457. */
  2458. SessionStatus["Terminated"] = "Terminated";
  2459. })(exports.SessionStatus || (exports.SessionStatus = {}));
  2460. /**
  2461. * @enum {string} CTI 所有错误的分类
  2462. * SdkTerminated: SDK 不可用错误,需要重新初始化
  2463. * SdkError: SDK 状态可用,其他普通错误
  2464. * ServerTerminated: 服务端不可用错误,需要重新初始化,透传服务端 code,msg
  2465. * ServerError: 服务端可用,普通错误,透传服务端 code,msg
  2466. */
  2467. exports.CTIErrorType = void 0;
  2468. (function (CTIErrorType) {
  2469. CTIErrorType["SdkTerminated"] = "SdkTerminated";
  2470. CTIErrorType["SdkError"] = "SdkError";
  2471. CTIErrorType["ServerTerminated"] = "ServerTerminated";
  2472. CTIErrorType["ServerError"] = "ServerError";
  2473. })(exports.CTIErrorType || (exports.CTIErrorType = {}));
  2474. /**
  2475. * @enum {string} SdkTerminated 类型错误的 code 枚举
  2476. * CTITerminated: SDK 状态不可用,CTIStatus 的状态为 Terminated
  2477. * GetUserMedia: 获取坐席媒体权限失败
  2478. * GetInitConfig: 调接口获取 CTI 初始化配置失败
  2479. * SocketOnError: 监听 socket.io 的 error 事件
  2480. * SocketOnConnectError: 监听 socket.io 的 connect_error 事件
  2481. * SocketOnDisconnect: 监听 socket.io 的 disconnect 事件
  2482. * SocketRepeatLogin: 多页面重复登录,IM 互踢事件
  2483. * SIPInitUserAgent: SIP UserAgent 初始化时启动失败
  2484. * SIPInitRegister: SIP Register 初始化时注册失败
  2485. * SIPUserAgentStateStopped: 监听 SIP UserAgent stateChange 事件状态变更为 Stopped
  2486. * SIPTransportStateDisconnected: 监听 SIP Transport StateChange 事件状态变更为 Disconnect
  2487. * SIPRegistererStateTerminated: 监听 SIP Registerer StateChange 事件状态变更为 Terminated
  2488. * SIPOnDisconnect: 监听 SIP OnDisconnect 事件收到异常退出 error
  2489. * SIPInitTransport: SIP Transport 初始化时连接失败
  2490. * SipHeartBeatErr: SIP发送心跳OPTIONS事件时收到异常结果
  2491. * SIPUnRegistered: 注册SIP时失败
  2492. * SocketOnReconnectFailed: Socket重连超过阈值且依然重连失败
  2493. */
  2494. exports.HskTerminatedCode = void 0;
  2495. (function (HskTerminatedCode) {
  2496. HskTerminatedCode["CTITerminated"] = "100001";
  2497. HskTerminatedCode["GetUserMedia"] = "100002";
  2498. HskTerminatedCode["GetInitConfig"] = "100003";
  2499. HskTerminatedCode["SocketOnError"] = "110001";
  2500. HskTerminatedCode["SocketOnConnectError"] = "110002";
  2501. HskTerminatedCode["SocketOnDisconnect"] = "110003";
  2502. HskTerminatedCode["SocketRepeatLogin"] = "110004";
  2503. HskTerminatedCode["SocketOnReconnectFailed"] = "110007";
  2504. HskTerminatedCode["SIPInitUserAgent"] = "120001";
  2505. HskTerminatedCode["SIPInitRegister"] = "120002";
  2506. HskTerminatedCode["SIPUserAgentStateStopped"] = "120003";
  2507. HskTerminatedCode["SIPTransportStateDisconnected"] = "120004";
  2508. HskTerminatedCode["SIPRegistererStateTerminated"] = "120005";
  2509. HskTerminatedCode["SIPOnDisconnect"] = "120006";
  2510. HskTerminatedCode["SIPInitTransport"] = "120007";
  2511. HskTerminatedCode["SipHeartBeatErr"] = "120008";
  2512. HskTerminatedCode["SIPUnRegistered"] = "120009";
  2513. })(exports.HskTerminatedCode || (exports.HskTerminatedCode = {}));
  2514. /**
  2515. * @enum {string} SdkError 类型错误的 code 枚举
  2516. * Answer: SIP accept 接起失败
  2517. * Bye: SIP bye 挂断失败
  2518. * InvitationCancel: SIP Invitation 会话请求被取消
  2519. * AssignStream: 播放语音流失败
  2520. * FetchError: 修饰器handleApiRes当进入到catch时上报此code
  2521. */
  2522. exports.SdkErrorCode = void 0;
  2523. (function (SdkErrorCode) {
  2524. SdkErrorCode["Answer"] = "200001";
  2525. SdkErrorCode["Bye"] = "200002";
  2526. SdkErrorCode["InvitationCancel"] = "200003";
  2527. SdkErrorCode["AssignStream"] = "200004";
  2528. SdkErrorCode["FetchError"] = "200005";
  2529. })(exports.SdkErrorCode || (exports.SdkErrorCode = {}));
  2530. /**
  2531. * @enum {string} CTI 事件推送
  2532. * OnCtiError: CTI 错误事件,含前后端所有错误,SDK 推送
  2533. * OnSessionStatusChange: 坐席侧 SIP 会话状态变更事件,SDK 推送
  2534. * OnInitalSuccess: CTI 初始化成功事件,SDK 推送
  2535. * OnAgentWorkReport: 坐席&用户状态变更事件,Server 推送
  2536. * OnRingStart: 手动外呼用户未接听时,开始播放回铃音,Server 推送
  2537. * OnRingEnd: 手动外呼用户未接听时,播放回铃音结束,Server 推送
  2538. * OnAgentReport: 坐席状态变更事件,Server 推送
  2539. * OnCallReportInfo: 通话时长及通话次数等信息,Server 推送
  2540. * OnDetectedTone: 服务端收到音频信号后推送
  2541. */
  2542. exports.CTIEvent = void 0;
  2543. (function (CTIEvent) {
  2544. CTIEvent["OnCtiError"] = "OnCtiError";
  2545. CTIEvent["OnSessionStatusChange"] = "OnSessionStatusChange";
  2546. CTIEvent["OnInitalSuccess"] = "OnInitalSuccess";
  2547. CTIEvent["OnAgentWorkReport"] = "OnAgentWorkReport";
  2548. CTIEvent["OnRingStart"] = "OnRingStart";
  2549. CTIEvent["OnRingEnd"] = "OnRingEnd";
  2550. CTIEvent["OnDetectedTone"] = "OnDetectedTone";
  2551. CTIEvent["OnAgentReport"] = "OnAgentReport";
  2552. CTIEvent["OnCallReportInfo"] = "OnCallReportInfo";
  2553. // TODO: 后 7 个事件服务端未来不再推送时删掉
  2554. CTIEvent["OnCallRing"] = "OnCallRing";
  2555. CTIEvent["OnCallEnd"] = "OnCallEnd";
  2556. CTIEvent["OnCallAnswer"] = "OnCallAnswer";
  2557. CTIEvent["OnAgentGroupQuery"] = "OnAgentGroupQuery";
  2558. CTIEvent["OnMethodResponseEvent"] = "OnMethodResponseEvent";
  2559. CTIEvent["OnEventPrompt"] = "OnEventPrompt";
  2560. CTIEvent["OnPrompt"] = "OnPrompt";
  2561. })(exports.CTIEvent || (exports.CTIEvent = {}));
  2562. var BaseOption;
  2563. (function (BaseOption) {
  2564. BaseOption["TrackParams"] = "trackParams";
  2565. BaseOption["ENV"] = "env";
  2566. BaseOption["LoggerLevel"] = "loggerLevel";
  2567. })(BaseOption || (BaseOption = {}));
  2568. const items = [[BaseOption.TrackParams, {}], [BaseOption.ENV, 'test'], [BaseOption.LoggerLevel, exports.LoggerLevels.debug]];
  2569. const baseOption = new Map();
  2570. const resetBaseOption = () => {
  2571. items.forEach((i, v) => baseOption.set(i, v));
  2572. };
  2573. resetBaseOption();
  2574. const setBaseOption = (key, value, isInit = false) => {
  2575. if (!isInit && typeof value === 'object') {
  2576. baseOption.set(key, Object.assign(Object.assign({}, baseOption.get(key)), value));
  2577. } else {
  2578. baseOption.set(key, value);
  2579. }
  2580. };
  2581. const getBaseOption = key => {
  2582. return baseOption.get(key);
  2583. };
  2584. const generateUUID = () => {
  2585. return 'xxxxxxxxxxxx4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  2586. const r = Math.random() * 16 | 0;
  2587. const v = c === 'x' ? r : r & 0x3 | 0x8;
  2588. return v.toString(16);
  2589. }).replace(/-/g, '');
  2590. };
  2591. const getClientId = () => {
  2592. if (!window.HS_CTI_CLIENT_ID) {
  2593. window.HS_CTI_CLIENT_ID = generateUUID();
  2594. }
  2595. return window.HS_CTI_CLIENT_ID;
  2596. };
  2597. /**
  2598. * @enum {string} 本地提示音枚举
  2599. * RingAudio: 来电振铃提示音
  2600. * WaitAudio: 主动外呼等待音
  2601. * ByeAudio: 挂断提示音
  2602. */
  2603. var AudioName;
  2604. (function (AudioName) {
  2605. AudioName["RingAudio"] = "_ringAudio";
  2606. AudioName["WaitAudio"] = "_waitAudio";
  2607. AudioName["ByeAudio"] = "_byeAudio";
  2608. })(AudioName || (AudioName = {}));
  2609. /**
  2610. * @enum {string} 埋点上报的分类
  2611. * FeSocket: Socket 类暴露的事件
  2612. * FeSIP: SIP 相关事件
  2613. * FeMethod: 业务调用 SDK 暴露的方法
  2614. * FeAPI: SDK 调用后端的接口返回值
  2615. * FeAPIError: SDK 调用后端的接口错误返回值
  2616. * FeIMDown: 后端通过 IM 返回的常规事件
  2617. * FeIMCmd: IM 返回的断开指令
  2618. * FeMedia: SDK 媒体事件
  2619. * FeStatu: SDK 是否状态流转事件
  2620. * FeEmit: SDK 抛出的事件
  2621. */
  2622. var TrackSource;
  2623. (function (TrackSource) {
  2624. TrackSource["FeSocket"] = "fe-socket";
  2625. TrackSource["FeSIP"] = "fe-sip";
  2626. TrackSource["FeMethod"] = "fe-method";
  2627. TrackSource["FeAPI"] = "fe-api";
  2628. TrackSource["FeAPIError"] = "fe-api-error";
  2629. TrackSource["FeIMDown"] = "fe-im-down";
  2630. TrackSource["FeIMCmd"] = "fe-im-cmd";
  2631. TrackSource["FeMedia"] = "fe-media";
  2632. TrackSource["FeStatus"] = "fe-status";
  2633. TrackSource["FeEmit"] = "fe-emit";
  2634. })(TrackSource || (TrackSource = {}));
  2635. var SocketEvent;
  2636. (function (SocketEvent) {
  2637. SocketEvent["SetSocketStatus"] = "SetSocketStatus";
  2638. SocketEvent["SocketDownEvent"] = "SocketDownEvent";
  2639. })(SocketEvent || (SocketEvent = {}));
  2640. var ExceptMessage;
  2641. (function (ExceptMessage) {
  2642. ExceptMessage["CommonNetworkErrorMsg"] = "\u5BF9\u4E0D\u8D77\uFF0C\u7F51\u7EDC\u72B6\u51B5\u6682\u65F6\u4E0D\u4F73\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\u3002";
  2643. ExceptMessage["CustomNetworkErrorMsg"] = "\u5BF9\u4E0D\u8D77\uFF0C\u8FDE\u63A5\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\u3002\u5982\u679C\u95EE\u9898\u6301\u7EED\u51FA\u73B0\uFF0C\u8BF7\u8054\u7CFB\u6211\u4EEC\u7684\u6280\u672F\u4EBA\u5458\u3002\u611F\u8C22\u60A8\u7684\u7406\u89E3\u548C\u652F\u6301\u3002";
  2644. ExceptMessage["ManualCallAnswerErrorMsg"] = "\u5F53\u524D\u7535\u8BDD\u672A\u63A5\u901A\uFF0C\u901A\u8BDD\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u91CD\u8BD5\u3002";
  2645. ExceptMessage["RobotOrWeChatAnswerErrorMsg"] = "\u5BF9\u4E0D\u8D77\uFF0C\u7531\u4E8E\u7528\u6237\u6302\u673A\u7B49\u539F\u56E0\uFF0C\u5F53\u524D\u7535\u8BDD\u672A\u63A5\u901A\uFF0C\u8BF7\u7B49\u5F85\u4E0B\u4E00\u901A\u7535\u8BDD\u3002";
  2646. ExceptMessage["SipByeErrorMsg"] = "\u8BF7\u7A0D\u7B49\uFF0C\u6B63\u5728\u6302\u65AD\u3002";
  2647. ExceptMessage["CTIRepeatLoginMsg"] = "\u5F53\u524D\u5750\u5E2D\u5DF2\u88AB\u5176\u4ED6\u7EC8\u7AEF\u66FF\u4EE3\u3002";
  2648. })(ExceptMessage || (ExceptMessage = {}));
  2649. const methodExceptMsgMap = {
  2650. checkIn: ExceptMessage.CommonNetworkErrorMsg,
  2651. checkOut: ExceptMessage.CommonNetworkErrorMsg,
  2652. setIdle: ExceptMessage.CustomNetworkErrorMsg,
  2653. setBusy: ExceptMessage.CommonNetworkErrorMsg,
  2654. makeCall: ExceptMessage.CommonNetworkErrorMsg,
  2655. answer: ExceptMessage.CommonNetworkErrorMsg,
  2656. bye: ExceptMessage.CommonNetworkErrorMsg,
  2657. loadAgentGroupData: ExceptMessage.CommonNetworkErrorMsg,
  2658. listen: ExceptMessage.CommonNetworkErrorMsg,
  2659. setActiveService: ExceptMessage.CustomNetworkErrorMsg
  2660. };
  2661. const baseRequireParams = ['agent_id', 'saas_id',
  2662. // 'password',
  2663. 'env', 'scene'];
  2664. const monitorRequireParams = ['monitorScene'];
  2665. const allRequiredParams = [...baseRequireParams, ...monitorRequireParams];
  2666. class HsSocket extends EventEmitter {
  2667. constructor(socketOptions) {
  2668. super();
  2669. Object.defineProperty(this, "logger", {
  2670. enumerable: true,
  2671. configurable: true,
  2672. writable: true,
  2673. value: void 0
  2674. });
  2675. Object.defineProperty(this, "socket", {
  2676. enumerable: true,
  2677. configurable: true,
  2678. writable: true,
  2679. value: void 0
  2680. });
  2681. /** 初始化 socket 需要的参数 */
  2682. Object.defineProperty(this, "socketOptions", {
  2683. enumerable: true,
  2684. configurable: true,
  2685. writable: true,
  2686. value: void 0
  2687. });
  2688. /** 心跳延迟时间 */
  2689. Object.defineProperty(this, "heartBeatDelay", {
  2690. enumerable: true,
  2691. configurable: true,
  2692. writable: true,
  2693. value: void 0
  2694. });
  2695. /** 主动关闭链接时间 */
  2696. Object.defineProperty(this, "closeHeartBeatDelay", {
  2697. enumerable: true,
  2698. configurable: true,
  2699. writable: true,
  2700. value: void 0
  2701. });
  2702. /** 心跳检测定时器 */
  2703. Object.defineProperty(this, "heartBeatTimer", {
  2704. enumerable: true,
  2705. configurable: true,
  2706. writable: true,
  2707. value: void 0
  2708. });
  2709. /** 清空心跳检测定时器 */
  2710. Object.defineProperty(this, "closeHeartBeatTimer", {
  2711. enumerable: true,
  2712. configurable: true,
  2713. writable: true,
  2714. value: void 0
  2715. });
  2716. /** 超时次数 */
  2717. // private timeOutCount: number
  2718. /** 最大超时次数限制 */
  2719. Object.defineProperty(this, "imRetryCount", {
  2720. enumerable: true,
  2721. configurable: true,
  2722. writable: true,
  2723. value: void 0
  2724. });
  2725. /** 本次 socket 会话唯一 id */
  2726. Object.defineProperty(this, "sessionId", {
  2727. enumerable: true,
  2728. configurable: true,
  2729. writable: true,
  2730. value: void 0
  2731. });
  2732. /** 页面关闭时 关闭 socket */
  2733. window.addEventListener('onunload', this.closeSocket);
  2734. this.logger = new Logger(socketOptions.loggerLevel, 'HsSocket');
  2735. this.socket = undefined;
  2736. this.heartBeatTimer = null;
  2737. this.closeHeartBeatTimer = null;
  2738. // this.timeOutCount = 0
  2739. this.sessionId = '';
  2740. this.socketOptions = socketOptions;
  2741. this.heartBeatDelay = socketOptions.imHeartTime * 1000 || 3000;
  2742. this.closeHeartBeatDelay = socketOptions.imHeartTime * 1000 || 3000;
  2743. this.imRetryCount = socketOptions.imRetryCount || 10;
  2744. }
  2745. /** @public initSocket 初始化 Socket 连接 */
  2746. initSocket() {
  2747. /** 如果有未断开的连接先断开 */
  2748. this.closeSocket();
  2749. // 设置状态为连接中
  2750. this.emit(SocketEvent.SetSocketStatus, {
  2751. status: exports.SocketStatus.Connecting
  2752. });
  2753. /** https://socket.io/docs/v2/client-api/#iourl */
  2754. this.socket = io(this.socketOptions.imWsServer, {
  2755. transports: ['websocket'],
  2756. reconnectionAttempts: this.imRetryCount,
  2757. reconnectionDelay: this.heartBeatDelay,
  2758. reconnectionDelayMax: this.heartBeatDelay + 1000,
  2759. timeout: this.heartBeatDelay,
  2760. reconnection: true
  2761. });
  2762. /** https://socket.io/docs/v2/client-api/#event-error */
  2763. this.socket.on('error', error => {
  2764. this.logger.error(`socket_error | ${JSON.stringify(error)}`);
  2765. });
  2766. /** https://socket.io/docs/v2/client-api/#event-connect_error-1 */
  2767. this.socket.on('connect_error', error => {
  2768. const errorData = `socket_connect_error | ${JSON.stringify(error)}`;
  2769. this.logger.warn(errorData);
  2770. });
  2771. this.socket.on('reconnecting', res => {
  2772. this.logger.error(`socket_warn | socket_reconnecting | ${res}`);
  2773. this.emit(SocketEvent.SetSocketStatus, {
  2774. status: exports.SocketStatus.ReTry
  2775. });
  2776. });
  2777. this.socket.on('reconnect', res => {
  2778. this.logger.error(`socket_warn | socket_reconnect | ${res}`);
  2779. this.emit(SocketEvent.SetSocketStatus, {
  2780. status: exports.SocketStatus.Ready
  2781. });
  2782. });
  2783. this.socket.on('reconnect_failed', error => {
  2784. this.logger.error(`socket_warn | socket_reconnect_failed | ${error}`);
  2785. this.emit(SocketEvent.SetSocketStatus, {
  2786. status: exports.SocketStatus.Terminated,
  2787. code: exports.HskTerminatedCode.SocketOnReconnectFailed,
  2788. error: `${error}`
  2789. });
  2790. });
  2791. /** https://socket.io/docs/v2/client-api/#event-connect */
  2792. this.socket.on('connect', () => {
  2793. this.emit(SocketEvent.SetSocketStatus, {
  2794. status: exports.SocketStatus.Connected
  2795. });
  2796. this.socketLogin();
  2797. });
  2798. /** https://socket.io/docs/v2/client-api/#event-disconnect */
  2799. this.socket.on('disconnect', reason => {
  2800. const errorMessage = `socket_disconnect | ${reason}`;
  2801. this.logger.warn(errorMessage);
  2802. });
  2803. /** 服务端下行事件 */
  2804. this.socket.on('common_down_data', e => {
  2805. console.log(e, 3434343434);
  2806. if (e && JSON.parse(e) && JSON.parse(e).data) {
  2807. this.emit(SocketEvent.SocketDownEvent, {
  2808. eventData: JSON.parse(JSON.parse(e).data)
  2809. });
  2810. }
  2811. });
  2812. /** 服务端下行指令 */
  2813. this.socket.on('common_down_cmd', e => {
  2814. const {
  2815. clientSessionId
  2816. } = JSON.parse(e);
  2817. console.log('dsdsdsdsdsds', clientSessionId);
  2818. if (clientSessionId === this.sessionId) {
  2819. this.logger.error(`socket status | ${exports.SocketStatus.Terminated} | 坐席在其他页面重新初始化,本页面被踢出`);
  2820. this.emit(SocketEvent.SetSocketStatus, {
  2821. status: exports.SocketStatus.Terminated,
  2822. code: exports.HskTerminatedCode.SocketRepeatLogin,
  2823. error: '您已在其他页面签入,当前页面连接已断开'
  2824. });
  2825. }
  2826. });
  2827. }
  2828. /** @private socketLogin 客户端上行登录事件 */
  2829. socketLogin() {
  2830. const data = {
  2831. // appCode: this.socketOptions.appCode || '1111',
  2832. // token: this.socketOptions.token || '1111',
  2833. userId: this.socketOptions.agent_id
  2834. };
  2835. this.socket && this.socket.emit('login', data, sessionId => {
  2836. console.log(sessionId, '测试一下');
  2837. this.emit(SocketEvent.SetSocketStatus, {
  2838. status: exports.SocketStatus.Ready
  2839. });
  2840. setBaseOption(BaseOption.TrackParams, {
  2841. socket_session_id: sessionId
  2842. });
  2843. this.sessionId = sessionId;
  2844. this.startHeartbeat();
  2845. });
  2846. }
  2847. /** @public closeSocket 关闭 socket 连接 */
  2848. closeSocket() {
  2849. if (this.socket) {
  2850. this.socket.io.opts.reconnection = false;
  2851. this.socket.close();
  2852. // 清除之前的监听事件
  2853. this.socket.removeAllListeners();
  2854. }
  2855. this.socket = undefined;
  2856. this.sessionId = '';
  2857. if (this.heartBeatTimer) {
  2858. window.clearTimeout(this.heartBeatTimer);
  2859. this.heartBeatTimer = null;
  2860. }
  2861. if (this.closeHeartBeatTimer) {
  2862. window.clearTimeout(this.closeHeartBeatTimer);
  2863. this.closeHeartBeatTimer = null;
  2864. }
  2865. }
  2866. /** @private startHeartbeat 开启心跳检测 */
  2867. startHeartbeat() {
  2868. if (this.heartBeatTimer) {
  2869. window.clearTimeout(this.heartBeatTimer);
  2870. this.heartBeatTimer = null;
  2871. }
  2872. if (this.closeHeartBeatTimer) {
  2873. window.clearTimeout(this.closeHeartBeatTimer);
  2874. this.closeHeartBeatTimer = null;
  2875. }
  2876. this.socket && this.heartbeatEvent();
  2877. }
  2878. /** @private heartbeatEvent websocket心跳检测 */
  2879. heartbeatEvent() {
  2880. this.heartBeatTimer = setTimeout(() => {
  2881. this.socket && this.sendHeartbeat();
  2882. /** 如果心跳检测一直没回应,则进行重连 */
  2883. this.closeHeartBeatTimer = setTimeout(() => {
  2884. this.logger.warn('socket_heart_beat | 心跳超时,即将重新连接');
  2885. this.initSocket();
  2886. }, this.closeHeartBeatDelay);
  2887. }, this.heartBeatDelay);
  2888. }
  2889. /** @private sendHeartbeat 客户端上行心跳事件 */
  2890. sendHeartbeat() {
  2891. this.socket && this.socket.emit('heartbeat', JSON.stringify(Object.assign({}, this.socketOptions)), () => {
  2892. this.startHeartbeat();
  2893. });
  2894. }
  2895. }
  2896. const apiLogger = new Logger(window.ctiLoggerLevel || getBaseOption(BaseOption.LoggerLevel), 'HsApi');
  2897. const random16Hex = () => (0x10000 | Math.random() * 0x10000).toString(16).substr(1);
  2898. const random64Hex = () => random16Hex() + random16Hex() + random16Hex() + random16Hex();
  2899. function JPOST({
  2900. baseUrl,
  2901. url,
  2902. data
  2903. }) {
  2904. return __awaiter(this, void 0, void 0, function* () {
  2905. const id = random64Hex();
  2906. const response = yield fetch(baseUrl + url, {
  2907. method: 'POST',
  2908. headers: {
  2909. 'Content-Type': 'application/json',
  2910. 'X-B3-TraceId': id,
  2911. 'X-B3-SpanId': id
  2912. },
  2913. body: JSON.stringify(data)
  2914. });
  2915. if (!response.ok) {
  2916. apiLogger.error(`api response | ${url} | Request failed with status ${response.status}`);
  2917. }
  2918. return response.json();
  2919. });
  2920. }
  2921. const hsTrackJPOST = ({
  2922. baseUrl,
  2923. url = '',
  2924. data
  2925. }) => {
  2926. // eslint-disable-next-line no-async-promise-executor
  2927. return new Promise((resolve, reject) => __awaiter(void 0, void 0, void 0, function* () {
  2928. try {
  2929. const res = yield JPOST({
  2930. baseUrl,
  2931. url,
  2932. data
  2933. });
  2934. const {
  2935. code,
  2936. msg
  2937. } = res;
  2938. console.log(msg);
  2939. if (code === 0) {
  2940. apiLogger.log(`api response | ${url} | ${JSON.stringify(res)}`);
  2941. } else {
  2942. apiLogger.error(`api response | ${url} | ${JSON.stringify(res)}`);
  2943. }
  2944. resolve(res);
  2945. } catch (e) {
  2946. apiLogger.error(`api response | ${url} | ${JSON.stringify(e)}`);
  2947. reject(e);
  2948. }
  2949. }));
  2950. };
  2951. // 获取初始化配置
  2952. const baseUrl = 'http://192.168.100.159:8090';
  2953. const getInitConf = data => {
  2954. return hsTrackJPOST({
  2955. baseUrl,
  2956. url: '/open/agent/get-init-config',
  2957. data
  2958. });
  2959. };
  2960. // 坐席签入
  2961. const agentCheckIn = data => {
  2962. return hsTrackJPOST({
  2963. baseUrl,
  2964. url: '/open/agent/check-in',
  2965. data
  2966. });
  2967. };
  2968. // 坐席签出
  2969. const agentCheckOut = data => {
  2970. return hsTrackJPOST({
  2971. baseUrl,
  2972. url: '/open/agent/check-out',
  2973. data
  2974. });
  2975. };
  2976. // 坐席置闲
  2977. const agentSetIdle = data => {
  2978. return hsTrackJPOST({
  2979. baseUrl,
  2980. url: '/open/agent/idle',
  2981. data
  2982. });
  2983. };
  2984. // 坐席置忙
  2985. const agentSetBusy = data => {
  2986. return hsTrackJPOST({
  2987. baseUrl,
  2988. url: '/open/agent/busy',
  2989. data
  2990. });
  2991. };
  2992. // 获取坐席状态
  2993. const getAgentStatus = data => {
  2994. return hsTrackJPOST({
  2995. baseUrl,
  2996. url: '/open/agent/agent-state',
  2997. data
  2998. });
  2999. };
  3000. // 外呼
  3001. const manualCall = data => {
  3002. return hsTrackJPOST({
  3003. baseUrl,
  3004. url: '/open/agent/manual-call',
  3005. data
  3006. });
  3007. };
  3008. // 挂断
  3009. const manualHang = data => {
  3010. return hsTrackJPOST({
  3011. baseUrl,
  3012. url: '/open/agent/manual-hang',
  3013. data
  3014. });
  3015. };
  3016. // 发起监听
  3017. const listen = data => {
  3018. return hsTrackJPOST({
  3019. baseUrl,
  3020. url: '/open/agent/listen',
  3021. data
  3022. });
  3023. };
  3024. // 获取监控组成员信息
  3025. const loadAgentGroupData = data => {
  3026. return hsTrackJPOST({
  3027. baseUrl,
  3028. url: '/open/monitor/load-agent-group-data',
  3029. data
  3030. });
  3031. };
  3032. // 机器人外呼-签入人工组
  3033. const setActiveServiceTask = data => {
  3034. return hsTrackJPOST({
  3035. baseUrl,
  3036. url: '/open/human-service/member-active',
  3037. data
  3038. });
  3039. };
  3040. // 获取 cti 流程 ID
  3041. const getCtiFlowId = data => {
  3042. return hsTrackJPOST({
  3043. baseUrl,
  3044. url: '/open/num/generate',
  3045. data
  3046. });
  3047. };
  3048. /**
  3049. * @function getServerErrorType 根据服务端返回的 code 生成错误类型
  3050. * @param {number} code
  3051. * @returns {CTIErrorType}
  3052. */
  3053. function getServerErrorType(code) {
  3054. if (code >= 300001 && code <= 399999) return exports.CTIErrorType.ServerTerminated;else return exports.CTIErrorType.ServerError;
  3055. }
  3056. /** @function getUserMedia 获取媒体权限 */
  3057. function getUserMedia() {
  3058. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3059. return function (_target, _methodName, descriptor) {
  3060. const originalMethod = descriptor.value;
  3061. descriptor.value = function (...args) {
  3062. if (navigator && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  3063. navigator.mediaDevices.getUserMedia({
  3064. audio: true,
  3065. video: false
  3066. }).then(() => {
  3067. this.logger.debug('media | getUserMedia | 获取浏览器媒体权限成功');
  3068. return originalMethod.apply(this, args);
  3069. }).catch(error => {
  3070. this.logger.error(`media | getUserMedia | ${error}`);
  3071. this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, {
  3072. type: exports.CTIErrorType.SdkTerminated,
  3073. code: exports.HskTerminatedCode.GetUserMedia,
  3074. msg: error.name === 'NotAllowedError' ? '用户拒绝了获取麦克风权限!' : '获取麦克风权限失败',
  3075. method: 'getUserMedia'
  3076. }, {
  3077. source: TrackSource.FeMedia,
  3078. event_name: 'get_user_media_error',
  3079. error: error.name
  3080. });
  3081. });
  3082. } else {
  3083. this.logger.error('media | getUserMedia | 浏览器版本过低,不支持获取媒体权限');
  3084. this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, {
  3085. type: exports.CTIErrorType.SdkTerminated,
  3086. code: exports.HskTerminatedCode.GetUserMedia,
  3087. msg: '浏览器版本过低,不支持获取媒体权限',
  3088. method: 'getUserMedia'
  3089. }, {
  3090. source: TrackSource.FeMedia,
  3091. event_name: 'get_user_media_not_support'
  3092. });
  3093. }
  3094. };
  3095. return descriptor;
  3096. };
  3097. }
  3098. /**
  3099. * @function checkCTIStatus 校验 cti 状态
  3100. * @param {string} msg
  3101. */
  3102. function checkCTIStatus(msg) {
  3103. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3104. return function (_target, methodName, descriptor) {
  3105. const originalMethod = descriptor.value;
  3106. descriptor.value = function (...args) {
  3107. /** 调用 SDK method */
  3108. this.logger.log(`sdk method | ${methodName} | ${msg}`);
  3109. /** 校验 CTIStatus, 如果不是 Ready 状态,直接报错 */
  3110. if (this.getCTIStatus !== exports.CTIStatus.Ready) {
  3111. const errorData = {
  3112. type: exports.CTIErrorType.SdkTerminated,
  3113. code: exports.HskTerminatedCode.CTITerminated,
  3114. msg: methodExceptMsgMap[methodName],
  3115. method: methodName,
  3116. terminated_source: this._terminatedStatusList
  3117. };
  3118. this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, errorData);
  3119. return Promise.reject(errorData);
  3120. }
  3121. return originalMethod.apply(this, args);
  3122. };
  3123. return descriptor;
  3124. };
  3125. }
  3126. /** @function handleApiRes 统一处理服务端接口返回值 */
  3127. function handleApiRes() {
  3128. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3129. return function (_target, methodName, descriptor) {
  3130. const originalMethod = descriptor.value;
  3131. descriptor.value = function (...args) {
  3132. return __awaiter(this, void 0, void 0, function* () {
  3133. try {
  3134. const res = yield originalMethod.apply(this, args);
  3135. const {
  3136. code,
  3137. msg
  3138. } = res;
  3139. if (code !== 0) {
  3140. const serverErrorType = getServerErrorType(code);
  3141. const errorData = {
  3142. type: serverErrorType,
  3143. code,
  3144. msg: msg,
  3145. method: methodName
  3146. };
  3147. this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, errorData);
  3148. if (serverErrorType === exports.CTIErrorType.ServerTerminated) {
  3149. this.setCTIStatus(exports.CTIStatus.Terminated);
  3150. }
  3151. return Promise.reject(errorData);
  3152. } else {
  3153. return Promise.resolve(res);
  3154. }
  3155. } catch (error) {
  3156. const errorData = {
  3157. type: 'fetch_error',
  3158. code: exports.SdkErrorCode.FetchError,
  3159. msg: JSON.stringify(error),
  3160. method: methodName
  3161. };
  3162. this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, errorData);
  3163. return Promise.reject(errorData);
  3164. }
  3165. });
  3166. };
  3167. return descriptor;
  3168. };
  3169. }
  3170. function validateParams() {
  3171. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3172. return function (_target, _methodName, descriptor) {
  3173. const originalMethod = descriptor.value;
  3174. descriptor.value = function (...args) {
  3175. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3176. const currentParams = args[0];
  3177. let requireList = [];
  3178. if (currentParams.scene === exports.Scene.Monitor) {
  3179. requireList = allRequiredParams;
  3180. } else {
  3181. requireList = baseRequireParams;
  3182. }
  3183. requireList.forEach(param => {
  3184. if (!currentParams[param]) {
  3185. throw `参数[${param}]为必填参数`;
  3186. }
  3187. });
  3188. return originalMethod.apply(this, args);
  3189. };
  3190. return descriptor;
  3191. };
  3192. }
  3193. function generateUniqueId() {
  3194. return 'id-' + Date.now() + '-' + Math.floor(Math.random() * 10000);
  3195. }
  3196. /**
  3197. * 本地提示音
  3198. * _ringAudio 机器人外呼/监听,等待接起提示音
  3199. * _waitAudio 主动外呼,点击拨打时的等待音
  3200. * _byeAudio 结束通话提示音
  3201. */
  3202. const audioList = {
  3203. _ringAudio: 'http://static.fuxicarbon.com/hs-cti/ring.wav',
  3204. _waitAudio: 'http://static.fuxicarbon.com/hs-cti/manual.wav',
  3205. _byeAudio: 'http://static.fuxicarbon.com/hs-cti/bye.wav'
  3206. };
  3207. /** @class HsCTI 红杉外呼类 */
  3208. class HsCTI extends EventEmitter {
  3209. constructor(hsCTIInitOptions) {
  3210. const {
  3211. saas_id,
  3212. agent_id,
  3213. scene,
  3214. env,
  3215. loggerLevel
  3216. } = hsCTIInitOptions;
  3217. super();
  3218. Object.defineProperty(this, "logger", {
  3219. enumerable: true,
  3220. configurable: true,
  3221. writable: true,
  3222. value: void 0
  3223. });
  3224. Object.defineProperty(this, "loggerLevel", {
  3225. enumerable: true,
  3226. configurable: true,
  3227. writable: true,
  3228. value: void 0
  3229. });
  3230. Object.defineProperty(this, "scene", {
  3231. enumerable: true,
  3232. configurable: true,
  3233. writable: true,
  3234. value: void 0
  3235. });
  3236. Object.defineProperty(this, "agent_id", {
  3237. enumerable: true,
  3238. configurable: true,
  3239. writable: true,
  3240. value: void 0
  3241. });
  3242. Object.defineProperty(this, "saas_id", {
  3243. enumerable: true,
  3244. configurable: true,
  3245. writable: true,
  3246. value: void 0
  3247. });
  3248. /** 接口返回的初始化配置 */
  3249. Object.defineProperty(this, "_initOptions", {
  3250. enumerable: true,
  3251. configurable: true,
  3252. writable: true,
  3253. value: void 0
  3254. });
  3255. /** IM socket的实例 */
  3256. Object.defineProperty(this, "_socket", {
  3257. enumerable: true,
  3258. configurable: true,
  3259. writable: true,
  3260. value: void 0
  3261. });
  3262. /** sip.js UA实例 */
  3263. Object.defineProperty(this, "_sipUserAgent", {
  3264. enumerable: true,
  3265. configurable: true,
  3266. writable: true,
  3267. value: void 0
  3268. });
  3269. Object.defineProperty(this, "_callId", {
  3270. enumerable: true,
  3271. configurable: true,
  3272. writable: true,
  3273. value: void 0
  3274. });
  3275. Object.defineProperty(this, "_ctiFlowIdList", {
  3276. enumerable: true,
  3277. configurable: true,
  3278. writable: true,
  3279. value: void 0
  3280. });
  3281. /** 基本参数 */
  3282. Object.defineProperty(this, "_baseParams", {
  3283. enumerable: true,
  3284. configurable: true,
  3285. writable: true,
  3286. value: void 0
  3287. });
  3288. /** 等待提示音播放器 */
  3289. Object.defineProperty(this, "_waitAudio", {
  3290. enumerable: true,
  3291. configurable: true,
  3292. writable: true,
  3293. value: void 0
  3294. });
  3295. /** 振铃提示音播放器 */
  3296. Object.defineProperty(this, "_ringAudio", {
  3297. enumerable: true,
  3298. configurable: true,
  3299. writable: true,
  3300. value: void 0
  3301. });
  3302. /** 结束通话提示音 */
  3303. Object.defineProperty(this, "_byeAudio", {
  3304. enumerable: true,
  3305. configurable: true,
  3306. writable: true,
  3307. value: void 0
  3308. });
  3309. /** 远端音频流播放器 */
  3310. Object.defineProperty(this, "_remoteAudio", {
  3311. enumerable: true,
  3312. configurable: true,
  3313. writable: true,
  3314. value: void 0
  3315. });
  3316. /** CTI状态 */
  3317. Object.defineProperty(this, "_ctiStatus", {
  3318. enumerable: true,
  3319. configurable: true,
  3320. writable: true,
  3321. value: void 0
  3322. });
  3323. Object.defineProperty(this, "_ctiStatusList", {
  3324. enumerable: true,
  3325. configurable: true,
  3326. writable: true,
  3327. value: void 0
  3328. });
  3329. /** sip状态 */
  3330. Object.defineProperty(this, "_sipStatus", {
  3331. enumerable: true,
  3332. configurable: true,
  3333. writable: true,
  3334. value: void 0
  3335. });
  3336. Object.defineProperty(this, "_sipStatusList", {
  3337. enumerable: true,
  3338. configurable: true,
  3339. writable: true,
  3340. value: void 0
  3341. });
  3342. /** socket状态 */
  3343. Object.defineProperty(this, "_socketStatus", {
  3344. enumerable: true,
  3345. configurable: true,
  3346. writable: true,
  3347. value: void 0
  3348. });
  3349. Object.defineProperty(this, "_socketStatusList", {
  3350. enumerable: true,
  3351. configurable: true,
  3352. writable: true,
  3353. value: void 0
  3354. });
  3355. Object.defineProperty(this, "_callStatus", {
  3356. enumerable: true,
  3357. configurable: true,
  3358. writable: true,
  3359. value: void 0
  3360. });
  3361. Object.defineProperty(this, "_terminatedStatusList", {
  3362. enumerable: true,
  3363. configurable: true,
  3364. writable: true,
  3365. value: void 0
  3366. });
  3367. this.loggerLevel = window.ctiLoggerLevel || loggerLevel || exports.LoggerLevels.log;
  3368. this.logger = new Logger(this.loggerLevel, 'HsCTI');
  3369. this._waitAudio = new Audio();
  3370. this._ringAudio = new Audio();
  3371. this._byeAudio = new Audio();
  3372. this._remoteAudio = new Audio();
  3373. this.saas_id = saas_id;
  3374. this.agent_id = agent_id;
  3375. this.scene = scene;
  3376. this._callId = '';
  3377. setBaseOption(BaseOption.ENV, env);
  3378. setBaseOption(BaseOption.LoggerLevel, this.loggerLevel);
  3379. this._baseParams = {
  3380. agent_id,
  3381. saas_id,
  3382. scene
  3383. };
  3384. const baseTrackParams = {
  3385. agent_id: agent_id,
  3386. vcc_id: saas_id,
  3387. scene
  3388. };
  3389. if (scene === exports.Scene.Monitor) {
  3390. const {
  3391. monitorScene
  3392. } = hsCTIInitOptions;
  3393. this._baseParams = Object.assign(Object.assign({}, this._baseParams), {
  3394. monitorScene
  3395. });
  3396. setBaseOption(BaseOption.TrackParams, Object.assign(Object.assign({}, baseTrackParams), {
  3397. monitor_scene: monitorScene
  3398. }), true);
  3399. } else {
  3400. setBaseOption(BaseOption.TrackParams, baseTrackParams, true);
  3401. }
  3402. this.initInstanceOptions();
  3403. this.setCTIStatus(exports.CTIStatus.Initial);
  3404. // 首次获取实例时,将外呼状态置为未开始
  3405. this._callStatus = exports.CallStatus.Stopped;
  3406. this._terminatedStatusList = [];
  3407. }
  3408. get getCTIStatus() {
  3409. return this._ctiStatus;
  3410. }
  3411. get getSocketStatus() {
  3412. return this._socketStatus;
  3413. }
  3414. get getSIPStatus() {
  3415. return this._sipStatus;
  3416. }
  3417. static getInstance(hsCTIInitOptions) {
  3418. if (!HsCTI.instance) {
  3419. HsCTI.instance = new HsCTI(hsCTIInitOptions);
  3420. }
  3421. setBaseOption(BaseOption.TrackParams, {
  3422. clientId: getClientId()
  3423. });
  3424. return HsCTI.instance;
  3425. }
  3426. /** @private 重置实例 */
  3427. initInstanceOptions() {
  3428. this._ctiFlowIdList = [];
  3429. this._ctiStatusList = [];
  3430. this._sipStatusList = [];
  3431. this._socketStatusList = [];
  3432. HsCTI.instance = undefined;
  3433. this._initOptions = undefined;
  3434. resetBaseOption();
  3435. }
  3436. /** @private 优雅关闭 SIP 和 socket */
  3437. clearSocketAndSip() {
  3438. var _a, _b, _c;
  3439. (_a = this._socket) === null || _a === void 0 ? void 0 : _a.closeSocket();
  3440. (_b = this._sipUserAgent) === null || _b === void 0 ? void 0 : _b.unregister();
  3441. (_c = this._sipUserAgent) === null || _c === void 0 ? void 0 : _c.disconnect();
  3442. this._sipUserAgent = undefined;
  3443. }
  3444. /**
  3445. * @private 设置等待音 src
  3446. * @param {AudioName} audioName
  3447. * @param {boolean} loop
  3448. */
  3449. setAudioSrc(audioName, loop) {
  3450. this.logger.debug(`media | 设置等待音 src: ${audioList[audioName]}`);
  3451. this[audioName].src = audioList[audioName];
  3452. this[audioName].currentTime = 0;
  3453. this[audioName].autoplay = false;
  3454. this[audioName].loop = loop;
  3455. }
  3456. playAudio(audioName) {
  3457. this.logger.debug(`media | 播放音频:${audioName}`);
  3458. this[audioName].play();
  3459. }
  3460. stopLocalAudio() {
  3461. switch (this.scene) {
  3462. case exports.Scene.Robot:
  3463. case exports.Scene.Monitor:
  3464. this.stopAudio(AudioName.RingAudio, true);
  3465. break;
  3466. case exports.Scene.Manual:
  3467. this.stopAudio(AudioName.WaitAudio, true);
  3468. break;
  3469. }
  3470. }
  3471. stopAudio(audioName, loop) {
  3472. this.logger.debug(`media | 停止音频播放:${audioName}`);
  3473. this[audioName].src = '';
  3474. setTimeout(() => {
  3475. this.setAudioSrc(audioName, loop);
  3476. }, 1000);
  3477. }
  3478. init() {
  3479. // 不允许重复初始化,必须在销毁sdk后才能重新初始化
  3480. const [lastStatus] = this._ctiStatusList.slice(-1);
  3481. if (lastStatus !== exports.CTIStatus.Initial) return;
  3482. this.setAudioSrc(AudioName.ByeAudio, false);
  3483. this.setAudioSrc(AudioName.RingAudio, true);
  3484. this.setAudioSrc(AudioName.WaitAudio, true);
  3485. // switch (this.scene) {
  3486. // case Scene.Robot:
  3487. // case Scene.Monitor:
  3488. // this.setAudioSrc(AudioName.RingAudio, true)
  3489. // break
  3490. // case Scene.Manual:
  3491. // this.setAudioSrc(AudioName.WaitAudio, true)
  3492. // break
  3493. // }
  3494. this.getInitConfig();
  3495. }
  3496. getInitConfig() {
  3497. return __awaiter(this, void 0, void 0, function* () {
  3498. const res = yield getInitConf(this._baseParams);
  3499. const {
  3500. code,
  3501. data,
  3502. msg
  3503. } = res;
  3504. let initOptions = data;
  3505. /**
  3506. * 由于后端接口层面对于查询来说,查不到不代表异常,所以即使查不到也是正向流程
  3507. * 因此如果传入一个不存在的agent_id,后端也会返回code=0,但是data=null
  3508. * 这里需要根据code===0&&initOptions存在进行联合判断,只有两个条件都成立,才表示该坐席获取fs以及im等配置成功
  3509. */
  3510. initOptions = Object.assign(Object.assign({}, initOptions), {
  3511. imHeartTime: 3,
  3512. // IM 重试次数
  3513. imRetryCount: 3,
  3514. // FS 心跳间隔
  3515. fsHeartTime: 60,
  3516. // FS 重试次数,
  3517. fsRetryCount: 3,
  3518. // FS 重试间隔时间
  3519. fsRetryTime: 60,
  3520. // FS 注册过期时间
  3521. fsRegisterExpireTime: 84000,
  3522. // 单次初始化唯一 ID
  3523. ctiSessionId: generateUniqueId(),
  3524. // IM websocket url
  3525. imWsServer: 'ws://192.168.100.159:8091/ws/cs-im',
  3526. // IM websocket path
  3527. imWsPath: 'ws/cs-im'
  3528. });
  3529. if (code === 0 && initOptions) {
  3530. setBaseOption(BaseOption.TrackParams, {
  3531. sip_server: initOptions.sipServer,
  3532. cti_session_id: initOptions.ctiSessionId
  3533. });
  3534. this._initOptions = initOptions;
  3535. this.initSocket(initOptions);
  3536. this.initSip(initOptions);
  3537. } else {
  3538. this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, {
  3539. type: exports.CTIErrorType.ServerTerminated,
  3540. code: exports.HskTerminatedCode.GetInitConfig,
  3541. // 如果code===0并且initOptions不存在时,代表未查到对应坐席,此时接口返回的msg是空字符串,所以提示文案要特定处理
  3542. msg: code === 0 && !initOptions ? '未查到坐席' : msg,
  3543. method: 'getInitConfig',
  3544. res_code: code
  3545. });
  3546. }
  3547. });
  3548. }
  3549. initSocket(initOptions) {
  3550. this.setSocketStatus({
  3551. status: exports.SocketStatus.Initial
  3552. });
  3553. this._socket = new HsSocket({
  3554. agent_id: this.agent_id,
  3555. saas_id: this.saas_id,
  3556. // appCode: initOptions.appCode,
  3557. imWsServer: initOptions.imWsServer,
  3558. imWsPath: initOptions.imWsPath,
  3559. imHeartTime: initOptions.imHeartTime,
  3560. imRetryCount: initOptions.imRetryCount,
  3561. ctiSessionId: initOptions.ctiSessionId,
  3562. loggerLevel: this.loggerLevel
  3563. });
  3564. this._socket.on(SocketEvent.SocketDownEvent, ({
  3565. eventData
  3566. }) => {
  3567. const {
  3568. eventName,
  3569. ext
  3570. } = eventData;
  3571. this.logger.log(`socket server down | ${eventName} | ${JSON.stringify(ext)}`);
  3572. this.handleSocketDownEvent({
  3573. eventName,
  3574. ext
  3575. });
  3576. });
  3577. this._socket.on(SocketEvent.SetSocketStatus, res => {
  3578. console.log(`set socket statussdsdsdsdsdsdds | ${JSON.stringify(res)}`);
  3579. this.setSocketStatus(res);
  3580. });
  3581. this._socket.initSocket();
  3582. }
  3583. handleSocketDownEvent({
  3584. eventName,
  3585. ext
  3586. }) {
  3587. const ctiFlowId = this._baseParams.ctiFlowId;
  3588. const extCtiFlowId = ext.ctiFlowId;
  3589. if ([exports.Scene.Manual, exports.Scene.Monitor].includes(this.scene) && ctiFlowId && extCtiFlowId && ctiFlowId !== extCtiFlowId) {
  3590. this.logger.error(`cti_flow_id | 不一致! fe: ${ctiFlowId}, server: ${extCtiFlowId}, eventName: ${eventName}`);
  3591. return;
  3592. }
  3593. this.serverEventEmit({
  3594. eventName,
  3595. ext
  3596. });
  3597. }
  3598. /** @private serverEventEmit 统一处理服务端推送的事件 */
  3599. serverEventEmit({
  3600. eventName,
  3601. ext
  3602. }) {
  3603. const NO_EMIT_EVENT_LIST = [exports.CTIEvent.OnRingStart, exports.CTIEvent.OnDetectedTone, exports.CTIEvent.OnRingEnd];
  3604. switch (eventName) {
  3605. case exports.CTIEvent.OnRingStart:
  3606. this.stopLocalAudio();
  3607. break;
  3608. case exports.CTIEvent.OnDetectedTone:
  3609. this.stopLocalAudio();
  3610. break;
  3611. case exports.CTIEvent.OnAgentWorkReport:
  3612. break;
  3613. case exports.CTIEvent.OnCallEnd:
  3614. /** 通话结束:重置可拨打状态,清空本轮通话的CallId */
  3615. this._callStatus = exports.CallStatus.Stopped;
  3616. setBaseOption(BaseOption.TrackParams, {
  3617. call_id: ''
  3618. });
  3619. break;
  3620. case exports.CTIEvent.OnRingEnd:
  3621. /** TODO: 后 4 个事件未来服务端不再推送时删掉 */
  3622. break;
  3623. // do nothing
  3624. }
  3625. if (!NO_EMIT_EVENT_LIST.includes(eventName)) {
  3626. this.eventEmitAndTrack(eventName, ext);
  3627. }
  3628. }
  3629. initSip(initOptions) {
  3630. this.setSipStatus({
  3631. status: exports.SIPStatus.Initial
  3632. });
  3633. const server = initOptions.wss_server;
  3634. const simpleUserPlusOptions = {
  3635. aor: initOptions.sip_server,
  3636. reconnectionAttempts: initOptions.fsRetryCount,
  3637. reconnectionDelay: initOptions.fsRetryTime,
  3638. optionsPingInterval: initOptions.fsHeartTime,
  3639. media: {
  3640. remote: {
  3641. audio: this._remoteAudio
  3642. }
  3643. },
  3644. userAgentOptions: {
  3645. gracefulShutdown: true,
  3646. authorizationPassword: initOptions.phone_pwd,
  3647. sessionDescriptionHandlerFactoryOptions: {
  3648. constraints: {
  3649. audio: {
  3650. echoCancellation: true,
  3651. noiseSuppression: true,
  3652. autoGainControl: true
  3653. },
  3654. video: false
  3655. },
  3656. peerConnectionConfiguration: {
  3657. // iceServers: []
  3658. iceServers: [{
  3659. urls: initOptions.ice_server
  3660. }]
  3661. }
  3662. }
  3663. }
  3664. };
  3665. simpleUserPlusOptions.delegate = this.sipDelegate();
  3666. this._sipUserAgent = new SimpleUserPlus(server, simpleUserPlusOptions);
  3667. this._sipUserAgent.connect().catch(error => {
  3668. const err = `SIP UserAgent 启动失败:${JSON.stringify(error)}`;
  3669. this.logger.error(err);
  3670. this.setSipStatus({
  3671. status: exports.SIPStatus.Terminated,
  3672. code: exports.HskTerminatedCode.SIPInitUserAgent,
  3673. error: err,
  3674. method: 'initSIPJS'
  3675. });
  3676. });
  3677. }
  3678. sipDelegate() {
  3679. return {
  3680. onServerConnect: () => {
  3681. this._sipUserAgent.register();
  3682. },
  3683. onServerDisconnect: () => {
  3684. // 正向关闭UA时会进入此回调
  3685. this.setSipStatus({
  3686. status: exports.SIPStatus.Terminated
  3687. });
  3688. },
  3689. onReconnectStart: () => {
  3690. // 开始重连时将状态流转为ReTry
  3691. this.setSipStatus({
  3692. status: exports.SIPStatus.ReTry
  3693. });
  3694. },
  3695. onReconnectFailed: () => {
  3696. // 重连失败时会进如此回调
  3697. this.setSipStatus({
  3698. status: exports.SIPStatus.Terminated,
  3699. code: exports.HskTerminatedCode.SIPOnDisconnect,
  3700. error: `超过重连次数,终止重连`,
  3701. method: 'onReconnectFailed'
  3702. });
  3703. this.setSipStatus({
  3704. status: exports.SIPStatus.Terminated
  3705. });
  3706. },
  3707. onRegistered: () => {
  3708. this.setSipStatus({
  3709. status: exports.SIPStatus.Ready
  3710. });
  3711. },
  3712. onUserAgentStateChange: state => {
  3713. switch (state) {
  3714. case sip_js.UserAgentState.Started:
  3715. this.setSipStatus({
  3716. status: exports.SIPStatus.Started
  3717. });
  3718. break;
  3719. case sip_js.UserAgentState.Stopped:
  3720. this.setSipStatus({
  3721. status: exports.SIPStatus.Terminated,
  3722. code: this._sipStatusList.includes(exports.SIPStatus.Started) ? exports.HskTerminatedCode.SIPUserAgentStateStopped : exports.HskTerminatedCode.SIPInitUserAgent,
  3723. error: 'SIP UserAgentState 状态停止',
  3724. method: 'onUserAgentStateChange'
  3725. });
  3726. break;
  3727. }
  3728. },
  3729. onInvite: invitation => {
  3730. // this.scene = Scene.Robot
  3731. const callId = invitation.request.getHeader('P-LIBRA-CallId') || invitation.request.getHeader('P-LIBRA-Callid') || '';
  3732. console.log(callId, 2888888888);
  3733. // const ctiFlowId =
  3734. // invitation.request.getHeader('P-LIBRA-CtiFlowId') || ''
  3735. // if (ctiFlowId != this._baseParams.ctiFlowId) {
  3736. // this.logger.error(
  3737. // `cti_flow_id 不一致! fe: ${this._baseParams.ctiFlowId} | P-LIBRA-CtiFlowId: ${ctiFlowId}`
  3738. // )
  3739. // return
  3740. // }
  3741. this._callId = callId;
  3742. console.log(callId, 1888888888);
  3743. setBaseOption(BaseOption.TrackParams, {
  3744. call_id: callId
  3745. });
  3746. this.sessionStateChangeAndTrack(invitation.state);
  3747. if ([exports.Scene.Robot, exports.Scene.Monitor].includes(this.scene)) {
  3748. this.playAudio(AudioName.RingAudio);
  3749. console.log('playAudio', 1888888888);
  3750. }
  3751. if ([exports.Scene.Manual].includes(this.scene)) {
  3752. this.answer();
  3753. console.log('answer', 1888888888);
  3754. }
  3755. invitation.delegate = {
  3756. onCancel: cancel => {
  3757. const error = `sip_invitation_on_cancel | ${JSON.stringify(cancel)}`;
  3758. this.logger.error(error);
  3759. this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, {
  3760. type: exports.CTIErrorType.SdkError,
  3761. code: exports.SdkErrorCode.InvitationCancel,
  3762. msg: '当前通话已结束',
  3763. method: 'sipDelegate'
  3764. }, error);
  3765. }
  3766. };
  3767. invitation.stateChange.addListener(state => {
  3768. this.sessionStateChangeAndTrack(state);
  3769. switch (state) {
  3770. case sip_js.SessionState.Initial:
  3771. case sip_js.SessionState.Establishing:
  3772. break;
  3773. case sip_js.SessionState.Established:
  3774. if ([exports.Scene.Robot, exports.Scene.Monitor].includes(this.scene)) {
  3775. this.stopLocalAudio();
  3776. }
  3777. break;
  3778. case sip_js.SessionState.Terminating:
  3779. break;
  3780. case sip_js.SessionState.Terminated:
  3781. this.playAudio(AudioName.ByeAudio);
  3782. setTimeout(() => {
  3783. this.stopAudio(AudioName.ByeAudio, false);
  3784. }, 1000);
  3785. this.stopLocalAudio();
  3786. // this._baseParams.scene = Scene.Manual
  3787. setBaseOption(BaseOption.TrackParams, {
  3788. call_id: ''
  3789. });
  3790. if (this.scene == exports.Scene.Manual) {
  3791. this.scene = exports.Scene.Robot;
  3792. this._baseParams.scene = exports.Scene.Robot;
  3793. }
  3794. break;
  3795. }
  3796. });
  3797. }
  3798. };
  3799. }
  3800. sessionStateChangeAndTrack(status) {
  3801. this.eventEmitAndTrack(exports.CTIEvent.OnSessionStatusChange, {
  3802. status
  3803. });
  3804. const trackName = `sip_session_state_${upperCamelToLowerSnake(status)}`;
  3805. this.logger.log(trackName);
  3806. }
  3807. /**
  3808. * @private setCTIStatus CTI 状态流转
  3809. * @param {CTIStatus} ctiStatus
  3810. */
  3811. setCTIStatus(ctiStatus) {
  3812. if (ctiStatus === this.getCTIStatus) return;
  3813. this._ctiStatus = ctiStatus;
  3814. this._ctiStatusList.push(ctiStatus);
  3815. const logInfo = `cti status | ${ctiStatus} | ${this._ctiStatusList}`;
  3816. if (ctiStatus === exports.CTIStatus.Terminated) {
  3817. this.setSocketStatus({
  3818. status: exports.SocketStatus.Terminated
  3819. });
  3820. this.setSipStatus({
  3821. status: exports.SIPStatus.Terminated
  3822. });
  3823. this.stopLocalAudio();
  3824. this.logger.warn(logInfo);
  3825. } else {
  3826. this.logger.debug(logInfo);
  3827. }
  3828. if (ctiStatus === exports.CTIStatus.Ready) {
  3829. this.setSocketStatus({
  3830. status: exports.SocketStatus.Ready
  3831. });
  3832. this.setSipStatus({
  3833. status: exports.SIPStatus.Ready
  3834. });
  3835. this._terminatedStatusList = [];
  3836. if (!this._ctiStatusList.includes(exports.CTIStatus.ReTry)) {
  3837. this.checkIn();
  3838. }
  3839. }
  3840. }
  3841. /**
  3842. * @private setSocketStatus Socket 状态流转
  3843. * @param SocketStatusChangeParams Socket 状态流转参数及错误详情等
  3844. */
  3845. setSocketStatus({
  3846. status,
  3847. code,
  3848. error
  3849. }) {
  3850. if (status === this.getSocketStatus) return;
  3851. this._socketStatus = status;
  3852. this._socketStatusList.push(status);
  3853. const logInfo = `socket status | ${status} | ${this._socketStatusList}`;
  3854. status === exports.SocketStatus.Terminated ? this.logger.warn(logInfo) : this.logger.debug(logInfo);
  3855. this.socketOrSipStatusChange(status, this.getSIPStatus);
  3856. if (error) {
  3857. this._terminatedStatusList.push(code);
  3858. this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, {
  3859. type: exports.CTIErrorType.SdkTerminated,
  3860. code,
  3861. msg: code === exports.HskTerminatedCode.SocketRepeatLogin ? ExceptMessage.CTIRepeatLoginMsg : ExceptMessage.CommonNetworkErrorMsg,
  3862. method: 'setSocketStatus'
  3863. }, {
  3864. error_msg: error,
  3865. socket_status_list: this._socketStatusList,
  3866. sip_status_list: this._sipStatusList,
  3867. cti_status_list: this._ctiStatusList
  3868. });
  3869. this.clearSocketAndSip();
  3870. }
  3871. }
  3872. /**
  3873. * @private setSipStatus SIP 状态流转
  3874. * @param SIPStatusChangeParams SIP 状态流转参数及错误详情等
  3875. */
  3876. setSipStatus({
  3877. status,
  3878. code,
  3879. error,
  3880. method
  3881. }) {
  3882. if (status === this.getSIPStatus) return;
  3883. this._sipStatus = status;
  3884. this._sipStatusList.push(status);
  3885. const logInfo = `sip status | ${status} | ${this._sipStatusList}`;
  3886. status === exports.SIPStatus.Terminated ? this.logger.warn(logInfo) : this.logger.debug(logInfo);
  3887. this.socketOrSipStatusChange(this.getSocketStatus, status);
  3888. if (error) {
  3889. /** 抛出 SIP 类型的错误详情 */
  3890. this._terminatedStatusList.push(code);
  3891. this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, {
  3892. type: exports.CTIErrorType.SdkTerminated,
  3893. code,
  3894. msg: ExceptMessage.CommonNetworkErrorMsg,
  3895. method: method || 'setSipStatus'
  3896. }, {
  3897. error_msg: error,
  3898. socket_status_list: this._socketStatusList,
  3899. sip_status_list: this._sipStatusList,
  3900. cti_status_list: this._ctiStatusList
  3901. });
  3902. this.clearSocketAndSip();
  3903. }
  3904. }
  3905. /**
  3906. * @private socketOrSipStatusChange Socket 或 SIP 状态变化可能引起 CTI 状态变化
  3907. * @param {SocketStatus} socketStatus
  3908. * @param {SIPStatus} sipStatus
  3909. */
  3910. socketOrSipStatusChange(socketStatus, sipStatus) {
  3911. if (socketStatus === exports.SocketStatus.Ready && sipStatus === exports.SIPStatus.Ready) {
  3912. this.setCTIStatus(exports.CTIStatus.Ready);
  3913. }
  3914. // if (socketStatus === SocketStatus.Ready) {
  3915. // this.setCTIStatus(CTIStatus.Ready)
  3916. // }
  3917. if (socketStatus === exports.SocketStatus.ReTry || sipStatus === exports.SIPStatus.ReTry) {
  3918. this.setCTIStatus(exports.CTIStatus.ReTry);
  3919. }
  3920. if (socketStatus === exports.SocketStatus.Terminated || sipStatus === exports.SIPStatus.Terminated) {
  3921. this.setCTIStatus(exports.CTIStatus.Terminated);
  3922. }
  3923. }
  3924. /**
  3925. * @private eventEmitAndTrack SDK 对外抛出事件并统一埋点
  3926. * @param {CTIEvent} eventName 事件名称
  3927. * @param {object} ext 事件参数
  3928. * @param { error } error 错误详情或错误辅助信息
  3929. */
  3930. eventEmitAndTrack(eventName, ext, error) {
  3931. this.logger.debug(`sdk emit | ${eventName} | ${JSON.stringify(ext)}`);
  3932. // 如果出现异常,则将通话状态置为结束
  3933. if (eventName === exports.CTIEvent.OnCtiError) {
  3934. this._callStatus = exports.CallStatus.Stopped;
  3935. }
  3936. try {
  3937. this.emit(eventName, ext);
  3938. console.log(error);
  3939. } catch (error) {
  3940. this.logger.error(`业务监听 ${eventName} 事件,处理回调时报错: ${error}`);
  3941. }
  3942. }
  3943. /** @private checkIn 服务端签入,CTIStatus Ready 时自动调用,坐席状态变更 */
  3944. checkIn() {
  3945. return __awaiter(this, void 0, void 0, function* () {
  3946. const res = yield agentCheckIn(this._baseParams);
  3947. if (res.code === 0) {
  3948. this.eventEmitAndTrack(exports.CTIEvent.OnInitalSuccess, {
  3949. saas_id: this.saas_id,
  3950. agent_id: this.agent_id,
  3951. scene: this.scene,
  3952. phoneNum: this._initOptions.phone_num,
  3953. sipServer: this._initOptions.sip_server
  3954. });
  3955. }
  3956. return res;
  3957. });
  3958. }
  3959. /** @public checkOut 服务端签出, unInit 时自动调用,坐席状态变更 */
  3960. checkOut() {
  3961. return __awaiter(this, void 0, void 0, function* () {
  3962. return yield agentCheckOut(this._baseParams);
  3963. });
  3964. }
  3965. /** @private _getCtiFlowId 获取手动外呼场景需要的 ctiFlowId */
  3966. getCtiFlowId() {
  3967. return __awaiter(this, void 0, void 0, function* () {
  3968. const res = yield getCtiFlowId(this._baseParams);
  3969. const {
  3970. code,
  3971. data
  3972. } = res;
  3973. if (code === 0) {
  3974. this._baseParams.ctiFlowId = data;
  3975. this._ctiFlowIdList.push(data);
  3976. setBaseOption(BaseOption.TrackParams, {
  3977. cti_flow_id: data,
  3978. cti_flow_id_list: JSON.stringify(this._ctiFlowIdList)
  3979. });
  3980. }
  3981. return res;
  3982. });
  3983. }
  3984. /** @public setIdle 服务端置闲,坐席状态变更 */
  3985. setIdle() {
  3986. return __awaiter(this, void 0, void 0, function* () {
  3987. this.scene = exports.Scene.Robot;
  3988. this._baseParams.scene = exports.Scene.Robot;
  3989. return yield agentSetIdle(this._baseParams);
  3990. });
  3991. }
  3992. /** @public setBusy 服务端置忙,坐席状态变更 */
  3993. setBusy() {
  3994. return __awaiter(this, void 0, void 0, function* () {
  3995. return yield agentSetBusy(this._baseParams);
  3996. });
  3997. }
  3998. makeCall(params) {
  3999. return __awaiter(this, void 0, void 0, function* () {
  4000. this.scene = exports.Scene.Manual;
  4001. this._baseParams.scene = exports.Scene.Manual;
  4002. // 如果当前通话状态处于外呼开始,则不允许再次调用此方法并上报埋点
  4003. if (this._callStatus === exports.CallStatus.Started) {
  4004. return;
  4005. }
  4006. this._callStatus = exports.CallStatus.Started;
  4007. yield this.getCtiFlowId();
  4008. this.playAudio(AudioName.WaitAudio);
  4009. return yield this.serverCall(params);
  4010. });
  4011. }
  4012. serverCall({
  4013. called,
  4014. caller,
  4015. ext
  4016. }) {
  4017. return __awaiter(this, void 0, void 0, function* () {
  4018. const params = Object.assign(Object.assign(Object.assign({}, this._baseParams), {
  4019. called,
  4020. caller
  4021. }), ext);
  4022. const res = yield manualCall(params);
  4023. const {
  4024. code,
  4025. data
  4026. } = res;
  4027. if (code === 0) {
  4028. if (this._callId === '' && data) {
  4029. this._callId = data;
  4030. setBaseOption(BaseOption.TrackParams, {
  4031. call_id: data
  4032. });
  4033. }
  4034. } else {
  4035. // 外呼接口调用失败将通话状态置为结束不阻碍下次外呼
  4036. this._callStatus = exports.CallStatus.Stopped;
  4037. this.stopLocalAudio();
  4038. }
  4039. return res;
  4040. });
  4041. }
  4042. /** @public answer SDK SIP 接起 */
  4043. answer() {
  4044. return new Promise((resolve, reject) => {
  4045. var _a;
  4046. (_a = this._sipUserAgent) === null || _a === void 0 ? void 0 : _a.answer({
  4047. sessionDescriptionHandlerOptions: {
  4048. constraints: {
  4049. audio: true,
  4050. video: false
  4051. }
  4052. }
  4053. }).then(() => {
  4054. resolve({
  4055. code: 0,
  4056. data: 'answer',
  4057. msg: 'SIP 接起电话成功'
  4058. });
  4059. this.logger.debug('sip_accept_success');
  4060. }).catch(err => {
  4061. const errorData = {
  4062. type: exports.CTIErrorType.SdkError,
  4063. code: exports.SdkErrorCode.Answer,
  4064. msg: this.scene === exports.Scene.Manual ? ExceptMessage.ManualCallAnswerErrorMsg : ExceptMessage.RobotOrWeChatAnswerErrorMsg,
  4065. method: 'answer'
  4066. };
  4067. reject(errorData);
  4068. this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, errorData, `${err}`);
  4069. this.logger.error(`${exports.CTIEvent.OnCtiError} | ${err}`);
  4070. });
  4071. });
  4072. }
  4073. /** @public bye SDK SIP 挂断 */
  4074. bye() {
  4075. return new Promise((resolve, reject) => {
  4076. var _a;
  4077. (_a = this._sipUserAgent) === null || _a === void 0 ? void 0 : _a.hangup().then(() => {
  4078. resolve({
  4079. code: 0,
  4080. data: 'bye',
  4081. msg: 'SIP 挂断电话成功'
  4082. });
  4083. this.logger.debug('sip_bye_success');
  4084. }).catch(err => {
  4085. const errorData = {
  4086. type: exports.CTIErrorType.SdkError,
  4087. code: exports.SdkErrorCode.Bye,
  4088. msg: ExceptMessage.SipByeErrorMsg,
  4089. method: 'bye'
  4090. };
  4091. reject(errorData);
  4092. if (err.message !== 'Session does not exist.') {
  4093. this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, errorData, `${err}`);
  4094. }
  4095. this.logger.error(`${exports.CTIEvent.OnCtiError} | ${err}`);
  4096. });
  4097. });
  4098. }
  4099. /** @public serverBye 挂断且流转坐席状态 */
  4100. serverBye() {
  4101. return __awaiter(this, void 0, void 0, function* () {
  4102. try {
  4103. this.bye();
  4104. // 如果人工外呼场景下,没有flowId则不调用并上报埋点
  4105. // if (!this._baseParams.ctiFlowId && this.scene === Scene.Manual) {
  4106. // return
  4107. // }
  4108. const res = yield this.turnHang();
  4109. return Promise.resolve(res);
  4110. } catch (error) {
  4111. return Promise.reject(error);
  4112. }
  4113. });
  4114. }
  4115. /** @public turnHang 流转坐席状态-通话结束 */
  4116. turnHang() {
  4117. return __awaiter(this, void 0, void 0, function* () {
  4118. const res = yield manualHang(Object.assign(Object.assign({}, this._baseParams), {
  4119. call_id: this._callId
  4120. }));
  4121. this._callId = '';
  4122. return res;
  4123. });
  4124. }
  4125. /** @public getAgentStatus 获取坐席状态 */
  4126. getAgentStatus() {
  4127. return __awaiter(this, void 0, void 0, function* () {
  4128. return yield getAgentStatus(this._baseParams);
  4129. });
  4130. }
  4131. /**
  4132. * @public loadAgentGroupData 监听-根据监听组 ID 获取监听组成员
  4133. * @param {string[]} monitorIds
  4134. */
  4135. loadAgentGroupData(monitorIds) {
  4136. return __awaiter(this, void 0, void 0, function* () {
  4137. return yield loadAgentGroupData(Object.assign(Object.assign({}, this._baseParams), {
  4138. monitorIds
  4139. }));
  4140. });
  4141. }
  4142. /**
  4143. * @public listen 监听-服务端发起监听
  4144. * @param {string} monitoredAgNo
  4145. */
  4146. listen(monitoredAgNo) {
  4147. return __awaiter(this, void 0, void 0, function* () {
  4148. const flowIdRes = yield this.getCtiFlowId();
  4149. if (flowIdRes && flowIdRes.code !== 0) {
  4150. return flowIdRes;
  4151. }
  4152. return yield listen(Object.assign(Object.assign({}, this._baseParams), {
  4153. agent_id: monitoredAgNo,
  4154. leaderAgentId: this.agent_id
  4155. }));
  4156. });
  4157. }
  4158. /**
  4159. * @public setActiveService 机器人外呼-签入人工组
  4160. * @param {string} serviceId
  4161. */
  4162. setActiveService(serviceId) {
  4163. return __awaiter(this, void 0, void 0, function* () {
  4164. return yield setActiveServiceTask(Object.assign(Object.assign({}, this._baseParams), {
  4165. serviceId
  4166. }));
  4167. });
  4168. }
  4169. /** @public unInit 卸载 SDK,checkOut 成功后断开 socket 和 sip 连接,并销毁 SdCTI 实例 */
  4170. unInit() {
  4171. return __awaiter(this, void 0, void 0, function* () {
  4172. yield this.checkOut();
  4173. this.setCTIStatus(exports.CTIStatus.Terminated);
  4174. this.initInstanceOptions();
  4175. this.clearSocketAndSip();
  4176. this._callId = '';
  4177. });
  4178. }
  4179. }
  4180. __decorate([getUserMedia()], HsCTI.prototype, "init", null);
  4181. __decorate([checkCTIStatus('签入'), handleApiRes()], HsCTI.prototype, "checkIn", null);
  4182. __decorate([checkCTIStatus('签出'), handleApiRes()], HsCTI.prototype, "checkOut", null);
  4183. __decorate([handleApiRes()], HsCTI.prototype, "getCtiFlowId", null);
  4184. __decorate([checkCTIStatus('置闲'), handleApiRes()], HsCTI.prototype, "setIdle", null);
  4185. __decorate([checkCTIStatus('置忙'), handleApiRes()], HsCTI.prototype, "setBusy", null);
  4186. __decorate([checkCTIStatus('人工外呼')], HsCTI.prototype, "makeCall", null);
  4187. __decorate([handleApiRes()], HsCTI.prototype, "serverCall", null);
  4188. __decorate([checkCTIStatus('接起')], HsCTI.prototype, "answer", null);
  4189. __decorate([checkCTIStatus('挂断')], HsCTI.prototype, "bye", null);
  4190. __decorate([handleApiRes()], HsCTI.prototype, "turnHang", null);
  4191. __decorate([handleApiRes()], HsCTI.prototype, "getAgentStatus", null);
  4192. __decorate([checkCTIStatus('获取监听组成员'), handleApiRes()], HsCTI.prototype, "loadAgentGroupData", null);
  4193. __decorate([checkCTIStatus('坐席监听'), handleApiRes()], HsCTI.prototype, "listen", null);
  4194. __decorate([checkCTIStatus('签入人工组'), handleApiRes()], HsCTI.prototype, "setActiveService", null);
  4195. __decorate([validateParams()], HsCTI, "getInstance", null);
  4196. /**
  4197. * @function getInstance 获取 HsCTI 的实例
  4198. * @param HsCTIInitOptions 初始化 HsCTI 的配置
  4199. */
  4200. const getInstance = HsCTIInitOptions => HsCTI.getInstance(HsCTIInitOptions);
  4201. exports.Logger = Logger;
  4202. exports.getInstance = getInstance;
  4203. }));