123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196 |
- /*!
- - Name HS_CTI
- - FileName hs-cti
- - Version 1.0.9
- - JS Standard es5
- - Author platformfe
- - Built on 2024/11/30 19:22:58
- - GitHub
- - Branch dev_20241128
- - CommitID 0c10b4e431cfa4ea6c1364f2b4fdb2320d5cf659
- - CommitMessage feat: init
- */
- (function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('sip.js'), require('socket.io-client')) :
- typeof define === 'function' && define.amd ? define(['exports', 'sip.js', 'socket.io-client'], factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.HS_CTI = {}, global.SIP, global.io));
- })(this, (function (exports, sip_js, io) { 'use strict';
- /******************************************************************************
- Copyright (c) Microsoft Corporation.
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted.
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- PERFORMANCE OF THIS SOFTWARE.
- ***************************************************************************** */
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf || {
- __proto__: []
- } instanceof Array && function (d, b) {
- d.__proto__ = b;
- } || function (d, b) {
- for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
- };
- return extendStatics(d, b);
- };
- function __extends(d, b) {
- if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() {
- this.constructor = d;
- }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- }
- var __assign = function () {
- __assign = Object.assign || function __assign(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
- };
- function __decorate(decorators, target, key, desc) {
- var c = arguments.length,
- r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
- d;
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- }
- function __awaiter(thisArg, _arguments, P, generator) {
- function adopt(value) {
- return value instanceof P ? value : new P(function (resolve) {
- resolve(value);
- });
- }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) {
- try {
- step(generator.next(value));
- } catch (e) {
- reject(e);
- }
- }
- function rejected(value) {
- try {
- step(generator["throw"](value));
- } catch (e) {
- reject(e);
- }
- }
- function step(result) {
- result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
- }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- }
- function __generator(thisArg, body) {
- var _ = {
- label: 0,
- sent: function () {
- if (t[0] & 1) throw t[1];
- return t[1];
- },
- trys: [],
- ops: []
- },
- f,
- y,
- t,
- g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function () {
- return this;
- }), g;
- function verb(n) {
- return function (v) {
- return step([n, v]);
- };
- }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0:
- case 1:
- t = op;
- break;
- case 4:
- _.label++;
- return {
- value: op[1],
- done: false
- };
- case 5:
- _.label++;
- y = op[1];
- op = [0];
- continue;
- case 7:
- op = _.ops.pop();
- _.trys.pop();
- continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
- _ = 0;
- continue;
- }
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
- _.label = op[1];
- break;
- }
- if (op[0] === 6 && _.label < t[1]) {
- _.label = t[1];
- t = op;
- break;
- }
- if (t && _.label < t[2]) {
- _.label = t[2];
- _.ops.push(op);
- break;
- }
- if (t[2]) _.ops.pop();
- _.trys.pop();
- continue;
- }
- op = body.call(thisArg, _);
- } catch (e) {
- op = [6, e];
- y = 0;
- } finally {
- f = t = 0;
- }
- if (op[0] & 5) throw op[1];
- return {
- value: op[0] ? op[1] : void 0,
- done: true
- };
- }
- }
- function __spreadArray(to, from, pack) {
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
- if (ar || !(i in from)) {
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
- ar[i] = from[i];
- }
- }
- return to.concat(ar || Array.prototype.slice.call(from));
- }
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
- var e = new Error(message);
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
- };
- /**
- * A session manager for SIP.js sessions.
- * @public
- */
- var SessionManagerPlus = /** @class */function () {
- /**
- * Constructs a new instance of the `SessionManager` class.
- * @param server - SIP WebSocket Server URL.
- * @param options - Options bucket. See {@link Web.SessionManagerOptions} for details.
- */
- function SessionManagerPlus(server, options) {
- if (options === void 0) {
- options = {};
- }
- var _this = this;
- /** Delegate. */
- Object.defineProperty(this, "delegate", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** Sessions being managed. */
- Object.defineProperty(this, "managedSessions", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: []
- });
- /** User agent which created sessions being managed. */
- Object.defineProperty(this, "userAgent", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "logger", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "options", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "optionsPingFailure", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: false
- });
- Object.defineProperty(this, "optionsPingRequest", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "optionsPingRunning", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: false
- });
- Object.defineProperty(this, "optionsPingTimeout", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "registrationAttemptTimeout", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "registerer", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "registererOptions", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "registererRegisterOptions", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "shouldBeConnected", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: false
- });
- Object.defineProperty(this, "shouldBeRegistered", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: false
- });
- Object.defineProperty(this, "attemptingReconnection", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: false
- });
- // Delegate
- this.delegate = options.delegate;
- // Copy options
- this.options = __assign({
- aor: '',
- autoStop: true,
- delegate: {},
- iceStopWaitingOnServerReflexive: false,
- managedSessionFactory: this.managedSessionFactory,
- maxSimultaneousSessions: 2,
- media: {},
- optionsPingInterval: -1,
- optionsPingRequestURI: '',
- reconnectionAttempts: 3,
- reconnectionDelay: 3,
- registrationRetry: false,
- registrationRetryInterval: 3,
- registerGuard: null,
- registererOptions: {},
- registererRegisterOptions: {},
- sendDTMFUsingSessionDescriptionHandler: false,
- userAgentOptions: {}
- }, SessionManagerPlus.stripUndefinedProperties(options));
- // UserAgentOptions
- var userAgentOptions = __assign({}, options.userAgentOptions);
- // Transport
- if (!userAgentOptions.transportConstructor) {
- userAgentOptions.transportConstructor = sip_js.Web.Transport;
- }
- // TransportOptions
- if (!userAgentOptions.transportOptions) {
- userAgentOptions.transportOptions = {
- server: server
- };
- }
- // URI
- if (!userAgentOptions.uri) {
- // If an AOR was provided, convert it to a URI
- if (options.aor) {
- var uri = sip_js.UserAgent.makeURI(options.aor);
- if (!uri) {
- throw new Error("Failed to create valid URI from ".concat(options.aor));
- }
- userAgentOptions.uri = uri;
- }
- }
- // UserAgent
- this.userAgent = new sip_js.UserAgent(userAgentOptions);
- // UserAgent's delegate
- this.userAgent.delegate = {
- // Handle connection with server established
- onConnect: function () {
- _this.logger.log("Connected");
- if (_this.delegate && _this.delegate.onServerConnect) {
- _this.delegate.onServerConnect();
- }
- // Attempt to register if we are supposed to be registered
- if (_this.shouldBeRegistered) {
- _this.register();
- }
- // Start OPTIONS pings if we are to be pinging
- if (_this.options.optionsPingInterval > 0) {
- _this.optionsPingStart();
- }
- },
- // Handle connection with server lost
- onDisconnect: function (error) {
- return __awaiter(_this, void 0, void 0, function () {
- var optionsPingFailure;
- var _this = this;
- var _a, _b, _c, _d;
- return __generator(this, function (_e) {
- this.logger.log("Disconnected");
- optionsPingFailure = false;
- if (this.options.optionsPingInterval > 0) {
- optionsPingFailure = this.optionsPingFailure;
- this.optionsPingFailure = false;
- this.optionsPingStop();
- }
- // If the user called `disconnect` a graceful cleanup will be done therein.
- // Only cleanup if network/server dropped the connection.
- // Only reconnect if network/server dropped the connection
- if (error || optionsPingFailure) {
- // There is no transport at this point, so we are not expecting to be able to
- // send messages much less get responses. So just dispose of everything without
- // waiting for anything to succeed.
- if (this.registerer) {
- this.logger.log("Disposing of registerer...");
- this.registerer.dispose().catch(function (e) {
- _this.logger.debug("Error occurred disposing of registerer after connection with server was lost.");
- _this.logger.debug(e.toString());
- });
- this.registerer = undefined;
- }
- this.managedSessions.slice().map(function (el) {
- return el.session;
- }).forEach(function (session) {
- return __awaiter(_this, void 0, void 0, function () {
- var _this = this;
- return __generator(this, function (_a) {
- this.logger.log("Disposing of session...");
- session.dispose().catch(function (e) {
- _this.logger.debug("Error occurred disposing of a session after connection with server was lost.");
- _this.logger.debug(e.toString());
- });
- return [2 /*return*/];
- });
- });
- });
- // Attempt to reconnect if we are supposed to be connected.
- if (this.shouldBeConnected) {
- (_b = (_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onReconnectStart) === null || _b === void 0 ? void 0 : _b.call(_a);
- this.attemptReconnection();
- }
- } else {
- // Let delgate know we have disconnected
- (_d = (_c = this.delegate) === null || _c === void 0 ? void 0 : _c.onServerDisconnect) === null || _d === void 0 ? void 0 : _d.call(_c, error);
- }
- return [2 /*return*/];
- });
- });
- },
- // Handle incoming invitations
- onInvite: function (invitation) {
- _this.logger.log("[".concat(invitation.id, "] Received INVITE"));
- // Guard against a maximum number of pre-existing sessions.
- // An incoming INVITE request may be received at any time and/or while in the process
- // of sending an outgoing INVITE request. So we reject any incoming INVITE in those cases.
- var maxSessions = _this.options.maxSimultaneousSessions;
- if (maxSessions !== 0 && _this.managedSessions.length > maxSessions) {
- _this.logger.warn("[".concat(invitation.id, "] Session already in progress, rejecting INVITE..."));
- invitation.reject().then(function () {
- _this.logger.log("[".concat(invitation.id, "] Rejected INVITE"));
- }).catch(function (error) {
- _this.logger.error("[".concat(invitation.id, "] Failed to reject INVITE"));
- _this.logger.error(error.toString());
- });
- return;
- }
- // Use our configured constraints as options for any Inviter created as result of a REFER
- var referralInviterOptions = {
- sessionDescriptionHandlerOptions: {
- constraints: _this.constraints
- }
- };
- // Initialize our session
- _this.initSession(invitation, referralInviterOptions);
- // Delegate
- if (_this.delegate && _this.delegate.onCallReceived) {
- _this.delegate.onCallReceived(invitation);
- } else {
- _this.logger.warn("[".concat(invitation.id, "] No handler available, rejecting INVITE..."));
- invitation.reject().then(function () {
- _this.logger.log("[".concat(invitation.id, "] Rejected INVITE"));
- }).catch(function (error) {
- _this.logger.error("[".concat(invitation.id, "] Failed to reject INVITE"));
- _this.logger.error(error.toString());
- });
- }
- },
- // Handle incoming messages
- onMessage: function (message) {
- message.accept().then(function () {
- if (_this.delegate && _this.delegate.onMessageReceived) {
- _this.delegate.onMessageReceived(message);
- }
- });
- },
- // Handle incoming notifications
- onNotify: function (notification) {
- notification.accept().then(function () {
- if (_this.delegate && _this.delegate.onNotificationReceived) {
- _this.delegate.onNotificationReceived(notification);
- }
- });
- }
- };
- // RegistererOptions
- this.registererOptions = __assign({}, options.registererOptions);
- // RegistererRegisterOptions
- this.registererRegisterOptions = __assign({}, options.registererRegisterOptions);
- // Retry registration on failure or rejection.
- if (this.options.registrationRetry) {
- // If the register request is rejected, try again...
- this.registererRegisterOptions.requestDelegate = this.registererRegisterOptions.requestDelegate || {};
- var existingOnReject_1 = this.registererRegisterOptions.requestDelegate.onReject;
- this.registererRegisterOptions.requestDelegate.onReject = function (response) {
- existingOnReject_1 && existingOnReject_1(response);
- // If at first we don't succeed, try try again...
- _this.attemptRegistration();
- };
- }
- // Use the SIP.js logger
- this.logger = this.userAgent.getLogger('sip.SessionManager');
- // Monitor network connectivity and attempt reconnection and reregistration when we come online
- window.addEventListener('online', function () {
- _this.logger.log("Online");
- if (_this.shouldBeConnected) {
- _this.connect();
- }
- });
- // NOTE: The autoStop option does not currently work as one likley expects.
- // This code is here because the "autoStop behavior" and this assoicated
- // implemenation has been a recurring request. So instead of removing
- // the implementation again (because it doesn't work) and then having
- // to explain agian the issue over and over again to those who want it,
- // we have included it here to break that cycle. The implementation is
- // harmless and serves to provide an explaination for those interested.
- if (this.options.autoStop) {
- // Standard operation workflow will resume after this callback exits, meaning
- // that any asynchronous operations are likely not going to be finished, especially
- // if they are guaranteed to not be executed in the current tick (promises fall
- // under this category, they will never be resolved synchronously by design).
- window.addEventListener('beforeunload', function () {
- return __awaiter(_this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- this.shouldBeConnected = false;
- this.shouldBeRegistered = false;
- if (!(this.userAgent.state !== sip_js.UserAgentState.Stopped)) return [3 /*break*/, 2];
- // The stop() method returns a promise which will not resolve before the page unloads.
- return [4 /*yield*/, this.userAgent.stop()];
- case 1:
- // The stop() method returns a promise which will not resolve before the page unloads.
- _a.sent();
- _a.label = 2;
- case 2:
- return [2 /*return*/];
- }
- });
- });
- });
- }
- }
- /**
- * Strip properties with undefined values from options.
- * This is a work around while waiting for missing vs undefined to be addressed (or not)...
- * https://github.com/Microsoft/TypeScript/issues/13195
- * @param options - Options to reduce
- */
- Object.defineProperty(SessionManagerPlus, "stripUndefinedProperties", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (options) {
- return Object.keys(options).reduce(function (object, key) {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- if (options[key] !== undefined) {
- object[key] = options[key];
- }
- return object;
- }, {});
- }
- });
- /**
- * The local media stream. Undefined if call not answered.
- * @param session - Session to get the media stream from.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "getLocalMediaStream", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- var hsh = session.sessionDescriptionHandler;
- if (!hsh) {
- return undefined;
- }
- if (!(hsh instanceof sip_js.Web.SessionDescriptionHandler)) {
- throw new Error('Session description handler not instance of web SessionDescriptionHandler');
- }
- return hsh.localMediaStream;
- }
- });
- /**
- * The remote media stream. Undefined if call not answered.
- * @param session - Session to get the media stream from.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "getRemoteMediaStream", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- var hsh = session.sessionDescriptionHandler;
- if (!hsh) {
- return undefined;
- }
- if (!(hsh instanceof sip_js.Web.SessionDescriptionHandler)) {
- throw new Error('Session description handler not instance of web SessionDescriptionHandler');
- }
- return hsh.remoteMediaStream;
- }
- });
- /**
- * The local audio track, if available.
- * @param session - Session to get track from.
- * @deprecated Use localMediaStream and get track from the stream.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "getLocalAudioTrack", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- var _a;
- return (_a = this.getLocalMediaStream(session)) === null || _a === void 0 ? void 0 : _a.getTracks().find(function (track) {
- return track.kind === 'audio';
- });
- }
- });
- /**
- * The local video track, if available.
- * @param session - Session to get track from.
- * @deprecated Use localMediaStream and get track from the stream.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "getLocalVideoTrack", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- var _a;
- return (_a = this.getLocalMediaStream(session)) === null || _a === void 0 ? void 0 : _a.getTracks().find(function (track) {
- return track.kind === 'video';
- });
- }
- });
- /**
- * The remote audio track, if available.
- * @param session - Session to get track from.
- * @deprecated Use remoteMediaStream and get track from the stream.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "getRemoteAudioTrack", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- var _a;
- return (_a = this.getRemoteMediaStream(session)) === null || _a === void 0 ? void 0 : _a.getTracks().find(function (track) {
- return track.kind === 'audio';
- });
- }
- });
- /**
- * The remote video track, if available.
- * @param session - Session to get track from.
- * @deprecated Use remoteMediaStream and get track from the stream.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "getRemoteVideoTrack", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- var _a;
- return (_a = this.getRemoteMediaStream(session)) === null || _a === void 0 ? void 0 : _a.getTracks().find(function (track) {
- return track.kind === 'video';
- });
- }
- });
- /**
- * Connect.
- * @remarks
- * If not started, starts the UserAgent connecting the WebSocket Transport.
- * Otherwise reconnects the UserAgent's WebSocket Transport.
- * Attempts will be made to reconnect as needed.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "connect", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- this.logger.log("Connecting UserAgent...");
- this.shouldBeConnected = true;
- if (this.userAgent.state !== sip_js.UserAgentState.Started) {
- return [2 /*return*/, this.userAgent.start()];
- }
- return [2 /*return*/, this.userAgent.reconnect()];
- });
- });
- }
- });
- /**
- * Disconnect.
- * @remarks
- * If not stopped, stops the UserAgent disconnecting the WebSocket Transport.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "disconnect", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- this.logger.log("Disconnecting UserAgent...");
- if (this.userAgent.state === sip_js.UserAgentState.Stopped) {
- return [2 /*return*/, Promise.resolve()];
- }
- this.shouldBeConnected = false;
- this.shouldBeRegistered = false;
- this.registerer = undefined;
- return [2 /*return*/, this.userAgent.stop()];
- });
- });
- }
- });
- /**
- * Return true if transport is connected.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "isConnected", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- return this.userAgent.isConnected();
- }
- });
- /**
- * Start receiving incoming calls.
- * @remarks
- * Send a REGISTER request for the UserAgent's AOR.
- * Resolves when the REGISTER request is sent, otherwise rejects.
- * Attempts will be made to re-register as needed.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "register", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (registererRegisterOptions) {
- return __awaiter(this, void 0, void 0, function () {
- var _this = this;
- return __generator(this, function (_a) {
- this.logger.log("Registering UserAgent...");
- this.shouldBeRegistered = true;
- if (registererRegisterOptions !== undefined) {
- this.registererRegisterOptions = __assign({}, registererRegisterOptions);
- }
- if (!this.registerer) {
- this.registerer = new sip_js.Registerer(this.userAgent, this.registererOptions);
- this.registerer.stateChange.addListener(function (state) {
- switch (state) {
- case sip_js.RegistererState.Initial:
- break;
- case sip_js.RegistererState.Registered:
- if (_this.delegate && _this.delegate.onRegistered) {
- _this.delegate.onRegistered();
- }
- break;
- case sip_js.RegistererState.Unregistered:
- if (_this.delegate && _this.delegate.onUnregistered) {
- _this.delegate.onUnregistered();
- }
- // If we transition to an unregister state, attempt to get back to a registered state.
- if (_this.shouldBeRegistered) {
- _this.attemptRegistration();
- }
- break;
- case sip_js.RegistererState.Terminated:
- break;
- default:
- throw new Error('Unknown registerer state.');
- }
- });
- }
- return [2 /*return*/, this.attemptRegistration(true)];
- });
- });
- }
- });
- /**
- * Stop receiving incoming calls.
- * @remarks
- * Send an un-REGISTER request for the UserAgent's AOR.
- * Resolves when the un-REGISTER request is sent, otherwise rejects.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "unregister", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (registererUnregisterOptions) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- this.logger.log("Unregistering UserAgent...");
- this.shouldBeRegistered = false;
- if (!this.registerer) {
- this.logger.warn("No registerer to unregister.");
- return [2 /*return*/, Promise.resolve()];
- }
- return [2 /*return*/, this.registerer.unregister(registererUnregisterOptions).then(function () {
- return;
- })];
- });
- });
- }
- });
- /**
- * Make an outgoing call.
- * @remarks
- * Send an INVITE request to create a new Session.
- * Resolves when the INVITE request is sent, otherwise rejects.
- * Use `onCallAnswered` delegate method to determine if Session is established.
- * @param destination - The target destination to call. A SIP address to send the INVITE to.
- * @param inviterOptions - Optional options for Inviter constructor.
- * @param inviterInviteOptions - Optional options for Inviter.invite().
- */
- Object.defineProperty(SessionManagerPlus.prototype, "call", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (destination, inviterOptions, inviterInviteOptions) {
- return __awaiter(this, void 0, void 0, function () {
- var maxSessions, target, existingOnProgress_1, inviter;
- var _this = this;
- return __generator(this, function (_a) {
- this.logger.log("Beginning Session...");
- maxSessions = this.options.maxSimultaneousSessions;
- if (maxSessions !== 0 && this.managedSessions.length > maxSessions) {
- return [2 /*return*/, Promise.reject(new Error('Maximum number of sessions already exists.'))];
- }
- target = sip_js.UserAgent.makeURI(destination);
- if (!target) {
- return [2 /*return*/, Promise.reject(new Error("Failed to create a valid URI from \"".concat(destination, "\"")))];
- }
- // Use our configured constraints as InviterOptions if none provided
- if (!inviterOptions) {
- inviterOptions = {};
- }
- if (!inviterOptions.sessionDescriptionHandlerOptions) {
- inviterOptions.sessionDescriptionHandlerOptions = {};
- }
- if (!inviterOptions.sessionDescriptionHandlerOptions.constraints) {
- inviterOptions.sessionDescriptionHandlerOptions.constraints = this.constraints;
- }
- // If utilizing early media, add a handler to catch 183 Session Progress
- // messages and then to play the associated remote media (the early media).
- if (inviterOptions.earlyMedia) {
- inviterInviteOptions = inviterInviteOptions || {};
- inviterInviteOptions.requestDelegate = inviterInviteOptions.requestDelegate || {};
- existingOnProgress_1 = inviterInviteOptions.requestDelegate.onProgress;
- inviterInviteOptions.requestDelegate.onProgress = function (response) {
- if (response.message.statusCode === 183) {
- _this.setupRemoteMedia(inviter);
- }
- existingOnProgress_1 && existingOnProgress_1(response);
- };
- }
- // TODO: Any existing onSessionDescriptionHandler is getting clobbered here.
- // If we get a server reflexive candidate, stop waiting on ICE gathering to complete.
- // The candidate is a server reflexive candidate; the ip indicates an intermediary
- // address assigned by the STUN server to represent the candidate's peer anonymously.
- if (this.options.iceStopWaitingOnServerReflexive) {
- inviterOptions.delegate = inviterOptions.delegate || {};
- inviterOptions.delegate.onSessionDescriptionHandler = function (sessionDescriptionHandler) {
- if (!(sessionDescriptionHandler instanceof sip_js.Web.SessionDescriptionHandler)) {
- throw new Error('Session description handler not instance of SessionDescriptionHandler');
- }
- sessionDescriptionHandler.peerConnectionDelegate = {
- onicecandidate: function (event) {
- var _a;
- if (((_a = event.candidate) === null || _a === void 0 ? void 0 : _a.type) === 'srflx') {
- _this.logger.log("[".concat(inviter.id, "] Found srflx ICE candidate, stop waiting..."));
- // In sip.js > 0.20.1 this cast should be removed as iceGatheringComplete will be public
- var hsh = sessionDescriptionHandler;
- hsh.iceGatheringComplete();
- }
- }
- };
- };
- }
- inviter = new sip_js.Inviter(this.userAgent, target, inviterOptions);
- // Send INVITE
- return [2 /*return*/, this.sendInvite(inviter, inviterOptions, inviterInviteOptions).then(function () {
- return inviter;
- })];
- });
- });
- }
- });
- /**
- * Hangup a call.
- * @param session - Session to hangup.
- * @remarks
- * Send a BYE request, CANCEL request or reject response to end the current Session.
- * Resolves when the request/response is sent, otherwise rejects.
- * Use `onCallHangup` delegate method to determine if and when call is ended.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "hangup", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- this.logger.log("[".concat(session.id, "] Hangup..."));
- if (!this.sessionExists(session)) {
- return [2 /*return*/, Promise.reject(new Error('Session does not exist.'))];
- }
- return [2 /*return*/, this.terminate(session)];
- });
- });
- }
- });
- /**
- * Answer an incoming call.
- * @param session - Session to answer.
- * @remarks
- * Accept an incoming INVITE request creating a new Session.
- * Resolves with the response is sent, otherwise rejects.
- * Use `onCallAnswered` delegate method to determine if and when call is established.
- * @param invitationAcceptOptions - Optional options for Inviter.accept().
- */
- Object.defineProperty(SessionManagerPlus.prototype, "answer", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session, invitationAcceptOptions) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- this.logger.log("[".concat(session.id, "] Accepting Invitation..."));
- if (!this.sessionExists(session)) {
- return [2 /*return*/, Promise.reject(new Error('Session does not exist.'))];
- }
- if (!(session instanceof sip_js.Invitation)) {
- return [2 /*return*/, Promise.reject(new Error('Session not instance of Invitation.'))];
- }
- // Use our configured constraints as InvitationAcceptOptions if none provided
- if (!invitationAcceptOptions) {
- invitationAcceptOptions = {};
- }
- if (!invitationAcceptOptions.sessionDescriptionHandlerOptions) {
- invitationAcceptOptions.sessionDescriptionHandlerOptions = {};
- }
- if (!invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints) {
- invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints = this.constraints;
- }
- return [2 /*return*/, session.accept(invitationAcceptOptions)];
- });
- });
- }
- });
- /**
- * Decline an incoming call.
- * @param session - Session to decline.
- * @remarks
- * Reject an incoming INVITE request.
- * Resolves with the response is sent, otherwise rejects.
- * Use `onCallHangup` delegate method to determine if and when call is ended.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "decline", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- this.logger.log("[".concat(session.id, "] Rejecting Invitation..."));
- if (!this.sessionExists(session)) {
- return [2 /*return*/, Promise.reject(new Error('Session does not exist.'))];
- }
- if (!(session instanceof sip_js.Invitation)) {
- return [2 /*return*/, Promise.reject(new Error('Session not instance of Invitation.'))];
- }
- return [2 /*return*/, session.reject()];
- });
- });
- }
- });
- /**
- * Hold call
- * @param session - Session to hold.
- * @remarks
- * Send a re-INVITE with new offer indicating "hold".
- * Resolves when the re-INVITE request is sent, otherwise rejects.
- * Use `onCallHold` delegate method to determine if request is accepted or rejected.
- * See: https://tools.ietf.org/html/rfc6337
- */
- Object.defineProperty(SessionManagerPlus.prototype, "hold", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- this.logger.log("[".concat(session.id, "] Holding session..."));
- return [2 /*return*/, this.setHold(session, true)];
- });
- });
- }
- });
- /**
- * Unhold call.
- * @param session - Session to unhold.
- * @remarks
- * Send a re-INVITE with new offer indicating "unhold".
- * Resolves when the re-INVITE request is sent, otherwise rejects.
- * Use `onCallHold` delegate method to determine if request is accepted or rejected.
- * See: https://tools.ietf.org/html/rfc6337
- */
- Object.defineProperty(SessionManagerPlus.prototype, "unhold", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- this.logger.log("[".concat(session.id, "] Unholding session..."));
- return [2 /*return*/, this.setHold(session, false)];
- });
- });
- }
- });
- /**
- * Hold state.
- * @param session - Session to check.
- * @remarks
- * True if session is on hold.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "isHeld", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- var managedSession = this.sessionManaged(session);
- return managedSession ? managedSession.held : false;
- }
- });
- /**
- * Mute call.
- * @param session - Session to mute.
- * @remarks
- * Disable sender's media tracks.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "mute", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- this.logger.log("[".concat(session.id, "] Disabling media tracks..."));
- this.setMute(session, true);
- }
- });
- /**
- * Unmute call.
- * @param session - Session to unmute.
- * @remarks
- * Enable sender's media tracks.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "unmute", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- this.logger.log("[".concat(session.id, "] Enabling media tracks..."));
- this.setMute(session, false);
- }
- });
- /**
- * Mute state.
- * @param session - Session to check.
- * @remarks
- * True if sender's media track is disabled.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "isMuted", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- var managedSession = this.sessionManaged(session);
- return managedSession ? managedSession.muted : false;
- }
- });
- /**
- * Send DTMF.
- * @param session - Session to send on.
- * @remarks
- * Send an INFO request with content type application/dtmf-relay.
- * @param tone - Tone to send.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "sendDTMF", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session, tone) {
- return __awaiter(this, void 0, void 0, function () {
- var dtmf, duration, body, requestOptions;
- return __generator(this, function (_a) {
- this.logger.log("[".concat(session.id, "] Sending DTMF..."));
- // Validate tone
- if (!/^[0-9A-D#*,]$/.exec(tone)) {
- return [2 /*return*/, Promise.reject(new Error('Invalid DTMF tone.'))];
- }
- if (!this.sessionExists(session)) {
- return [2 /*return*/, Promise.reject(new Error('Session does not exist.'))];
- }
- this.logger.log("[".concat(session.id, "] Sending DTMF tone: ").concat(tone));
- if (this.options.sendDTMFUsingSessionDescriptionHandler) {
- if (!session.sessionDescriptionHandler) {
- return [2 /*return*/, Promise.reject(new Error('Session desciption handler undefined.'))];
- }
- if (!session.sessionDescriptionHandler.sendDtmf(tone)) {
- return [2 /*return*/, Promise.reject(new Error('Failed to send DTMF'))];
- }
- return [2 /*return*/, Promise.resolve()];
- } else {
- dtmf = tone;
- duration = 2000;
- body = {
- contentDisposition: 'render',
- contentType: 'application/dtmf-relay',
- content: 'Signal=' + dtmf + '\r\nDuration=' + duration
- };
- requestOptions = {
- body: body
- };
- return [2 /*return*/, session.info({
- requestOptions: requestOptions
- }).then(function () {
- return;
- })];
- }
- });
- });
- }
- });
- /**
- * Transfer.
- * @param session - Session with the transferee to transfer.
- * @param target - The referral target.
- * @remarks
- * If target is a Session this is an attended transfer completion (REFER with Replaces),
- * otherwise this is a blind transfer (REFER). Attempting an attended transfer
- * completion on a call that has not been answered will be rejected. To implement
- * an attended transfer with early completion, hangup the call with the target
- * and execute a blind transfer to the target.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "transfer", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session, target, options) {
- return __awaiter(this, void 0, void 0, function () {
- var uri;
- return __generator(this, function (_a) {
- this.logger.log("[".concat(session.id, "] Referring session..."));
- if (target instanceof sip_js.Session) {
- return [2 /*return*/, session.refer(target, options).then(function () {
- return;
- })];
- }
- uri = sip_js.UserAgent.makeURI(target);
- if (!uri) {
- return [2 /*return*/, Promise.reject(new Error("Failed to create a valid URI from \"".concat(target, "\"")))];
- }
- return [2 /*return*/, session.refer(uri, options).then(function () {
- return;
- })];
- });
- });
- }
- });
- /**
- * Send a message.
- * @remarks
- * Send a MESSAGE request.
- * @param destination - The target destination for the message. A SIP address to send the MESSAGE to.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "message", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (destination, message) {
- return __awaiter(this, void 0, void 0, function () {
- var target;
- return __generator(this, function (_a) {
- this.logger.log("Sending message...");
- target = sip_js.UserAgent.makeURI(destination);
- if (!target) {
- return [2 /*return*/, Promise.reject(new Error("Failed to create a valid URI from \"".concat(destination, "\"")))];
- }
- return [2 /*return*/, new sip_js.Messager(this.userAgent, target, message).message()];
- });
- });
- }
- });
- Object.defineProperty(SessionManagerPlus.prototype, "constraints", {
- /** Media constraints. */
- get: function () {
- var constraints = {
- audio: true,
- video: false
- }; // default to audio only calls
- if (this.options.media.constraints) {
- constraints = __assign({}, this.options.media.constraints);
- }
- return constraints;
- },
- enumerable: false,
- configurable: true
- });
- /**
- * Attempt reconnection up to `reconnectionAttempts` times.
- * @param reconnectionAttempt - Current attempt number.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "attemptReconnection", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (reconnectionAttempt) {
- var _this = this;
- var _a, _b;
- if (reconnectionAttempt === void 0) {
- reconnectionAttempt = 1;
- }
- var reconnectionAttempts = this.options.reconnectionAttempts;
- var reconnectionDelay = this.options.reconnectionDelay;
- if (!this.shouldBeConnected) {
- this.logger.log("Should not be connected currently");
- return; // If intentionally disconnected, don't reconnect.
- }
- if (this.attemptingReconnection) {
- this.logger.log("Reconnection attempt already in progress");
- }
- if (reconnectionAttempt > reconnectionAttempts) {
- this.logger.log("Reconnection maximum attempts reached");
- (_b = (_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onReconnectFailed) === null || _b === void 0 ? void 0 : _b.call(_a);
- return;
- }
- if (reconnectionAttempt === 1) {
- this.logger.log("Reconnection attempt ".concat(reconnectionAttempt, " of ").concat(reconnectionAttempts, " - trying"));
- } else {
- this.logger.log("Reconnection attempt ".concat(reconnectionAttempt, " of ").concat(reconnectionAttempts, " - trying in ").concat(reconnectionDelay, " seconds"));
- }
- this.attemptingReconnection = true;
- setTimeout(function () {
- if (!_this.shouldBeConnected) {
- _this.logger.log("Reconnection attempt ".concat(reconnectionAttempt, " of ").concat(reconnectionAttempts, " - aborted"));
- _this.attemptingReconnection = false;
- return; // If intentionally disconnected, don't reconnect.
- }
- _this.userAgent.reconnect().then(function () {
- _this.logger.log("Reconnection attempt ".concat(reconnectionAttempt, " of ").concat(reconnectionAttempts, " - succeeded"));
- _this.attemptingReconnection = false;
- }).catch(function (error) {
- _this.logger.log("Reconnection attempt ".concat(reconnectionAttempt, " of ").concat(reconnectionAttempts, " - failed"));
- _this.logger.error(error.message);
- _this.attemptingReconnection = false;
- _this.attemptReconnection(++reconnectionAttempt);
- });
- }, reconnectionAttempt === 1 ? 0 : reconnectionDelay * 1000);
- }
- });
- /**
- * Register to receive calls.
- * @param withoutDelay - If true attempt immediately, otherwise wait `registrationRetryInterval`.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "attemptRegistration", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (withoutDelay) {
- var _this = this;
- if (withoutDelay === void 0) {
- withoutDelay = false;
- }
- this.logger.log("Registration attempt ".concat(withoutDelay ? 'without delay' : ''));
- if (!this.shouldBeRegistered) {
- this.logger.log("Should not be registered currently");
- return Promise.resolve();
- }
- // It only makes sense to have one attempt in progress at a time.
- // Perhaps we shall (or should) try once again.
- if (this.registrationAttemptTimeout !== undefined) {
- this.logger.log("Registration attempt already in progress");
- return Promise.resolve();
- }
- // Helper function to send the register request.
- var _register = function () {
- // If we do not have a registerer, it is not worth trying to register.
- if (!_this.registerer) {
- _this.logger.log("Registerer undefined");
- return Promise.resolve();
- }
- // If the WebSocket transport is not connected, it is not worth trying to register.
- // Perhpas we shall (or should) try once we are connected.
- if (!_this.isConnected()) {
- _this.logger.log("User agent not connected");
- return Promise.resolve();
- }
- // If the UserAgent is stopped, it is not worth trying to register.
- // Perhaps we shall (or should) try once the UserAgent is running.
- if (_this.userAgent.state === sip_js.UserAgentState.Stopped) {
- _this.logger.log("User agent stopped");
- return Promise.resolve();
- }
- // If no guard defined, we are good to proceed without any further ado.
- if (!_this.options.registerGuard) {
- return _this.registerer.register(_this.registererRegisterOptions).then(function () {
- return;
- });
- }
- // Otherwise check to make sure the guard does not want us halt.
- return _this.options.registerGuard().catch(function (error) {
- _this.logger.log("Register guard rejected will making registration attempt");
- throw error;
- }).then(function (halt) {
- if (halt || !_this.registerer) {
- return Promise.resolve();
- }
- return _this.registerer.register(_this.registererRegisterOptions).then(function () {
- return;
- });
- });
- };
- // Compute an amount of time in seconds to wait before sending another register request.
- // This is a small attempt to avoid DOS attacking our own backend in the event that a
- // relatively large number of clients sychonously keep retrying register reqeusts.
- // This is known to happen when the backend goes down for a period and all clients
- // are attempting to register again - the backend gets slammed with synced reqeusts.
- var computeRegistrationTimeout = function (lowerBound) {
- var upperBound = lowerBound * 2;
- return 1000 * (Math.random() * (upperBound - lowerBound) + lowerBound);
- };
- // Send register request after a delay
- return new Promise(function (resolve, reject) {
- _this.registrationAttemptTimeout = setTimeout(function () {
- _register().then(function () {
- _this.registrationAttemptTimeout = undefined;
- resolve();
- }).catch(function (error) {
- _this.registrationAttemptTimeout = undefined;
- if (error instanceof sip_js.RequestPendingError) {
- resolve();
- } else {
- reject(error);
- }
- });
- }, withoutDelay ? 0 : computeRegistrationTimeout(_this.options.registrationRetryInterval));
- });
- }
- });
- /** Helper function to remove media from html elements. */
- Object.defineProperty(SessionManagerPlus.prototype, "cleanupMedia", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- var managedSession = this.sessionManaged(session);
- if (!managedSession) {
- throw new Error('Managed session does not exist.');
- }
- if (managedSession.mediaLocal) {
- if (managedSession.mediaLocal.video) {
- managedSession.mediaLocal.video.srcObject = null;
- managedSession.mediaLocal.video.pause();
- }
- }
- if (managedSession.mediaRemote) {
- if (managedSession.mediaRemote.audio) {
- managedSession.mediaRemote.audio.srcObject = null;
- managedSession.mediaRemote.audio.pause();
- }
- if (managedSession.mediaRemote.video) {
- managedSession.mediaRemote.video.srcObject = null;
- managedSession.mediaRemote.video.pause();
- }
- }
- }
- });
- /** Helper function to enable/disable media tracks. */
- Object.defineProperty(SessionManagerPlus.prototype, "enableReceiverTracks", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session, enable) {
- if (!this.sessionExists(session)) {
- throw new Error('Session does not exist.');
- }
- var sessionDescriptionHandler = session.sessionDescriptionHandler;
- if (!(sessionDescriptionHandler instanceof sip_js.Web.SessionDescriptionHandler)) {
- throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");
- }
- sessionDescriptionHandler.enableReceiverTracks(enable);
- }
- });
- /** Helper function to enable/disable media tracks. */
- Object.defineProperty(SessionManagerPlus.prototype, "enableSenderTracks", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session, enable) {
- if (!this.sessionExists(session)) {
- throw new Error('Session does not exist.');
- }
- var sessionDescriptionHandler = session.sessionDescriptionHandler;
- if (!(sessionDescriptionHandler instanceof sip_js.Web.SessionDescriptionHandler)) {
- throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");
- }
- sessionDescriptionHandler.enableSenderTracks(enable);
- }
- });
- /**
- * Setup session delegate and state change handler.
- * @param session - Session to setup.
- * @param referralInviterOptions - Options for any Inviter created as result of a REFER.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "initSession", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session, referralInviterOptions) {
- var _this = this;
- // Add the session
- this.sessionAdd(session);
- // Call session created callback
- if (this.delegate && this.delegate.onCallCreated) {
- this.delegate.onCallCreated(session);
- }
- // Setup session state change handler
- session.stateChange.addListener(function (state) {
- _this.logger.log("[".concat(session.id, "] Session state changed to ").concat(state));
- switch (state) {
- case sip_js.SessionState.Initial:
- break;
- case sip_js.SessionState.Establishing:
- break;
- case sip_js.SessionState.Established:
- _this.setupLocalMedia(session);
- _this.setupRemoteMedia(session);
- if (_this.delegate && _this.delegate.onCallAnswered) {
- _this.delegate.onCallAnswered(session);
- }
- break;
- case sip_js.SessionState.Terminating:
- // fall through
- case sip_js.SessionState.Terminated:
- // This will already have executed if/when we fall
- // through from Terminating and thus the managed
- // session may already have been cleaned up.
- if (_this.sessionExists(session)) {
- _this.cleanupMedia(session);
- _this.sessionRemove(session);
- if (_this.delegate && _this.delegate.onCallHangup) {
- _this.delegate.onCallHangup(session);
- }
- }
- break;
- default:
- throw new Error('Unknown session state.');
- }
- });
- // TODO: Any existing onInfo or onRefer delegate gets clobbered here.
- // Setup delegate
- session.delegate = session.delegate || {};
- session.delegate.onInfo = function (info) {
- // As RFC 6086 states, sending DTMF via INFO is not standardized...
- //
- // Companies have been using INFO messages in order to transport
- // Dual-Tone Multi-Frequency (DTMF) tones. All mechanisms are
- // proprietary and have not been standardized.
- // https://tools.ietf.org/html/rfc6086#section-2
- //
- // It is however widely supported based on this draft:
- // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00
- var _a;
- // FIXME: TODO: We should reject correctly...
- //
- // If a UA receives an INFO request associated with an Info Package that
- // the UA has not indicated willingness to receive, the UA MUST send a
- // 469 (Bad Info Package) response (see Section 11.6), which contains a
- // Recv-Info header field with Info Packages for which the UA is willing
- // to receive INFO requests.
- // https://tools.ietf.org/html/rfc6086#section-4.2.2
- // No delegate
- if (((_a = _this.delegate) === null || _a === void 0 ? void 0 : _a.onCallDTMFReceived) === undefined) {
- info.reject();
- return;
- }
- // Invalid content type
- var contentType = info.request.getHeader('content-type');
- if (!contentType || !/^application\/dtmf-relay/i.exec(contentType)) {
- info.reject();
- return;
- }
- // Invalid body
- var body = info.request.body.split('\r\n', 2);
- if (body.length !== 2) {
- info.reject();
- return;
- }
- // Invalid tone
- var tone;
- var toneRegExp = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;
- if (body[0] !== undefined && toneRegExp.test(body[0])) {
- tone = body[0].replace(toneRegExp, '$2');
- }
- if (!tone) {
- info.reject();
- return;
- }
- // Invalid duration
- var duration;
- var durationRegExp = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;
- if (body[1] !== undefined && durationRegExp.test(body[1])) {
- duration = parseInt(body[1].replace(durationRegExp, '$2'), 10);
- }
- if (!duration) {
- info.reject();
- return;
- }
- info.accept().then(function () {
- if (_this.delegate && _this.delegate.onCallDTMFReceived) {
- if (!tone || !duration) {
- throw new Error('Tone or duration undefined.');
- }
- _this.delegate.onCallDTMFReceived(session, tone, duration);
- }
- }).catch(function (error) {
- _this.logger.error(error.message);
- });
- };
- session.delegate.onRefer = function (referral) {
- referral.accept().then(function () {
- return _this.sendInvite(referral.makeInviter(referralInviterOptions), referralInviterOptions);
- }).catch(function (error) {
- _this.logger.error(error.message);
- });
- };
- }
- });
- /**
- * Periodically send OPTIONS pings and disconnect when a ping fails.
- * @param requestURI - Request URI to target
- * @param fromURI - From URI
- * @param toURI - To URI
- */
- Object.defineProperty(SessionManagerPlus.prototype, "optionsPingRun", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (requestURI, fromURI, toURI) {
- var _this = this;
- // Guard against nvalid interval
- if (this.options.optionsPingInterval < 1) {
- throw new Error('Invalid options ping interval.');
- }
- // Guard against sending a ping when there is one outstanading
- if (this.optionsPingRunning) {
- return;
- }
- this.optionsPingRunning = true;
- // Setup next ping to run in future
- this.optionsPingTimeout = setTimeout(function () {
- _this.optionsPingTimeout = undefined;
- // If ping succeeds...
- var onPingSuccess = function () {
- // record success or failure
- _this.optionsPingFailure = false;
- // if we are still running, queue up the next ping
- if (_this.optionsPingRunning) {
- _this.optionsPingRunning = false;
- _this.optionsPingRun(requestURI, fromURI, toURI);
- }
- };
- // If ping fails...
- var onPingFailure = function () {
- _this.logger.error('OPTIONS ping failed');
- // record success or failure
- _this.optionsPingFailure = true;
- // stop running
- _this.optionsPingRunning = false;
- // disconnect the transport
- _this.userAgent.transport.disconnect().catch(function (error) {
- return _this.logger.error(error);
- });
- };
- // Create an OPTIONS request message
- var core = _this.userAgent.userAgentCore;
- var message = core.makeOutgoingRequestMessage('OPTIONS', requestURI, fromURI, toURI, {});
- // Send the request message
- _this.optionsPingRequest = core.request(message, {
- onAccept: function () {
- _this.optionsPingRequest = undefined;
- onPingSuccess();
- },
- onReject: function (response) {
- _this.optionsPingRequest = undefined;
- // Ping fails on following responses...
- // - 408 Request Timeout (no response was received)
- // - 503 Service Unavailable (a transport layer error occured)
- if (response.message.statusCode === 408 || response.message.statusCode === 503) {
- onPingFailure();
- } else {
- onPingSuccess();
- }
- }
- });
- }, this.options.optionsPingInterval * 1000);
- }
- });
- /**
- * Start sending OPTIONS pings.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "optionsPingStart", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- this.logger.log("OPTIONS pings started");
- // Create the URIs needed to send OPTIONS pings
- var requestURI, fromURI, toURI;
- if (this.options.optionsPingRequestURI) {
- // Use whatever specific RURI is provided.
- requestURI = sip_js.UserAgent.makeURI(this.options.optionsPingRequestURI);
- if (!requestURI) {
- throw new Error('Failed to create Request URI.');
- }
- // Use the user agent's contact URI for From and To URIs
- fromURI = this.userAgent.contact.uri.clone();
- toURI = this.userAgent.contact.uri.clone();
- } else if (this.options.aor) {
- // Otherwise use the AOR provided to target the assocated registrar server.
- var uri = sip_js.UserAgent.makeURI(this.options.aor);
- if (!uri) {
- throw new Error('Failed to create URI.');
- }
- requestURI = uri.clone();
- requestURI.user = undefined; // target the registrar server
- fromURI = uri.clone();
- toURI = uri.clone();
- } else {
- 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. ');
- return;
- }
- // Send the OPTIONS pings
- this.optionsPingRun(requestURI, fromURI, toURI);
- }
- });
- /**
- * Stop sending OPTIONS pings.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "optionsPingStop", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- this.logger.log("OPTIONS pings stopped");
- this.optionsPingRunning = false;
- this.optionsPingFailure = false;
- if (this.optionsPingRequest) {
- this.optionsPingRequest.dispose();
- this.optionsPingRequest = undefined;
- }
- if (this.optionsPingTimeout) {
- clearTimeout(this.optionsPingTimeout);
- this.optionsPingTimeout = undefined;
- }
- }
- });
- /** Helper function to init send then send invite. */
- Object.defineProperty(SessionManagerPlus.prototype, "sendInvite", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (inviter, inviterOptions, inviterInviteOptions) {
- return __awaiter(this, void 0, void 0, function () {
- var _this = this;
- return __generator(this, function (_a) {
- // Initialize our session
- this.initSession(inviter, inviterOptions);
- // Send the INVITE
- return [2 /*return*/, inviter.invite(inviterInviteOptions).then(function () {
- _this.logger.log("[".concat(inviter.id, "] Sent INVITE"));
- })];
- });
- });
- }
- });
- Object.defineProperty(SessionManagerPlus.prototype, "managedSessionFactory", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (_sessionManagerPlus, session) {
- return {
- session: session,
- held: false,
- muted: false
- };
- }
- });
- /** Helper function to add a session to the ones we are managing. */
- Object.defineProperty(SessionManagerPlus.prototype, "sessionAdd", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- var managedSession = this.managedSessionFactory(this, session);
- this.managedSessions.push(managedSession);
- }
- });
- /** Helper function to check if the session is one we are managing. */
- Object.defineProperty(SessionManagerPlus.prototype, "sessionExists", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- return this.sessionManaged(session) !== undefined;
- }
- });
- /** Helper function to check if the session is one we are managing. */
- Object.defineProperty(SessionManagerPlus.prototype, "sessionManaged", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- return this.managedSessions.find(function (el) {
- return el.session.id === session.id;
- });
- }
- });
- /** Helper function to remoce a session from the ones we are managing. */
- Object.defineProperty(SessionManagerPlus.prototype, "sessionRemove", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- this.managedSessions = this.managedSessions.filter(function (el) {
- return el.session.id !== session.id;
- });
- }
- });
- /**
- * Puts Session on hold.
- * @param session - The session to set.
- * @param hold - Hold on if true, off if false.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "setHold", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session, hold) {
- return __awaiter(this, void 0, void 0, function () {
- var sessionDescriptionHandler, options, sessionDescriptionHandlerOptions, managedSession;
- var _this = this;
- return __generator(this, function (_a) {
- if (!this.sessionExists(session)) {
- return [2 /*return*/, Promise.reject(new Error('Session does not exist.'))];
- }
- // Just resolve if we are already in correct state
- if (this.isHeld(session) === hold) {
- return [2 /*return*/, Promise.resolve()];
- }
- sessionDescriptionHandler = session.sessionDescriptionHandler;
- if (!(sessionDescriptionHandler instanceof sip_js.Web.SessionDescriptionHandler)) {
- throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");
- }
- options = {
- requestDelegate: {
- onAccept: function () {
- var managedSession = _this.sessionManaged(session);
- if (managedSession !== undefined) {
- managedSession.held = hold;
- _this.enableReceiverTracks(session, !managedSession.held);
- _this.enableSenderTracks(session, !managedSession.held && !managedSession.muted);
- if (_this.delegate && _this.delegate.onCallHold) {
- _this.delegate.onCallHold(session, managedSession.held);
- }
- }
- },
- onReject: function () {
- _this.logger.warn("[".concat(session.id, "] Re-invite request was rejected"));
- var managedSession = _this.sessionManaged(session);
- if (managedSession !== undefined) {
- managedSession.held = !hold; // this was preemptively set so undo on failure
- _this.enableReceiverTracks(session, !managedSession.held);
- _this.enableSenderTracks(session, !managedSession.held && !managedSession.muted);
- if (_this.delegate && _this.delegate.onCallHold) {
- _this.delegate.onCallHold(session, managedSession.held);
- }
- }
- }
- }
- };
- sessionDescriptionHandlerOptions = session.sessionDescriptionHandlerOptionsReInvite;
- sessionDescriptionHandlerOptions.hold = hold;
- session.sessionDescriptionHandlerOptionsReInvite = sessionDescriptionHandlerOptions;
- managedSession = this.sessionManaged(session);
- if (!managedSession) {
- throw new Error('Managed session is undefiend.');
- }
- managedSession.held = hold;
- // Send re-INVITE
- return [2 /*return*/, session.invite(options).then(function () {
- // Preemptively enable/disable tracks
- var managedSession = _this.sessionManaged(session);
- if (managedSession !== undefined) {
- _this.enableReceiverTracks(session, !managedSession.held);
- _this.enableSenderTracks(session, !managedSession.held && !managedSession.muted);
- }
- }).catch(function (error) {
- managedSession.held = !hold; // was preemptively set so undo on failure
- if (error instanceof sip_js.RequestPendingError) {
- _this.logger.error("[".concat(session.id, "] A hold request is already in progress."));
- }
- throw error;
- })];
- });
- });
- }
- });
- /**
- * Puts Session on mute.
- * @param session - The session to mute.
- * @param mute - Mute on if true, off if false.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "setMute", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session, mute) {
- if (!this.sessionExists(session)) {
- this.logger.warn("[".concat(session.id, "] A session is required to enabled/disable media tracks"));
- return;
- }
- if (session.state !== sip_js.SessionState.Established) {
- this.logger.warn("[".concat(session.id, "] An established session is required to enable/disable media tracks"));
- return;
- }
- var managedSession = this.sessionManaged(session);
- if (managedSession !== undefined) {
- managedSession.muted = mute;
- this.enableSenderTracks(session, !managedSession.held && !managedSession.muted);
- }
- }
- });
- /** Helper function to attach local media to html elements. */
- Object.defineProperty(SessionManagerPlus.prototype, "setupLocalMedia", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- var _this = this;
- var managedSession = this.sessionManaged(session);
- if (!managedSession) {
- throw new Error('Managed session does not exist.');
- }
- // Get the local media element, if any, from the and configuraiton options
- // and save the info with the managed session so we can clean it up later.
- var mediaLocal = typeof this.options.media.local === 'function' ? this.options.media.local(session) : this.options.media.local;
- managedSession.mediaLocal = mediaLocal;
- var mediaElement = mediaLocal === null || mediaLocal === void 0 ? void 0 : mediaLocal.video;
- if (mediaElement) {
- var localStream = this.getLocalMediaStream(session);
- if (!localStream) {
- throw new Error('Local media stream undefiend.');
- }
- mediaElement.srcObject = localStream;
- mediaElement.volume = 0;
- mediaElement.play().catch(function (error) {
- _this.logger.error("[".concat(session.id, "] Failed to play local media"));
- _this.logger.error(error.message);
- });
- }
- }
- });
- /** Helper function to attach remote media to html elements. */
- Object.defineProperty(SessionManagerPlus.prototype, "setupRemoteMedia", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- var _this = this;
- var managedSession = this.sessionManaged(session);
- if (!managedSession) {
- throw new Error('Managed session does not exist.');
- }
- // Get the remote media element, if any, from the and configuraiton options
- // and save the info with the managed session so we can clean it up later.
- var mediaRemote = typeof this.options.media.remote === 'function' ? this.options.media.remote(session) : this.options.media.remote;
- managedSession.mediaRemote = mediaRemote;
- var mediaElement = (mediaRemote === null || mediaRemote === void 0 ? void 0 : mediaRemote.video) || (mediaRemote === null || mediaRemote === void 0 ? void 0 : mediaRemote.audio);
- if (mediaElement) {
- var remoteStream = this.getRemoteMediaStream(session);
- if (!remoteStream) {
- throw new Error('Remote media stream undefiend.');
- }
- mediaElement.autoplay = true; // Safari hack, because you cannot call .play() from a non user action
- mediaElement.srcObject = remoteStream;
- mediaElement.play().catch(function (error) {
- _this.logger.error("[".concat(session.id, "] Failed to play remote media"));
- _this.logger.error(error.message);
- });
- remoteStream.onaddtrack = function () {
- _this.logger.log("Remote media onaddtrack");
- mediaElement.load(); // Safari hack, as it doesn't work otheriwse
- mediaElement.play().catch(function (error) {
- _this.logger.error("[".concat(session.id, "] Failed to play remote media"));
- _this.logger.error(error.message);
- });
- };
- }
- }
- });
- /**
- * End a session.
- * @param session - The session to terminate.
- * @remarks
- * Send a BYE request, CANCEL request or reject response to end the current Session.
- * Resolves when the request/response is sent, otherwise rejects.
- * Use `onCallHangup` delegate method to determine if and when Session is terminated.
- */
- Object.defineProperty(SessionManagerPlus.prototype, "terminate", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (session) {
- return __awaiter(this, void 0, void 0, function () {
- var _this = this;
- return __generator(this, function (_a) {
- this.logger.log("[".concat(session.id, "] Terminating..."));
- switch (session.state) {
- case sip_js.SessionState.Initial:
- if (session instanceof sip_js.Inviter) {
- return [2 /*return*/, session.cancel().then(function () {
- _this.logger.log("[".concat(session.id, "] Inviter never sent INVITE (canceled)"));
- })];
- } else if (session instanceof sip_js.Invitation) {
- return [2 /*return*/, session.reject().then(function () {
- _this.logger.log("[".concat(session.id, "] Invitation rejected (sent 480)"));
- })];
- } else {
- throw new Error('Unknown session type.');
- }
- case sip_js.SessionState.Establishing:
- if (session instanceof sip_js.Inviter) {
- return [2 /*return*/, session.cancel().then(function () {
- _this.logger.log("[".concat(session.id, "] Inviter canceled (sent CANCEL)"));
- })];
- } else if (session instanceof sip_js.Invitation) {
- return [2 /*return*/, session.reject().then(function () {
- _this.logger.log("[".concat(session.id, "] Invitation rejected (sent 480)"));
- })];
- } else {
- throw new Error('Unknown session type.');
- }
- case sip_js.SessionState.Established:
- return [2 /*return*/, session.bye().then(function () {
- _this.logger.log("[".concat(session.id, "] Session ended (sent BYE)"));
- })];
- case sip_js.SessionState.Terminating:
- break;
- case sip_js.SessionState.Terminated:
- break;
- default:
- throw new Error('Unknown state');
- }
- this.logger.log("[".concat(session.id, "] Terminating in state ").concat(session.state, ", no action taken"));
- return [2 /*return*/, Promise.resolve()];
- });
- });
- }
- });
- return SessionManagerPlus;
- }();
- /**
- * A simple SIP user class.
- * @remarks
- * While this class is completely functional for simple use cases, it is not intended
- * to provide an interface which is suitable for most (must less all) applications.
- * While this class has many limitations (for example, it only handles a single concurrent session),
- * it is, however, intended to serve as a simple example of using the SIP.js API.
- * @public
- */
- var SimpleUserPlus = /** @class */function () {
- /**
- * Constructs a new instance of the `SimpleUser` class.
- * @param server - SIP WebSocket Server URL.
- * @param options - Options bucket. See {@link SimpleUserOptions} for details.
- */
- function SimpleUserPlus(server, options) {
- if (options === void 0) {
- options = {};
- }
- var _this = this;
- /** Delegate. */
- Object.defineProperty(this, "delegate", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "logger", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "options", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "session", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: undefined
- });
- Object.defineProperty(this, "sessionManager", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- // Delegate
- this.delegate = options.delegate;
- // Copy options
- this.options = __assign({}, options);
- // Session manager options
- var sessionManagerOptions = {
- aor: this.options.aor,
- delegate: {
- onCallAnswered: function () {
- var _a, _b;
- return (_b = (_a = _this.delegate) === null || _a === void 0 ? void 0 : _a.onCallAnswered) === null || _b === void 0 ? void 0 : _b.call(_a);
- },
- onCallCreated: function (session) {
- var _a, _b, _c, _d;
- _this.session = session;
- (_b = (_a = _this.delegate) === null || _a === void 0 ? void 0 : _a.onCallBegin) === null || _b === void 0 ? void 0 : _b.call(_a, session);
- (_d = (_c = _this.delegate) === null || _c === void 0 ? void 0 : _c.onCallCreated) === null || _d === void 0 ? void 0 : _d.call(_c);
- },
- onCallReceived: function (session) {
- var _a, _b, _c, _d;
- (_b = (_a = _this.delegate) === null || _a === void 0 ? void 0 : _a.onCallReceived) === null || _b === void 0 ? void 0 : _b.call(_a);
- (_d = (_c = _this.delegate) === null || _c === void 0 ? void 0 : _c.onInvite) === null || _d === void 0 ? void 0 : _d.call(_c, session);
- },
- onCallHangup: function () {
- var _a, _b;
- _this.session = undefined;
- ((_a = _this.delegate) === null || _a === void 0 ? void 0 : _a.onCallHangup) && ((_b = _this.delegate) === null || _b === void 0 ? void 0 : _b.onCallHangup());
- },
- onCallHold: function (_s, held) {
- var _a, _b;
- return (_b = (_a = _this.delegate) === null || _a === void 0 ? void 0 : _a.onCallHold) === null || _b === void 0 ? void 0 : _b.call(_a, held);
- },
- onCallDTMFReceived: function (_s, tone, dur) {
- var _a, _b;
- return (_b = (_a = _this.delegate) === null || _a === void 0 ? void 0 : _a.onCallDTMFReceived) === null || _b === void 0 ? void 0 : _b.call(_a, tone, dur);
- },
- onMessageReceived: function (message) {
- var _a, _b;
- 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);
- },
- onRegistered: function () {
- var _a, _b;
- return (_b = (_a = _this.delegate) === null || _a === void 0 ? void 0 : _a.onRegistered) === null || _b === void 0 ? void 0 : _b.call(_a);
- },
- onUnregistered: function () {
- var _a, _b;
- return (_b = (_a = _this.delegate) === null || _a === void 0 ? void 0 : _a.onUnregistered) === null || _b === void 0 ? void 0 : _b.call(_a);
- },
- onServerConnect: function () {
- var _a, _b;
- return (_b = (_a = _this.delegate) === null || _a === void 0 ? void 0 : _a.onServerConnect) === null || _b === void 0 ? void 0 : _b.call(_a);
- },
- onServerDisconnect: function () {
- var _a, _b;
- return (_b = (_a = _this.delegate) === null || _a === void 0 ? void 0 : _a.onServerDisconnect) === null || _b === void 0 ? void 0 : _b.call(_a);
- },
- onReconnectFailed: function () {
- var _a, _b;
- return (_b = (_a = _this.delegate) === null || _a === void 0 ? void 0 : _a.onReconnectFailed) === null || _b === void 0 ? void 0 : _b.call(_a);
- },
- onReconnectStart: function () {
- var _a, _b;
- return (_b = (_a = _this.delegate) === null || _a === void 0 ? void 0 : _a.onReconnectStart) === null || _b === void 0 ? void 0 : _b.call(_a);
- }
- },
- maxSimultaneousSessions: 1,
- media: this.options.media,
- optionsPingInterval: this.options.optionsPingInterval,
- optionsPingRequestURI: this.options.aor,
- reconnectionAttempts: this.options.reconnectionAttempts,
- reconnectionDelay: this.options.reconnectionDelay,
- registererOptions: this.options.registererOptions,
- sendDTMFUsingSessionDescriptionHandler: this.options.sendDTMFUsingSessionDescriptionHandler,
- userAgentOptions: this.options.userAgentOptions
- };
- this.sessionManager = new SessionManagerPlus(server, sessionManagerOptions);
- this.sessionManager.userAgent.stateChange.addListener(function (state) {
- var _a, _b;
- (_b = (_a = _this.delegate) === null || _a === void 0 ? void 0 : _a.onUserAgentStateChange) === null || _b === void 0 ? void 0 : _b.call(_a, state);
- });
- // Use the SIP.js logger
- this.logger = this.sessionManager.userAgent.getLogger('sip.SimpleUser');
- }
- Object.defineProperty(SimpleUserPlus.prototype, "id", {
- /**
- * Instance identifier.
- * @internal
- */
- get: function () {
- return this.options.userAgentOptions && this.options.userAgentOptions.displayName || 'Anonymous';
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(SimpleUserPlus.prototype, "localMediaStream", {
- /** The local media stream. Undefined if call not answered. */
- get: function () {
- return this.session && this.sessionManager.getLocalMediaStream(this.session);
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(SimpleUserPlus.prototype, "remoteMediaStream", {
- /** The remote media stream. Undefined if call not answered. */
- get: function () {
- return this.session && this.sessionManager.getRemoteMediaStream(this.session);
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(SimpleUserPlus.prototype, "localAudioTrack", {
- /**
- * The local audio track, if available.
- * @deprecated Use localMediaStream and get track from the stream.
- */
- get: function () {
- return this.session && this.sessionManager.getLocalAudioTrack(this.session);
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(SimpleUserPlus.prototype, "localVideoTrack", {
- /**
- * The local video track, if available.
- * @deprecated Use localMediaStream and get track from the stream.
- */
- get: function () {
- return this.session && this.sessionManager.getLocalVideoTrack(this.session);
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(SimpleUserPlus.prototype, "remoteAudioTrack", {
- /**
- * The remote audio track, if available.
- * @deprecated Use remoteMediaStream and get track from the stream.
- */
- get: function () {
- return this.session && this.sessionManager.getRemoteAudioTrack(this.session);
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(SimpleUserPlus.prototype, "remoteVideoTrack", {
- /**
- * The remote video track, if available.
- * @deprecated Use remoteMediaStream and get track from the stream.
- */
- get: function () {
- return this.session && this.sessionManager.getRemoteVideoTrack(this.session);
- },
- enumerable: false,
- configurable: true
- });
- /**
- * Connect.
- * @remarks
- * Start the UserAgent's WebSocket Transport.
- */
- Object.defineProperty(SimpleUserPlus.prototype, "connect", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- this.logger.log("[".concat(this.id, "] Connecting UserAgent..."));
- return this.sessionManager.connect();
- }
- });
- /**
- * Disconnect.
- * @remarks
- * Stop the UserAgent's WebSocket Transport.
- */
- Object.defineProperty(SimpleUserPlus.prototype, "disconnect", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- this.logger.log("[".concat(this.id, "] Disconnecting UserAgent..."));
- return this.sessionManager.disconnect();
- }
- });
- /**
- * Return true if connected.
- */
- Object.defineProperty(SimpleUserPlus.prototype, "isConnected", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- return this.sessionManager.isConnected();
- }
- });
- /**
- * Start receiving incoming calls.
- * @remarks
- * Send a REGISTER request for the UserAgent's AOR.
- * Resolves when the REGISTER request is sent, otherwise rejects.
- */
- Object.defineProperty(SimpleUserPlus.prototype, "register", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (registererRegisterOptions) {
- this.logger.log("[".concat(this.id, "] Registering UserAgent..."));
- return this.sessionManager.register(registererRegisterOptions);
- }
- });
- /**
- * Stop receiving incoming calls.
- * @remarks
- * Send an un-REGISTER request for the UserAgent's AOR.
- * Resolves when the un-REGISTER request is sent, otherwise rejects.
- */
- Object.defineProperty(SimpleUserPlus.prototype, "unregister", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (registererUnregisterOptions) {
- this.logger.log("[".concat(this.id, "] Unregistering UserAgent..."));
- return this.sessionManager.unregister(registererUnregisterOptions);
- }
- });
- /**
- * Make an outgoing call.
- * @remarks
- * Send an INVITE request to create a new Session.
- * Resolves when the INVITE request is sent, otherwise rejects.
- * Use `onCallAnswered` delegate method to determine if Session is established.
- * @param destination - The target destination to call. A SIP address to send the INVITE to.
- * @param inviterOptions - Optional options for Inviter constructor.
- * @param inviterInviteOptions - Optional options for Inviter.invite().
- */
- Object.defineProperty(SimpleUserPlus.prototype, "call", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (destination, inviterOptions, inviterInviteOptions) {
- this.logger.log("[".concat(this.id, "] Beginning Session..."));
- if (this.session) {
- return Promise.reject(new Error('Session already exists.'));
- }
- return this.sessionManager.call(destination, inviterOptions, inviterInviteOptions).then(function () {
- return;
- });
- }
- });
- /**
- * Hangup a call.
- * @remarks
- * Send a BYE request, CANCEL request or reject response to end the current Session.
- * Resolves when the request/response is sent, otherwise rejects.
- * Use `onCallHangup` delegate method to determine if and when call is ended.
- */
- Object.defineProperty(SimpleUserPlus.prototype, "hangup", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- var _this = this;
- this.logger.log("[".concat(this.id, "] Hangup..."));
- if (!this.session) {
- return Promise.reject(new Error('Session does not exist.'));
- }
- return this.sessionManager.hangup(this.session).then(function () {
- _this.session = undefined;
- });
- }
- });
- /**
- * Answer an incoming call.
- * @remarks
- * Accept an incoming INVITE request creating a new Session.
- * Resolves with the response is sent, otherwise rejects.
- * Use `onCallAnswered` delegate method to determine if and when call is established.
- * @param invitationAcceptOptions - Optional options for Inviter.accept().
- */
- Object.defineProperty(SimpleUserPlus.prototype, "answer", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (invitationAcceptOptions) {
- this.logger.log("[".concat(this.id, "] Accepting Invitation..."));
- if (!this.session) {
- return Promise.reject(new Error('Session does not exist.'));
- }
- return this.sessionManager.answer(this.session, invitationAcceptOptions);
- }
- });
- /**
- * Decline an incoming call.
- * @remarks
- * Reject an incoming INVITE request.
- * Resolves with the response is sent, otherwise rejects.
- * Use `onCallHangup` delegate method to determine if and when call is ended.
- */
- Object.defineProperty(SimpleUserPlus.prototype, "decline", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- this.logger.log("[".concat(this.id, "] rejecting Invitation..."));
- if (!this.session) {
- return Promise.reject(new Error('Session does not exist.'));
- }
- return this.sessionManager.decline(this.session);
- }
- });
- /**
- * Hold call
- * @remarks
- * Send a re-INVITE with new offer indicating "hold".
- * Resolves when the re-INVITE request is sent, otherwise rejects.
- * Use `onCallHold` delegate method to determine if request is accepted or rejected.
- * See: https://tools.ietf.org/html/rfc6337
- */
- Object.defineProperty(SimpleUserPlus.prototype, "hold", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- this.logger.log("[".concat(this.id, "] holding session..."));
- if (!this.session) {
- return Promise.reject(new Error('Session does not exist.'));
- }
- return this.sessionManager.hold(this.session);
- }
- });
- /**
- * Unhold call.
- * @remarks
- * Send a re-INVITE with new offer indicating "unhold".
- * Resolves when the re-INVITE request is sent, otherwise rejects.
- * Use `onCallHold` delegate method to determine if request is accepted or rejected.
- * See: https://tools.ietf.org/html/rfc6337
- */
- Object.defineProperty(SimpleUserPlus.prototype, "unhold", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- this.logger.log("[".concat(this.id, "] unholding session..."));
- if (!this.session) {
- return Promise.reject(new Error('Session does not exist.'));
- }
- return this.sessionManager.unhold(this.session);
- }
- });
- /**
- * Hold state.
- * @remarks
- * True if session is on hold.
- */
- Object.defineProperty(SimpleUserPlus.prototype, "isHeld", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- return this.session ? this.sessionManager.isHeld(this.session) : false;
- }
- });
- /**
- * Mute call.
- * @remarks
- * Disable sender's media tracks.
- */
- Object.defineProperty(SimpleUserPlus.prototype, "mute", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- this.logger.log("[".concat(this.id, "] disabling media tracks..."));
- return this.session && this.sessionManager.mute(this.session);
- }
- });
- /**
- * Unmute call.
- * @remarks
- * Enable sender's media tracks.
- */
- Object.defineProperty(SimpleUserPlus.prototype, "unmute", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- this.logger.log("[".concat(this.id, "] enabling media tracks..."));
- return this.session && this.sessionManager.unmute(this.session);
- }
- });
- /**
- * Mute state.
- * @remarks
- * True if sender's media track is disabled.
- */
- Object.defineProperty(SimpleUserPlus.prototype, "isMuted", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- return this.session ? this.sessionManager.isMuted(this.session) : false;
- }
- });
- /**
- * Send DTMF.
- * @remarks
- * Send an INFO request with content type application/dtmf-relay.
- * @param tone - Tone to send.
- */
- Object.defineProperty(SimpleUserPlus.prototype, "sendDTMF", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (tone) {
- this.logger.log("[".concat(this.id, "] sending DTMF..."));
- if (!this.session) {
- return Promise.reject(new Error('Session does not exist.'));
- }
- return this.sessionManager.sendDTMF(this.session, tone);
- }
- });
- /**
- * Send a message.
- * @remarks
- * Send a MESSAGE request.
- * @param destination - The target destination for the message. A SIP address to send the MESSAGE to.
- */
- Object.defineProperty(SimpleUserPlus.prototype, "message", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (destination, message) {
- this.logger.log("[".concat(this.id, "] sending message..."));
- return this.sessionManager.message(destination, message);
- }
- });
- return SimpleUserPlus;
- }();
- let has = Object.prototype.hasOwnProperty,
- prefix = '~';
- /**
- * Constructor to create a storage for our `EE` objects.
- * An `Events` instance is a plain object whose properties are event names.
- *
- * @constructor
- * @private
- */
- // eslint-disable-next-line @typescript-eslint/no-empty-function
- function Events() {}
- //
- // We try to not inherit from `Object.prototype`. In some engines creating an
- // instance in this way is faster than calling `Object.create(null)` directly.
- // If `Object.create(null)` is not supported we prefix the event names with a
- // character to make sure that the built-in object properties are not
- // overridden or used as an attack vector.
- //
- if (Object.create) {
- Events.prototype = Object.create(null);
- //
- // This hack is needed because the `__proto__` property is still inherited in
- // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
- //
- // eslint-disable-next-line no-const-assign
- if (!new Events().__proto__) prefix = false;
- }
- /**
- * Representation of a single event listener.
- *
- * @param {Function} fn The listener function.
- * @param {*} context The context to invoke the listener with.
- * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
- * @constructor
- * @private
- */
- function EE(fn, context, once) {
- this.fn = fn;
- this.context = context;
- this.once = once || false;
- }
- /**
- * Add a listener for a given event.
- *
- * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn The listener function.
- * @param {*} context The context to invoke the listener with.
- * @param {Boolean} once Specify if the listener is a one-time listener.
- * @returns {EventEmitter}
- * @private
- */
- function addListener(emitter, event, fn, context, once) {
- if (typeof fn !== 'function') {
- throw new TypeError('The listener must be a function');
- }
- const listener = new EE(fn, context || emitter, once),
- evt = prefix ? prefix + event : event;
- 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];
- return emitter;
- }
- /**
- * Clear event by name.
- *
- * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
- * @param {(String|Symbol)} evt The Event name.
- * @private
- */
- function clearEvent(emitter, evt) {
- if (--emitter._eventsCount === 0) emitter._events = new Events();else delete emitter._events[evt];
- }
- /**
- * Minimal `EventEmitter` interface that is molded against the Node.js
- * `EventEmitter` interface.
- *
- * @constructor
- * @public
- */
- function EventEmitter() {
- this._events = new Events();
- this._eventsCount = 0;
- }
- /**
- * Return an array listing the events for which the emitter has registered
- * listeners.
- *
- * @returns {Array}
- * @public
- */
- EventEmitter.prototype.eventNames = function eventNames() {
- let names = [],
- events,
- name;
- if (this._eventsCount === 0) return names;
- for (name in events = this._events) {
- if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
- }
- if (Object.getOwnPropertySymbols) {
- return names.concat(Object.getOwnPropertySymbols(events));
- }
- return names;
- };
- /**
- * Return the listeners registered for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @returns {Array} The registered listeners.
- * @public
- */
- EventEmitter.prototype.listeners = function listeners(event) {
- const evt = prefix ? prefix + event : event,
- handlers = this._events[evt];
- if (!handlers) return [];
- if (handlers.fn) return [handlers.fn];
- for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
- ee[i] = handlers[i].fn;
- }
- return ee;
- };
- /**
- * Return the number of listeners listening to a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @returns {Number} The number of listeners.
- * @public
- */
- EventEmitter.prototype.listenerCount = function listenerCount(event) {
- const evt = prefix ? prefix + event : event,
- listeners = this._events[evt];
- if (!listeners) return 0;
- if (listeners.fn) return 1;
- return listeners.length;
- };
- /**
- * Calls each of the listeners registered for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @returns {Boolean} `true` if the event had listeners, else `false`.
- * @public
- */
- EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
- const evt = prefix ? prefix + event : event;
- if (!this._events[evt]) return false;
- let listeners = this._events[evt],
- len = arguments.length,
- args,
- i;
- if (listeners.fn) {
- if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
- switch (len) {
- case 1:
- return listeners.fn.call(listeners.context), true;
- case 2:
- return listeners.fn.call(listeners.context, a1), true;
- case 3:
- return listeners.fn.call(listeners.context, a1, a2), true;
- case 4:
- return listeners.fn.call(listeners.context, a1, a2, a3), true;
- case 5:
- return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
- case 6:
- return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
- }
- for (i = 1, args = new Array(len - 1); i < len; i++) {
- args[i - 1] = arguments[i];
- }
- listeners.fn.apply(listeners.context, args);
- } else {
- let length = listeners.length,
- j;
- for (i = 0; i < length; i++) {
- if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
- switch (len) {
- case 1:
- listeners[i].fn.call(listeners[i].context);
- break;
- case 2:
- listeners[i].fn.call(listeners[i].context, a1);
- break;
- case 3:
- listeners[i].fn.call(listeners[i].context, a1, a2);
- break;
- case 4:
- listeners[i].fn.call(listeners[i].context, a1, a2, a3);
- break;
- default:
- if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) {
- args[j - 1] = arguments[j];
- }
- listeners[i].fn.apply(listeners[i].context, args);
- }
- }
- }
- return true;
- };
- /**
- * Add a listener for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn The listener function.
- * @param {*} [context=this] The context to invoke the listener with.
- * @returns {EventEmitter} `this`.
- * @public
- */
- EventEmitter.prototype.on = function on(event, fn, context) {
- return addListener(this, event, fn, context, false);
- };
- /**
- * Add a one-time listener for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn The listener function.
- * @param {*} [context=this] The context to invoke the listener with.
- * @returns {EventEmitter} `this`.
- * @public
- */
- EventEmitter.prototype.once = function once(event, fn, context) {
- return addListener(this, event, fn, context, true);
- };
- /**
- * Remove the listeners of a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn Only remove the listeners that match this function.
- * @param {*} context Only remove the listeners that have this context.
- * @param {Boolean} once Only remove one-time listeners.
- * @returns {EventEmitter} `this`.
- * @public
- */
- EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
- const evt = prefix ? prefix + event : event;
- if (!this._events[evt]) return this;
- if (!fn) {
- clearEvent(this, evt);
- return this;
- }
- const listeners = this._events[evt];
- if (listeners.fn) {
- if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
- clearEvent(this, evt);
- }
- } else {
- for (var i = 0, events = [], length = listeners.length; i < length; i++) {
- if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
- events.push(listeners[i]);
- }
- }
- //
- // Reset the array, or remove it completely if we have no more listeners.
- //
- if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;else clearEvent(this, evt);
- }
- return this;
- };
- /**
- * Remove all listeners, or those of the specified event.
- *
- * @param {(String|Symbol)} [event] The event name.
- * @returns {EventEmitter} `this`.
- * @public
- */
- EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
- let evt;
- if (event) {
- evt = prefix ? prefix + event : event;
- if (this._events[evt]) clearEvent(this, evt);
- } else {
- this._events = new Events();
- this._eventsCount = 0;
- }
- return this;
- };
- //
- // Alias methods names because people roll like that.
- //
- EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
- EventEmitter.prototype.addListener = EventEmitter.prototype.on;
- //
- // Expose the prefix.
- //
- EventEmitter.prefixed = prefix;
- //
- // Allow `EventEmitter` to be imported as module namespace.
- //
- EventEmitter.EventEmitter = EventEmitter;
- //
- // Expose the module.
- //
- if ('undefined' !== typeof module) {
- module.exports = EventEmitter;
- }
- /** 将小驼峰式字符串转换为小写下划线格式
- * @param {string}
- * @returns {string}
- */
- function upperCamelToLowerSnake(s) {
- s = s.replace(/\s/g, '');
- s = s.replace(/([A-Z])/g, '_$1');
- s = s.toLowerCase();
- s = s.replace(/^_/, '');
- s = s.replace(/_$/, '');
- return s;
- }
- /**
- * 获取时间戳字符串
- * @returns {string} 年-月-日 时:分:秒.毫秒
- */
- var getDateTime = function () {
- var timestamp = Date.now();
- var date = new Date(timestamp);
- var year = date.getFullYear();
- var month = String(date.getMonth() + 1).padStart(2, '0');
- var day = String(date.getDate()).padStart(2, '0');
- var hours = String(date.getHours()).padStart(2, '0');
- var minutes = String(date.getMinutes()).padStart(2, '0');
- var seconds = String(date.getSeconds()).padStart(2, '0');
- var milliseconds = String(date.getMilliseconds()).padStart(3, '0');
- var formattedDateTime = "".concat(year, "-").concat(month, "-").concat(day, " ").concat(hours, ":").concat(minutes, ":").concat(seconds, ".").concat(milliseconds);
- return formattedDateTime;
- };
- /** @enum LoggerLevels 日志输出等级 */
- exports.LoggerLevels = void 0;
- (function (LoggerLevels) {
- LoggerLevels[LoggerLevels["error"] = 0] = "error";
- LoggerLevels[LoggerLevels["warn"] = 1] = "warn";
- LoggerLevels[LoggerLevels["log"] = 2] = "log";
- LoggerLevels[LoggerLevels["debug"] = 3] = "debug";
- })(exports.LoggerLevels || (exports.LoggerLevels = {}));
- /** @class Logger 通用的日志模块 */
- var Logger = /** @class */function () {
- function Logger(level, category, label) {
- Object.defineProperty(this, "_level", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "category", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "label", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- this._level = level;
- this.category = category;
- this.label = label;
- }
- Object.defineProperty(Logger.prototype, "error", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (content) {
- this.genericLog(exports.LoggerLevels.error, content);
- }
- });
- Object.defineProperty(Logger.prototype, "warn", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (content) {
- this.genericLog(exports.LoggerLevels.warn, content);
- }
- });
- Object.defineProperty(Logger.prototype, "log", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (content) {
- this.genericLog(exports.LoggerLevels.log, content);
- }
- });
- Object.defineProperty(Logger.prototype, "debug", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (content) {
- this.genericLog(exports.LoggerLevels.debug, content);
- }
- });
- Object.defineProperty(Logger.prototype, "genericLog", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (levelToLog, content) {
- if (this._level >= levelToLog) {
- this.print(levelToLog, this.category, this.label, content);
- }
- }
- });
- Object.defineProperty(Logger.prototype, "print", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (levelToLog, category, label, content) {
- if (typeof content === 'string') {
- var prefix = [getDateTime()];
- if (label) {
- prefix.push(label);
- }
- content = prefix.concat(content).join(' | ');
- }
- switch (levelToLog) {
- case exports.LoggerLevels.error:
- console.error("%c".concat(category), 'color: blue;', content);
- break;
- case exports.LoggerLevels.warn:
- console.warn("%c".concat(category), 'color: blue;', content);
- break;
- case exports.LoggerLevels.log:
- console.log("%c".concat(category), 'color: blue;', content);
- break;
- case exports.LoggerLevels.debug:
- console.debug("%c".concat(category), 'color: blue;', content);
- break;
- }
- }
- });
- Object.defineProperty(Logger.prototype, "level", {
- get: function () {
- return this._level;
- },
- set: function (newLevel) {
- if (newLevel >= 0 && newLevel <= 3) {
- this._level = newLevel;
- } else if (newLevel > 3) {
- this._level = 3;
- // eslint-disable-next-line no-prototype-builtins
- } else if (exports.LoggerLevels.hasOwnProperty(newLevel)) {
- this._level = newLevel;
- } else {
- this.error("invalid 'level' parameter value: " + JSON.stringify(newLevel));
- }
- },
- enumerable: false,
- configurable: true
- });
- return Logger;
- }();
- /**
- * @enum {string} CTI 初始化场景
- * Manual: 手动外呼
- * Robot: 机器人外呼
- * Monitor: 监听
- * Predictive: 预测式外呼
- */
- exports.Scene = void 0;
- (function (Scene) {
- Scene["Manual"] = "manual";
- Scene["Robot"] = "robot";
- Scene["Monitor"] = "monitor";
- Scene["Predictive"] = "predictive";
- Scene["Wechat"] = "wechat";
- })(exports.Scene || (exports.Scene = {}));
- /**
- * @enum {string} CTI 监听场景
- * All: 不区分场景
- * Manual: 手动外呼
- * Robot: 机器人外呼
- * Predictive: 预测式外呼
- */
- exports.MonitorScene = void 0;
- (function (MonitorScene) {
- MonitorScene["All"] = "all";
- MonitorScene["Manual"] = "manual";
- MonitorScene["Robot"] = "robot";
- MonitorScene["Predictive"] = "predictive";
- })(exports.MonitorScene || (exports.MonitorScene = {}));
- /**
- * @interface {} 初始化 SD_CTI 需要的参数
- * loggerLevel: 日志等级
- * password: 临时的鉴权字符串,由业务方写死传进来
- * scene: CTI 初始化场景
- * monitorScene: 监听场景
- * env: 环境变量
- */
- /**
- * @enum {string} Socket 状态
- * Initial: 初始状态
- * Connecting: Socket 开始建立连接
- * Connected: Socket 建立连接成功
- * Ready: 向 IM 发送第一个上行 login 消息收到成功回调
- * Terminated: Socket 连接断开、各种 Socket 错误流转到本状态
- */
- exports.SocketStatus = void 0;
- (function (SocketStatus) {
- SocketStatus["Initial"] = "Initial";
- SocketStatus["Connecting"] = "Connecting";
- SocketStatus["Connected"] = "Connected";
- SocketStatus["Ready"] = "Ready";
- SocketStatus["ReTry"] = "ReTry";
- SocketStatus["Terminated"] = "Terminated";
- })(exports.SocketStatus || (exports.SocketStatus = {}));
- /**
- * @enum {string} SIP 状态
- * Initial: 初始状态
- * Started: SIP 的 User Agent 创建成功
- * Connecting: SIP 底层 Socket 传输 TransportState.Connecting
- * Connected: SIP 底层 Socket 传输 TransportState.Connected
- * Ready: SIP Registerer 监听注册状态 RegistererState.Registered
- * Terminated: SIP Socket 断开、注册失败等各种错误、主动断开连接流转到本状态
- */
- exports.SIPStatus = void 0;
- (function (SIPStatus) {
- SIPStatus["Initial"] = "Initial";
- SIPStatus["Started"] = "Started";
- SIPStatus["Connecting"] = "Connecting";
- SIPStatus["Connected"] = "Connected";
- SIPStatus["Ready"] = "Ready";
- SIPStatus["ReTry"] = "ReTry";
- SIPStatus["Terminated"] = "Terminated";
- })(exports.SIPStatus || (exports.SIPStatus = {}));
- /**
- * @enum {string} CTI 状态
- * Initial: 初始状态
- * Ready: SocketStatus Ready && SIPStatus Ready
- * Terminated: SocketStatus Terminated || SIPStatus Terminated || 正常调用 unInit 方法卸载
- */
- exports.CTIStatus = void 0;
- (function (CTIStatus) {
- CTIStatus["Initial"] = "Initial";
- CTIStatus["Ready"] = "Ready";
- CTIStatus["ReTry"] = "ReTry";
- CTIStatus["Terminated"] = "Terminated";
- })(exports.CTIStatus || (exports.CTIStatus = {}));
- /**
- * @enum {string} 通话状态
- * 为了防止人工外呼方法被二次调用引发预期以外的问题,增加此状态的流转
- * Started: 外呼已开始,此状态下不允许再次发起外呼
- * Stopped: 外呼已结束,此状态下可以再次发起外呼
- */
- exports.CallStatus = void 0;
- (function (CallStatus) {
- CallStatus["Started"] = "Started";
- CallStatus["Stopped"] = "Stopped";
- })(exports.CallStatus || (exports.CallStatus = {}));
- /**
- * @enum {string} Session 状态
- * CTI 目前只有 Invitation(接受会话)的场景,Inviter (主动发起会话)暂时没有
- */
- exports.SessionStatus = void 0;
- (function (SessionStatus) {
- /**
- * If `Inviter`, INVITE not sent yet.
- * If `Invitation`, SDK 收到 INVITE 通话请求,但尚未处理.
- */
- SessionStatus["Initial"] = "Initial";
- /**
- * If `Inviter`, sent INVITE and waiting for a final response.
- * If `Invitation`, received INVITE and attempting to send 200 final response (but has not sent it yet).
- */
- SessionStatus["Establishing"] = "Establishing";
- /**
- * If `Inviter`, sent INVITE and received 200 final response and sent ACK.
- * If `Invitation`, SDK 完成接受 INVITE 并发送 200 OK 确认接起,同时接通本地语音流.
- */
- SessionStatus["Established"] = "Established";
- /**
- * If `Inviter`, sent INVITE, sent CANCEL and now waiting for 487 final response to ACK (or 200 to ACK & BYE).
- * If `Invitation`, received INVITE, sent 200 final response and now waiting on ACK and upon receipt will attempt BYE
- * (as the protocol specification requires, before sending a BYE we must receive the ACK - so we are waiting).
- */
- SessionStatus["Terminating"] = "Terminating";
- /**
- * If `Inviter`, sent INVITE and received non-200 final response (or sent/received BYE after receiving 200).
- * If `Invitation`, SDK 收到 BYE 信令,发送 200 OK 挂断确认,会话结束.
- */
- SessionStatus["Terminated"] = "Terminated";
- })(exports.SessionStatus || (exports.SessionStatus = {}));
- /**
- * @enum {string} CTI 所有错误的分类
- * SdkTerminated: SDK 不可用错误,需要重新初始化
- * SdkError: SDK 状态可用,其他普通错误
- * ServerTerminated: 服务端不可用错误,需要重新初始化,透传服务端 code,msg
- * ServerError: 服务端可用,普通错误,透传服务端 code,msg
- */
- exports.CTIErrorType = void 0;
- (function (CTIErrorType) {
- CTIErrorType["SdkTerminated"] = "SdkTerminated";
- CTIErrorType["SdkError"] = "SdkError";
- CTIErrorType["ServerTerminated"] = "ServerTerminated";
- CTIErrorType["ServerError"] = "ServerError";
- })(exports.CTIErrorType || (exports.CTIErrorType = {}));
- /**
- * @enum {string} SdkTerminated 类型错误的 code 枚举
- * CTITerminated: SDK 状态不可用,CTIStatus 的状态为 Terminated
- * GetUserMedia: 获取坐席媒体权限失败
- * GetInitConfig: 调接口获取 CTI 初始化配置失败
- * SocketOnError: 监听 socket.io 的 error 事件
- * SocketOnConnectError: 监听 socket.io 的 connect_error 事件
- * SocketOnDisconnect: 监听 socket.io 的 disconnect 事件
- * SocketRepeatLogin: 多页面重复登录,IM 互踢事件
- * SIPInitUserAgent: SIP UserAgent 初始化时启动失败
- * SIPInitRegister: SIP Register 初始化时注册失败
- * SIPUserAgentStateStopped: 监听 SIP UserAgent stateChange 事件状态变更为 Stopped
- * SIPTransportStateDisconnected: 监听 SIP Transport StateChange 事件状态变更为 Disconnect
- * SIPRegistererStateTerminated: 监听 SIP Registerer StateChange 事件状态变更为 Terminated
- * SIPOnDisconnect: 监听 SIP OnDisconnect 事件收到异常退出 error
- * SIPInitTransport: SIP Transport 初始化时连接失败
- * SipHeartBeatErr: SIP发送心跳OPTIONS事件时收到异常结果
- * SIPUnRegistered: 注册SIP时失败
- * SocketOnReconnectFailed: Socket重连超过阈值且依然重连失败
- */
- exports.HskTerminatedCode = void 0;
- (function (HskTerminatedCode) {
- HskTerminatedCode["CTITerminated"] = "100001";
- HskTerminatedCode["GetUserMedia"] = "100002";
- HskTerminatedCode["GetInitConfig"] = "100003";
- HskTerminatedCode["SocketOnError"] = "110001";
- HskTerminatedCode["SocketOnConnectError"] = "110002";
- HskTerminatedCode["SocketOnDisconnect"] = "110003";
- HskTerminatedCode["SocketRepeatLogin"] = "110004";
- HskTerminatedCode["SocketOnReconnectFailed"] = "110007";
- HskTerminatedCode["SIPInitUserAgent"] = "120001";
- HskTerminatedCode["SIPInitRegister"] = "120002";
- HskTerminatedCode["SIPUserAgentStateStopped"] = "120003";
- HskTerminatedCode["SIPTransportStateDisconnected"] = "120004";
- HskTerminatedCode["SIPRegistererStateTerminated"] = "120005";
- HskTerminatedCode["SIPOnDisconnect"] = "120006";
- HskTerminatedCode["SIPInitTransport"] = "120007";
- HskTerminatedCode["SipHeartBeatErr"] = "120008";
- HskTerminatedCode["SIPUnRegistered"] = "120009";
- })(exports.HskTerminatedCode || (exports.HskTerminatedCode = {}));
- /**
- * @enum {string} SdkError 类型错误的 code 枚举
- * Answer: SIP accept 接起失败
- * Bye: SIP bye 挂断失败
- * InvitationCancel: SIP Invitation 会话请求被取消
- * AssignStream: 播放语音流失败
- * FetchError: 修饰器handleApiRes当进入到catch时上报此code
- */
- exports.SdkErrorCode = void 0;
- (function (SdkErrorCode) {
- SdkErrorCode["Answer"] = "200001";
- SdkErrorCode["Bye"] = "200002";
- SdkErrorCode["InvitationCancel"] = "200003";
- SdkErrorCode["AssignStream"] = "200004";
- SdkErrorCode["FetchError"] = "200005";
- })(exports.SdkErrorCode || (exports.SdkErrorCode = {}));
- /**
- * @enum {string} CTI 事件推送
- * OnCtiError: CTI 错误事件,含前后端所有错误,SDK 推送
- * OnSessionStatusChange: 坐席侧 SIP 会话状态变更事件,SDK 推送
- * OnInitalSuccess: CTI 初始化成功事件,SDK 推送
- * OnAgentWorkReport: 坐席&用户状态变更事件,Server 推送
- * OnRingStart: 手动外呼用户未接听时,开始播放回铃音,Server 推送
- * OnRingEnd: 手动外呼用户未接听时,播放回铃音结束,Server 推送
- * OnAgentReport: 坐席状态变更事件,Server 推送
- * OnCallReportInfo: 通话时长及通话次数等信息,Server 推送
- * OnDetectedTone: 服务端收到音频信号后推送
- */
- exports.CTIEvent = void 0;
- (function (CTIEvent) {
- CTIEvent["OnCtiError"] = "OnCtiError";
- CTIEvent["OnSessionStatusChange"] = "OnSessionStatusChange";
- CTIEvent["OnInitalSuccess"] = "OnInitalSuccess";
- CTIEvent["OnAgentWorkReport"] = "OnAgentWorkReport";
- CTIEvent["OnRingStart"] = "OnRingStart";
- CTIEvent["OnRingEnd"] = "OnRingEnd";
- CTIEvent["OnDetectedTone"] = "OnDetectedTone";
- CTIEvent["OnAgentReport"] = "OnAgentReport";
- CTIEvent["OnCallReportInfo"] = "OnCallReportInfo";
- // TODO: 后 7 个事件服务端未来不再推送时删掉
- CTIEvent["OnCallRing"] = "OnCallRing";
- CTIEvent["OnCallEnd"] = "OnCallEnd";
- CTIEvent["OnCallAnswer"] = "OnCallAnswer";
- CTIEvent["OnAgentGroupQuery"] = "OnAgentGroupQuery";
- CTIEvent["OnMethodResponseEvent"] = "OnMethodResponseEvent";
- CTIEvent["OnEventPrompt"] = "OnEventPrompt";
- CTIEvent["OnPrompt"] = "OnPrompt";
- })(exports.CTIEvent || (exports.CTIEvent = {}));
- var BaseOption;
- (function (BaseOption) {
- BaseOption["TrackParams"] = "trackParams";
- BaseOption["ENV"] = "env";
- BaseOption["LoggerLevel"] = "loggerLevel";
- })(BaseOption || (BaseOption = {}));
- var items = [[BaseOption.TrackParams, {}], [BaseOption.ENV, 'test'], [BaseOption.LoggerLevel, exports.LoggerLevels.debug]];
- var baseOption = new Map();
- var resetBaseOption = function () {
- items.forEach(function (i, v) {
- return baseOption.set(i, v);
- });
- };
- resetBaseOption();
- var setBaseOption = function (key, value, isInit) {
- if (isInit === void 0) {
- isInit = false;
- }
- if (!isInit && typeof value === 'object') {
- baseOption.set(key, __assign(__assign({}, baseOption.get(key)), value));
- } else {
- baseOption.set(key, value);
- }
- };
- var getBaseOption = function (key) {
- return baseOption.get(key);
- };
- var generateUUID = function () {
- return 'xxxxxxxxxxxx4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
- var r = Math.random() * 16 | 0;
- var v = c === 'x' ? r : r & 0x3 | 0x8;
- return v.toString(16);
- }).replace(/-/g, '');
- };
- var getClientId = function () {
- if (!window.HS_CTI_CLIENT_ID) {
- window.HS_CTI_CLIENT_ID = generateUUID();
- }
- return window.HS_CTI_CLIENT_ID;
- };
- /**
- * @enum {string} 本地提示音枚举
- * RingAudio: 来电振铃提示音
- * WaitAudio: 主动外呼等待音
- * ByeAudio: 挂断提示音
- */
- var AudioName;
- (function (AudioName) {
- AudioName["RingAudio"] = "_ringAudio";
- AudioName["WaitAudio"] = "_waitAudio";
- AudioName["ByeAudio"] = "_byeAudio";
- })(AudioName || (AudioName = {}));
- /**
- * @enum {string} 埋点上报的分类
- * FeSocket: Socket 类暴露的事件
- * FeSIP: SIP 相关事件
- * FeMethod: 业务调用 SDK 暴露的方法
- * FeAPI: SDK 调用后端的接口返回值
- * FeAPIError: SDK 调用后端的接口错误返回值
- * FeIMDown: 后端通过 IM 返回的常规事件
- * FeIMCmd: IM 返回的断开指令
- * FeMedia: SDK 媒体事件
- * FeStatu: SDK 是否状态流转事件
- * FeEmit: SDK 抛出的事件
- */
- var TrackSource;
- (function (TrackSource) {
- TrackSource["FeSocket"] = "fe-socket";
- TrackSource["FeSIP"] = "fe-sip";
- TrackSource["FeMethod"] = "fe-method";
- TrackSource["FeAPI"] = "fe-api";
- TrackSource["FeAPIError"] = "fe-api-error";
- TrackSource["FeIMDown"] = "fe-im-down";
- TrackSource["FeIMCmd"] = "fe-im-cmd";
- TrackSource["FeMedia"] = "fe-media";
- TrackSource["FeStatus"] = "fe-status";
- TrackSource["FeEmit"] = "fe-emit";
- })(TrackSource || (TrackSource = {}));
- var SocketEvent;
- (function (SocketEvent) {
- SocketEvent["SetSocketStatus"] = "SetSocketStatus";
- SocketEvent["SocketDownEvent"] = "SocketDownEvent";
- })(SocketEvent || (SocketEvent = {}));
- var ExceptMessage;
- (function (ExceptMessage) {
- ExceptMessage["CommonNetworkErrorMsg"] = "\u5BF9\u4E0D\u8D77\uFF0C\u7F51\u7EDC\u72B6\u51B5\u6682\u65F6\u4E0D\u4F73\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\u3002";
- 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";
- ExceptMessage["ManualCallAnswerErrorMsg"] = "\u5F53\u524D\u7535\u8BDD\u672A\u63A5\u901A\uFF0C\u901A\u8BDD\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u91CD\u8BD5\u3002";
- 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";
- ExceptMessage["SipByeErrorMsg"] = "\u8BF7\u7A0D\u7B49\uFF0C\u6B63\u5728\u6302\u65AD\u3002";
- ExceptMessage["CTIRepeatLoginMsg"] = "\u5F53\u524D\u5750\u5E2D\u5DF2\u88AB\u5176\u4ED6\u7EC8\u7AEF\u66FF\u4EE3\u3002";
- })(ExceptMessage || (ExceptMessage = {}));
- var methodExceptMsgMap = {
- checkIn: ExceptMessage.CommonNetworkErrorMsg,
- checkOut: ExceptMessage.CommonNetworkErrorMsg,
- setIdle: ExceptMessage.CustomNetworkErrorMsg,
- setBusy: ExceptMessage.CommonNetworkErrorMsg,
- makeCall: ExceptMessage.CommonNetworkErrorMsg,
- answer: ExceptMessage.CommonNetworkErrorMsg,
- bye: ExceptMessage.CommonNetworkErrorMsg,
- loadAgentGroupData: ExceptMessage.CommonNetworkErrorMsg,
- listen: ExceptMessage.CommonNetworkErrorMsg,
- setActiveService: ExceptMessage.CustomNetworkErrorMsg
- };
- var baseRequireParams = ['agent_id', 'saas_id',
- // 'password',
- 'env', 'scene'];
- var monitorRequireParams = ['monitorScene'];
- var allRequiredParams = __spreadArray(__spreadArray([], baseRequireParams, true), monitorRequireParams, true);
- var HsSocket = /** @class */function (_super) {
- __extends(HsSocket, _super);
- function HsSocket(socketOptions) {
- var _this = _super.call(this) || this;
- Object.defineProperty(_this, "logger", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(_this, "socket", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** 初始化 socket 需要的参数 */
- Object.defineProperty(_this, "socketOptions", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** 心跳延迟时间 */
- Object.defineProperty(_this, "heartBeatDelay", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** 主动关闭链接时间 */
- Object.defineProperty(_this, "closeHeartBeatDelay", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** 心跳检测定时器 */
- Object.defineProperty(_this, "heartBeatTimer", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** 清空心跳检测定时器 */
- Object.defineProperty(_this, "closeHeartBeatTimer", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** 超时次数 */
- // private timeOutCount: number
- /** 最大超时次数限制 */
- Object.defineProperty(_this, "imRetryCount", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** 本次 socket 会话唯一 id */
- Object.defineProperty(_this, "sessionId", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** 页面关闭时 关闭 socket */
- window.addEventListener('onunload', _this.closeSocket);
- _this.logger = new Logger(socketOptions.loggerLevel, 'HsSocket');
- _this.socket = undefined;
- _this.heartBeatTimer = null;
- _this.closeHeartBeatTimer = null;
- // this.timeOutCount = 0
- _this.sessionId = '';
- _this.socketOptions = socketOptions;
- _this.heartBeatDelay = socketOptions.imHeartTime * 1000 || 3000;
- _this.closeHeartBeatDelay = socketOptions.imHeartTime * 1000 || 3000;
- _this.imRetryCount = socketOptions.imRetryCount || 10;
- return _this;
- }
- /** @public initSocket 初始化 Socket 连接 */
- Object.defineProperty(HsSocket.prototype, "initSocket", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- var _this = this;
- /** 如果有未断开的连接先断开 */
- this.closeSocket();
- // 设置状态为连接中
- this.emit(SocketEvent.SetSocketStatus, {
- status: exports.SocketStatus.Connecting
- });
- /** https://socket.io/docs/v2/client-api/#iourl */
- this.socket = io(this.socketOptions.imWsServer, {
- transports: ['websocket'],
- reconnectionAttempts: this.imRetryCount,
- reconnectionDelay: this.heartBeatDelay,
- reconnectionDelayMax: this.heartBeatDelay + 1000,
- timeout: this.heartBeatDelay,
- reconnection: true
- });
- /** https://socket.io/docs/v2/client-api/#event-error */
- this.socket.on('error', function (error) {
- _this.logger.error("socket_error | ".concat(JSON.stringify(error)));
- });
- /** https://socket.io/docs/v2/client-api/#event-connect_error-1 */
- this.socket.on('connect_error', function (error) {
- var errorData = "socket_connect_error | ".concat(JSON.stringify(error));
- _this.logger.warn(errorData);
- });
- this.socket.on('reconnecting', function (res) {
- _this.logger.error("socket_warn | socket_reconnecting | ".concat(res));
- _this.emit(SocketEvent.SetSocketStatus, {
- status: exports.SocketStatus.ReTry
- });
- });
- this.socket.on('reconnect', function (res) {
- _this.logger.error("socket_warn | socket_reconnect | ".concat(res));
- _this.emit(SocketEvent.SetSocketStatus, {
- status: exports.SocketStatus.Ready
- });
- });
- this.socket.on('reconnect_failed', function (error) {
- _this.logger.error("socket_warn | socket_reconnect_failed | ".concat(error));
- _this.emit(SocketEvent.SetSocketStatus, {
- status: exports.SocketStatus.Terminated,
- code: exports.HskTerminatedCode.SocketOnReconnectFailed,
- error: "".concat(error)
- });
- });
- /** https://socket.io/docs/v2/client-api/#event-connect */
- this.socket.on('connect', function () {
- _this.emit(SocketEvent.SetSocketStatus, {
- status: exports.SocketStatus.Connected
- });
- _this.socketLogin();
- });
- /** https://socket.io/docs/v2/client-api/#event-disconnect */
- this.socket.on('disconnect', function (reason) {
- var errorMessage = "socket_disconnect | ".concat(reason);
- _this.logger.warn(errorMessage);
- });
- /** 服务端下行事件 */
- this.socket.on('common_down_data', function (e) {
- console.log(e, 3434343434);
- if (e && JSON.parse(e) && JSON.parse(e).data) {
- _this.emit(SocketEvent.SocketDownEvent, {
- eventData: JSON.parse(JSON.parse(e).data)
- });
- }
- });
- /** 服务端下行指令 */
- this.socket.on('common_down_cmd', function (e) {
- var clientSessionId = JSON.parse(e).clientSessionId;
- console.log('dsdsdsdsdsds', clientSessionId);
- if (clientSessionId === _this.sessionId) {
- _this.logger.error("socket status | ".concat(exports.SocketStatus.Terminated, " | \u5750\u5E2D\u5728\u5176\u4ED6\u9875\u9762\u91CD\u65B0\u521D\u59CB\u5316\uFF0C\u672C\u9875\u9762\u88AB\u8E22\u51FA"));
- _this.emit(SocketEvent.SetSocketStatus, {
- status: exports.SocketStatus.Terminated,
- code: exports.HskTerminatedCode.SocketRepeatLogin,
- error: '您已在其他页面签入,当前页面连接已断开'
- });
- }
- });
- }
- });
- /** @private socketLogin 客户端上行登录事件 */
- Object.defineProperty(HsSocket.prototype, "socketLogin", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- var _this = this;
- var data = {
- // appCode: this.socketOptions.appCode || '1111',
- // token: this.socketOptions.token || '1111',
- userId: this.socketOptions.agent_id
- };
- this.socket && this.socket.emit('login', data, function (sessionId) {
- console.log(sessionId, '测试一下');
- _this.emit(SocketEvent.SetSocketStatus, {
- status: exports.SocketStatus.Ready
- });
- setBaseOption(BaseOption.TrackParams, {
- socket_session_id: sessionId
- });
- _this.sessionId = sessionId;
- _this.startHeartbeat();
- });
- }
- });
- /** @public closeSocket 关闭 socket 连接 */
- Object.defineProperty(HsSocket.prototype, "closeSocket", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- if (this.socket) {
- this.socket.io.opts.reconnection = false;
- this.socket.close();
- // 清除之前的监听事件
- this.socket.removeAllListeners();
- }
- this.socket = undefined;
- this.sessionId = '';
- if (this.heartBeatTimer) {
- window.clearTimeout(this.heartBeatTimer);
- this.heartBeatTimer = null;
- }
- if (this.closeHeartBeatTimer) {
- window.clearTimeout(this.closeHeartBeatTimer);
- this.closeHeartBeatTimer = null;
- }
- }
- });
- /** @private startHeartbeat 开启心跳检测 */
- Object.defineProperty(HsSocket.prototype, "startHeartbeat", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- if (this.heartBeatTimer) {
- window.clearTimeout(this.heartBeatTimer);
- this.heartBeatTimer = null;
- }
- if (this.closeHeartBeatTimer) {
- window.clearTimeout(this.closeHeartBeatTimer);
- this.closeHeartBeatTimer = null;
- }
- this.socket && this.heartbeatEvent();
- }
- });
- /** @private heartbeatEvent websocket心跳检测 */
- Object.defineProperty(HsSocket.prototype, "heartbeatEvent", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- var _this = this;
- this.heartBeatTimer = setTimeout(function () {
- _this.socket && _this.sendHeartbeat();
- /** 如果心跳检测一直没回应,则进行重连 */
- _this.closeHeartBeatTimer = setTimeout(function () {
- _this.logger.warn('socket_heart_beat | 心跳超时,即将重新连接');
- _this.initSocket();
- }, _this.closeHeartBeatDelay);
- }, this.heartBeatDelay);
- }
- });
- /** @private sendHeartbeat 客户端上行心跳事件 */
- Object.defineProperty(HsSocket.prototype, "sendHeartbeat", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- var _this = this;
- this.socket && this.socket.emit('heartbeat', JSON.stringify(__assign({}, this.socketOptions)), function () {
- _this.startHeartbeat();
- });
- }
- });
- return HsSocket;
- }(EventEmitter);
- var apiLogger = new Logger(window.ctiLoggerLevel || getBaseOption(BaseOption.LoggerLevel), 'HsApi');
- var random16Hex = function () {
- return (0x10000 | Math.random() * 0x10000).toString(16).substr(1);
- };
- var random64Hex = function () {
- return random16Hex() + random16Hex() + random16Hex() + random16Hex();
- };
- function JPOST(_a) {
- var baseUrl = _a.baseUrl,
- url = _a.url,
- data = _a.data;
- return __awaiter(this, void 0, void 0, function () {
- var id, response;
- return __generator(this, function (_b) {
- switch (_b.label) {
- case 0:
- id = random64Hex();
- return [4 /*yield*/, fetch(baseUrl + url, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-B3-TraceId': id,
- 'X-B3-SpanId': id
- },
- body: JSON.stringify(data)
- })];
- case 1:
- response = _b.sent();
- if (!response.ok) {
- apiLogger.error("api response | ".concat(url, " | Request failed with status ").concat(response.status));
- }
- return [2 /*return*/, response.json()];
- }
- });
- });
- }
- var hsTrackJPOST = function (_a) {
- var baseUrl = _a.baseUrl,
- _b = _a.url,
- url = _b === void 0 ? '' : _b,
- data = _a.data;
- // eslint-disable-next-line no-async-promise-executor
- return new Promise(function (resolve, reject) {
- return __awaiter(void 0, void 0, void 0, function () {
- var res, code, msg, e_1;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- _a.trys.push([0, 2,, 3]);
- return [4 /*yield*/, JPOST({
- baseUrl: baseUrl,
- url: url,
- data: data
- })];
- case 1:
- res = _a.sent();
- code = res.code, msg = res.msg;
- console.log(msg);
- if (code === 0) {
- apiLogger.log("api response | ".concat(url, " | ").concat(JSON.stringify(res)));
- } else {
- apiLogger.error("api response | ".concat(url, " | ").concat(JSON.stringify(res)));
- }
- resolve(res);
- return [3 /*break*/, 3];
- case 2:
- e_1 = _a.sent();
- apiLogger.error("api response | ".concat(url, " | ").concat(JSON.stringify(e_1)));
- reject(e_1);
- return [3 /*break*/, 3];
- case 3:
- return [2 /*return*/];
- }
- });
- });
- });
- };
- // 获取初始化配置
- var baseUrl = 'http://192.168.100.159:8090';
- var getInitConf = function (data) {
- return hsTrackJPOST({
- baseUrl: baseUrl,
- url: '/open/agent/get-init-config',
- data: data
- });
- };
- // 坐席签入
- var agentCheckIn = function (data) {
- return hsTrackJPOST({
- baseUrl: baseUrl,
- url: '/open/agent/check-in',
- data: data
- });
- };
- // 坐席签出
- var agentCheckOut = function (data) {
- return hsTrackJPOST({
- baseUrl: baseUrl,
- url: '/open/agent/check-out',
- data: data
- });
- };
- // 坐席置闲
- var agentSetIdle = function (data) {
- return hsTrackJPOST({
- baseUrl: baseUrl,
- url: '/open/agent/idle',
- data: data
- });
- };
- // 坐席置忙
- var agentSetBusy = function (data) {
- return hsTrackJPOST({
- baseUrl: baseUrl,
- url: '/open/agent/busy',
- data: data
- });
- };
- // 获取坐席状态
- var getAgentStatus = function (data) {
- return hsTrackJPOST({
- baseUrl: baseUrl,
- url: '/open/agent/agent-state',
- data: data
- });
- };
- // 外呼
- var manualCall = function (data) {
- return hsTrackJPOST({
- baseUrl: baseUrl,
- url: '/open/agent/manual-call',
- data: data
- });
- };
- // 挂断
- var manualHang = function (data) {
- return hsTrackJPOST({
- baseUrl: baseUrl,
- url: '/open/agent/manual-hang',
- data: data
- });
- };
- // 发起监听
- var listen = function (data) {
- return hsTrackJPOST({
- baseUrl: baseUrl,
- url: '/open/agent/listen',
- data: data
- });
- };
- // 获取监控组成员信息
- var loadAgentGroupData = function (data) {
- return hsTrackJPOST({
- baseUrl: baseUrl,
- url: '/open/monitor/load-agent-group-data',
- data: data
- });
- };
- // 机器人外呼-签入人工组
- var setActiveServiceTask = function (data) {
- return hsTrackJPOST({
- baseUrl: baseUrl,
- url: '/open/human-service/member-active',
- data: data
- });
- };
- // 获取 cti 流程 ID
- var getCtiFlowId = function (data) {
- return hsTrackJPOST({
- baseUrl: baseUrl,
- url: '/open/num/generate',
- data: data
- });
- };
- /**
- * @function getServerErrorType 根据服务端返回的 code 生成错误类型
- * @param {number} code
- * @returns {CTIErrorType}
- */
- function getServerErrorType(code) {
- if (code >= 300001 && code <= 399999) return exports.CTIErrorType.ServerTerminated;else return exports.CTIErrorType.ServerError;
- }
- /** @function getUserMedia 获取媒体权限 */
- function getUserMedia() {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- return function (_target, _methodName, descriptor) {
- var originalMethod = descriptor.value;
- descriptor.value = function () {
- var _this = this;
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- if (navigator && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
- navigator.mediaDevices.getUserMedia({
- audio: true,
- video: false
- }).then(function () {
- _this.logger.debug('media | getUserMedia | 获取浏览器媒体权限成功');
- return originalMethod.apply(_this, args);
- }).catch(function (error) {
- _this.logger.error("media | getUserMedia | ".concat(error));
- _this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, {
- type: exports.CTIErrorType.SdkTerminated,
- code: exports.HskTerminatedCode.GetUserMedia,
- msg: error.name === 'NotAllowedError' ? '用户拒绝了获取麦克风权限!' : '获取麦克风权限失败',
- method: 'getUserMedia'
- }, {
- source: TrackSource.FeMedia,
- event_name: 'get_user_media_error',
- error: error.name
- });
- });
- } else {
- this.logger.error('media | getUserMedia | 浏览器版本过低,不支持获取媒体权限');
- this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, {
- type: exports.CTIErrorType.SdkTerminated,
- code: exports.HskTerminatedCode.GetUserMedia,
- msg: '浏览器版本过低,不支持获取媒体权限',
- method: 'getUserMedia'
- }, {
- source: TrackSource.FeMedia,
- event_name: 'get_user_media_not_support'
- });
- }
- };
- return descriptor;
- };
- }
- /**
- * @function checkCTIStatus 校验 cti 状态
- * @param {string} msg
- */
- function checkCTIStatus(msg) {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- return function (_target, methodName, descriptor) {
- var originalMethod = descriptor.value;
- descriptor.value = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- /** 调用 SDK method */
- this.logger.log("sdk method | ".concat(methodName, " | ").concat(msg));
- /** 校验 CTIStatus, 如果不是 Ready 状态,直接报错 */
- if (this.getCTIStatus !== exports.CTIStatus.Ready) {
- var errorData = {
- type: exports.CTIErrorType.SdkTerminated,
- code: exports.HskTerminatedCode.CTITerminated,
- msg: methodExceptMsgMap[methodName],
- method: methodName,
- terminated_source: this._terminatedStatusList
- };
- this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, errorData);
- return Promise.reject(errorData);
- }
- return originalMethod.apply(this, args);
- };
- return descriptor;
- };
- }
- /** @function handleApiRes 统一处理服务端接口返回值 */
- function handleApiRes() {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- return function (_target, methodName, descriptor) {
- var originalMethod = descriptor.value;
- descriptor.value = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- return __awaiter(this, void 0, void 0, function () {
- var res, code, msg, serverErrorType, errorData, error_1, errorData;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- _a.trys.push([0, 2,, 3]);
- return [4 /*yield*/, originalMethod.apply(this, args)];
- case 1:
- res = _a.sent();
- code = res.code, msg = res.msg;
- if (code !== 0) {
- serverErrorType = getServerErrorType(code);
- errorData = {
- type: serverErrorType,
- code: code,
- msg: msg,
- method: methodName
- };
- this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, errorData);
- if (serverErrorType === exports.CTIErrorType.ServerTerminated) {
- this.setCTIStatus(exports.CTIStatus.Terminated);
- }
- return [2 /*return*/, Promise.reject(errorData)];
- } else {
- return [2 /*return*/, Promise.resolve(res)];
- }
- case 2:
- error_1 = _a.sent();
- errorData = {
- type: 'fetch_error',
- code: exports.SdkErrorCode.FetchError,
- msg: JSON.stringify(error_1),
- method: methodName
- };
- this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, errorData);
- return [2 /*return*/, Promise.reject(errorData)];
- case 3:
- return [2 /*return*/];
- }
- });
- });
- };
- return descriptor;
- };
- }
- function validateParams() {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- return function (_target, _methodName, descriptor) {
- var originalMethod = descriptor.value;
- descriptor.value = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- var currentParams = args[0];
- var requireList = [];
- if (currentParams.scene === exports.Scene.Monitor) {
- requireList = allRequiredParams;
- } else {
- requireList = baseRequireParams;
- }
- requireList.forEach(function (param) {
- if (!currentParams[param]) {
- throw "\u53C2\u6570[".concat(param, "]\u4E3A\u5FC5\u586B\u53C2\u6570");
- }
- });
- return originalMethod.apply(this, args);
- };
- return descriptor;
- };
- }
- function generateUniqueId() {
- return 'id-' + Date.now() + '-' + Math.floor(Math.random() * 10000);
- }
- /**
- * 本地提示音
- * _ringAudio 机器人外呼/监听,等待接起提示音
- * _waitAudio 主动外呼,点击拨打时的等待音
- * _byeAudio 结束通话提示音
- */
- var audioList = {
- _ringAudio: 'http://static.fuxicarbon.com/hs-cti/ring.wav',
- _waitAudio: 'http://static.fuxicarbon.com/hs-cti/manual.wav',
- _byeAudio: 'http://static.fuxicarbon.com/hs-cti/bye.wav'
- };
- /** @class HsCTI 红杉外呼类 */
- var HsCTI = /** @class */function (_super) {
- __extends(HsCTI, _super);
- function HsCTI(hsCTIInitOptions) {
- var _this = this;
- var saas_id = hsCTIInitOptions.saas_id,
- agent_id = hsCTIInitOptions.agent_id,
- scene = hsCTIInitOptions.scene,
- env = hsCTIInitOptions.env,
- loggerLevel = hsCTIInitOptions.loggerLevel;
- _this = _super.call(this) || this;
- Object.defineProperty(_this, "logger", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(_this, "loggerLevel", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(_this, "scene", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(_this, "agent_id", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(_this, "saas_id", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** 接口返回的初始化配置 */
- Object.defineProperty(_this, "_initOptions", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** IM socket的实例 */
- Object.defineProperty(_this, "_socket", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** sip.js UA实例 */
- Object.defineProperty(_this, "_sipUserAgent", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(_this, "_callId", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(_this, "_ctiFlowIdList", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** 基本参数 */
- Object.defineProperty(_this, "_baseParams", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** 等待提示音播放器 */
- Object.defineProperty(_this, "_waitAudio", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** 振铃提示音播放器 */
- Object.defineProperty(_this, "_ringAudio", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** 结束通话提示音 */
- Object.defineProperty(_this, "_byeAudio", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** 远端音频流播放器 */
- Object.defineProperty(_this, "_remoteAudio", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** CTI状态 */
- Object.defineProperty(_this, "_ctiStatus", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(_this, "_ctiStatusList", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** sip状态 */
- Object.defineProperty(_this, "_sipStatus", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(_this, "_sipStatusList", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- /** socket状态 */
- Object.defineProperty(_this, "_socketStatus", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(_this, "_socketStatusList", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(_this, "_callStatus", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(_this, "_terminatedStatusList", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- _this.loggerLevel = window.ctiLoggerLevel || loggerLevel || exports.LoggerLevels.log;
- _this.logger = new Logger(_this.loggerLevel, 'HsCTI');
- _this._waitAudio = new Audio();
- _this._ringAudio = new Audio();
- _this._byeAudio = new Audio();
- _this._remoteAudio = new Audio();
- _this.saas_id = saas_id;
- _this.agent_id = agent_id;
- _this.scene = scene;
- _this._callId = '';
- setBaseOption(BaseOption.ENV, env);
- setBaseOption(BaseOption.LoggerLevel, _this.loggerLevel);
- _this._baseParams = {
- agent_id: agent_id,
- saas_id: saas_id,
- scene: scene
- };
- var baseTrackParams = {
- agent_id: agent_id,
- vcc_id: saas_id,
- scene: scene
- };
- if (scene === exports.Scene.Monitor) {
- var monitorScene = hsCTIInitOptions.monitorScene;
- _this._baseParams = __assign(__assign({}, _this._baseParams), {
- monitorScene: monitorScene
- });
- setBaseOption(BaseOption.TrackParams, __assign(__assign({}, baseTrackParams), {
- monitor_scene: monitorScene
- }), true);
- } else {
- setBaseOption(BaseOption.TrackParams, baseTrackParams, true);
- }
- _this.initInstanceOptions();
- _this.setCTIStatus(exports.CTIStatus.Initial);
- // 首次获取实例时,将外呼状态置为未开始
- _this._callStatus = exports.CallStatus.Stopped;
- _this._terminatedStatusList = [];
- return _this;
- }
- Object.defineProperty(HsCTI.prototype, "getCTIStatus", {
- get: function () {
- return this._ctiStatus;
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(HsCTI.prototype, "getSocketStatus", {
- get: function () {
- return this._socketStatus;
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(HsCTI.prototype, "getSIPStatus", {
- get: function () {
- return this._sipStatus;
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(HsCTI, "getInstance", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (hsCTIInitOptions) {
- if (!HsCTI.instance) {
- HsCTI.instance = new HsCTI(hsCTIInitOptions);
- }
- setBaseOption(BaseOption.TrackParams, {
- clientId: getClientId()
- });
- return HsCTI.instance;
- }
- });
- /** @private 重置实例 */
- Object.defineProperty(HsCTI.prototype, "initInstanceOptions", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- this._ctiFlowIdList = [];
- this._ctiStatusList = [];
- this._sipStatusList = [];
- this._socketStatusList = [];
- HsCTI.instance = undefined;
- this._initOptions = undefined;
- resetBaseOption();
- }
- });
- /** @private 优雅关闭 SIP 和 socket */
- Object.defineProperty(HsCTI.prototype, "clearSocketAndSip", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- var _a, _b, _c;
- (_a = this._socket) === null || _a === void 0 ? void 0 : _a.closeSocket();
- (_b = this._sipUserAgent) === null || _b === void 0 ? void 0 : _b.unregister();
- (_c = this._sipUserAgent) === null || _c === void 0 ? void 0 : _c.disconnect();
- this._sipUserAgent = undefined;
- }
- });
- /**
- * @private 设置等待音 src
- * @param {AudioName} audioName
- * @param {boolean} loop
- */
- Object.defineProperty(HsCTI.prototype, "setAudioSrc", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (audioName, loop) {
- this.logger.debug("media | \u8BBE\u7F6E\u7B49\u5F85\u97F3 src: ".concat(audioList[audioName]));
- this[audioName].src = audioList[audioName];
- this[audioName].currentTime = 0;
- this[audioName].autoplay = false;
- this[audioName].loop = loop;
- }
- });
- Object.defineProperty(HsCTI.prototype, "playAudio", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (audioName) {
- this.logger.debug("media | \u64AD\u653E\u97F3\u9891\uFF1A".concat(audioName));
- this[audioName].play();
- }
- });
- Object.defineProperty(HsCTI.prototype, "stopLocalAudio", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- switch (this.scene) {
- case exports.Scene.Robot:
- case exports.Scene.Monitor:
- this.stopAudio(AudioName.RingAudio, true);
- break;
- case exports.Scene.Manual:
- this.stopAudio(AudioName.WaitAudio, true);
- break;
- }
- }
- });
- Object.defineProperty(HsCTI.prototype, "stopAudio", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (audioName, loop) {
- var _this = this;
- this.logger.debug("media | \u505C\u6B62\u97F3\u9891\u64AD\u653E\uFF1A".concat(audioName));
- this[audioName].src = '';
- setTimeout(function () {
- _this.setAudioSrc(audioName, loop);
- }, 1000);
- }
- });
- Object.defineProperty(HsCTI.prototype, "init", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- // 不允许重复初始化,必须在销毁sdk后才能重新初始化
- var lastStatus = this._ctiStatusList.slice(-1)[0];
- if (lastStatus !== exports.CTIStatus.Initial) return;
- this.setAudioSrc(AudioName.ByeAudio, false);
- this.setAudioSrc(AudioName.RingAudio, true);
- this.setAudioSrc(AudioName.WaitAudio, true);
- // switch (this.scene) {
- // case Scene.Robot:
- // case Scene.Monitor:
- // this.setAudioSrc(AudioName.RingAudio, true)
- // break
- // case Scene.Manual:
- // this.setAudioSrc(AudioName.WaitAudio, true)
- // break
- // }
- this.getInitConfig();
- }
- });
- Object.defineProperty(HsCTI.prototype, "getInitConfig", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- return __awaiter(this, void 0, void 0, function () {
- var res, code, data, msg, initOptions;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- return [4 /*yield*/, getInitConf(this._baseParams)];
- case 1:
- res = _a.sent();
- code = res.code, data = res.data, msg = res.msg;
- initOptions = data;
- /**
- * 由于后端接口层面对于查询来说,查不到不代表异常,所以即使查不到也是正向流程
- * 因此如果传入一个不存在的agent_id,后端也会返回code=0,但是data=null
- * 这里需要根据code===0&&initOptions存在进行联合判断,只有两个条件都成立,才表示该坐席获取fs以及im等配置成功
- */
- initOptions = __assign(__assign({}, initOptions), {
- imHeartTime: 3,
- // IM 重试次数
- imRetryCount: 3,
- // FS 心跳间隔
- fsHeartTime: 60,
- // FS 重试次数,
- fsRetryCount: 3,
- // FS 重试间隔时间
- fsRetryTime: 60,
- // FS 注册过期时间
- fsRegisterExpireTime: 84000,
- // 单次初始化唯一 ID
- ctiSessionId: generateUniqueId(),
- // IM websocket url
- imWsServer: 'ws://192.168.100.159:8091/ws/cs-im',
- // IM websocket path
- imWsPath: 'ws/cs-im'
- });
- if (code === 0 && initOptions) {
- setBaseOption(BaseOption.TrackParams, {
- sip_server: initOptions.sipServer,
- cti_session_id: initOptions.ctiSessionId
- });
- this._initOptions = initOptions;
- this.initSocket(initOptions);
- this.initSip(initOptions);
- } else {
- this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, {
- type: exports.CTIErrorType.ServerTerminated,
- code: exports.HskTerminatedCode.GetInitConfig,
- // 如果code===0并且initOptions不存在时,代表未查到对应坐席,此时接口返回的msg是空字符串,所以提示文案要特定处理
- msg: code === 0 && !initOptions ? '未查到坐席' : msg,
- method: 'getInitConfig',
- res_code: code
- });
- }
- return [2 /*return*/];
- }
- });
- });
- }
- });
- Object.defineProperty(HsCTI.prototype, "initSocket", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (initOptions) {
- var _this = this;
- this.setSocketStatus({
- status: exports.SocketStatus.Initial
- });
- this._socket = new HsSocket({
- agent_id: this.agent_id,
- saas_id: this.saas_id,
- // appCode: initOptions.appCode,
- imWsServer: initOptions.imWsServer,
- imWsPath: initOptions.imWsPath,
- imHeartTime: initOptions.imHeartTime,
- imRetryCount: initOptions.imRetryCount,
- ctiSessionId: initOptions.ctiSessionId,
- loggerLevel: this.loggerLevel
- });
- this._socket.on(SocketEvent.SocketDownEvent, function (_a) {
- var eventData = _a.eventData;
- var eventName = eventData.eventName,
- ext = eventData.ext;
- _this.logger.log("socket server down | ".concat(eventName, " | ").concat(JSON.stringify(ext)));
- _this.handleSocketDownEvent({
- eventName: eventName,
- ext: ext
- });
- });
- this._socket.on(SocketEvent.SetSocketStatus, function (res) {
- console.log("set socket statussdsdsdsdsdsdds | ".concat(JSON.stringify(res)));
- _this.setSocketStatus(res);
- });
- this._socket.initSocket();
- }
- });
- Object.defineProperty(HsCTI.prototype, "handleSocketDownEvent", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (_a) {
- var eventName = _a.eventName,
- ext = _a.ext;
- var ctiFlowId = this._baseParams.ctiFlowId;
- var extCtiFlowId = ext.ctiFlowId;
- if ([exports.Scene.Manual, exports.Scene.Monitor].includes(this.scene) && ctiFlowId && extCtiFlowId && ctiFlowId !== extCtiFlowId) {
- this.logger.error("cti_flow_id | \u4E0D\u4E00\u81F4! fe: ".concat(ctiFlowId, ", server: ").concat(extCtiFlowId, ", eventName: ").concat(eventName));
- return;
- }
- this.serverEventEmit({
- eventName: eventName,
- ext: ext
- });
- }
- });
- /** @private serverEventEmit 统一处理服务端推送的事件 */
- Object.defineProperty(HsCTI.prototype, "serverEventEmit", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (_a) {
- var eventName = _a.eventName,
- ext = _a.ext;
- var NO_EMIT_EVENT_LIST = [exports.CTIEvent.OnRingStart, exports.CTIEvent.OnDetectedTone, exports.CTIEvent.OnRingEnd];
- switch (eventName) {
- case exports.CTIEvent.OnRingStart:
- this.stopLocalAudio();
- break;
- case exports.CTIEvent.OnDetectedTone:
- this.stopLocalAudio();
- break;
- case exports.CTIEvent.OnAgentWorkReport:
- break;
- case exports.CTIEvent.OnCallEnd:
- /** 通话结束:重置可拨打状态,清空本轮通话的CallId */
- this._callStatus = exports.CallStatus.Stopped;
- setBaseOption(BaseOption.TrackParams, {
- call_id: ''
- });
- console.log('callEndsdsdsdsdsdsd12112323232323');
- break;
- case exports.CTIEvent.OnRingEnd:
- /** TODO: 后 4 个事件未来服务端不再推送时删掉 */
- break;
- // do nothing
- }
- if (!NO_EMIT_EVENT_LIST.includes(eventName)) {
- this.eventEmitAndTrack(eventName, ext);
- }
- }
- });
- Object.defineProperty(HsCTI.prototype, "initSip", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (initOptions) {
- var _this = this;
- this.setSipStatus({
- status: exports.SIPStatus.Initial
- });
- var server = initOptions.wss_server;
- var simpleUserPlusOptions = {
- aor: initOptions.sip_server,
- reconnectionAttempts: initOptions.fsRetryCount,
- reconnectionDelay: initOptions.fsRetryTime,
- optionsPingInterval: initOptions.fsHeartTime,
- media: {
- remote: {
- audio: this._remoteAudio
- }
- },
- userAgentOptions: {
- gracefulShutdown: true,
- authorizationPassword: initOptions.phone_pwd,
- sessionDescriptionHandlerFactoryOptions: {
- constraints: {
- audio: {
- echoCancellation: true,
- noiseSuppression: true,
- autoGainControl: true
- },
- video: false
- },
- peerConnectionConfiguration: {
- // iceServers: []
- iceServers: [{
- urls: initOptions.ice_server
- }]
- }
- }
- }
- };
- simpleUserPlusOptions.delegate = this.sipDelegate();
- this._sipUserAgent = new SimpleUserPlus(server, simpleUserPlusOptions);
- this._sipUserAgent.connect().catch(function (error) {
- var err = "SIP UserAgent \u542F\u52A8\u5931\u8D25\uFF1A".concat(JSON.stringify(error));
- _this.logger.error(err);
- _this.setSipStatus({
- status: exports.SIPStatus.Terminated,
- code: exports.HskTerminatedCode.SIPInitUserAgent,
- error: err,
- method: 'initSIPJS'
- });
- });
- }
- });
- Object.defineProperty(HsCTI.prototype, "sipDelegate", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- var _this = this;
- return {
- onServerConnect: function () {
- _this._sipUserAgent.register();
- },
- onServerDisconnect: function () {
- // 正向关闭UA时会进入此回调
- _this.setSipStatus({
- status: exports.SIPStatus.Terminated
- });
- },
- onReconnectStart: function () {
- // 开始重连时将状态流转为ReTry
- _this.setSipStatus({
- status: exports.SIPStatus.ReTry
- });
- },
- onReconnectFailed: function () {
- // 重连失败时会进如此回调
- _this.setSipStatus({
- status: exports.SIPStatus.Terminated,
- code: exports.HskTerminatedCode.SIPOnDisconnect,
- error: "\u8D85\u8FC7\u91CD\u8FDE\u6B21\u6570\uFF0C\u7EC8\u6B62\u91CD\u8FDE",
- method: 'onReconnectFailed'
- });
- _this.setSipStatus({
- status: exports.SIPStatus.Terminated
- });
- },
- onRegistered: function () {
- _this.setSipStatus({
- status: exports.SIPStatus.Ready
- });
- },
- onUserAgentStateChange: function (state) {
- switch (state) {
- case sip_js.UserAgentState.Started:
- _this.setSipStatus({
- status: exports.SIPStatus.Started
- });
- break;
- case sip_js.UserAgentState.Stopped:
- _this.setSipStatus({
- status: exports.SIPStatus.Terminated,
- code: _this._sipStatusList.includes(exports.SIPStatus.Started) ? exports.HskTerminatedCode.SIPUserAgentStateStopped : exports.HskTerminatedCode.SIPInitUserAgent,
- error: 'SIP UserAgentState 状态停止',
- method: 'onUserAgentStateChange'
- });
- break;
- }
- },
- onInvite: function (invitation) {
- // this.scene = Scene.Robot
- var callId = invitation.request.getHeader('P-LIBRA-CallId') || invitation.request.getHeader('P-LIBRA-Callid') || '';
- console.log(callId, 2888888888);
- // const ctiFlowId =
- // invitation.request.getHeader('P-LIBRA-CtiFlowId') || ''
- // if (ctiFlowId != this._baseParams.ctiFlowId) {
- // this.logger.error(
- // `cti_flow_id 不一致! fe: ${this._baseParams.ctiFlowId} | P-LIBRA-CtiFlowId: ${ctiFlowId}`
- // )
- // return
- // }
- _this._callId = callId;
- console.log(callId, 1888888888);
- setBaseOption(BaseOption.TrackParams, {
- call_id: callId
- });
- _this.sessionStateChangeAndTrack(invitation.state);
- if ([exports.Scene.Robot, exports.Scene.Monitor].includes(_this.scene)) {
- _this.playAudio(AudioName.RingAudio);
- console.log('playAudio', 1888888888);
- }
- if ([exports.Scene.Manual].includes(_this.scene)) {
- _this.answer();
- console.log('answer', 1888888888);
- }
- invitation.delegate = {
- onCancel: function (cancel) {
- var error = "sip_invitation_on_cancel | ".concat(JSON.stringify(cancel));
- _this.logger.error(error);
- _this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, {
- type: exports.CTIErrorType.SdkError,
- code: exports.SdkErrorCode.InvitationCancel,
- msg: '当前通话已结束',
- method: 'sipDelegate'
- }, error);
- }
- };
- invitation.stateChange.addListener(function (state) {
- _this.sessionStateChangeAndTrack(state);
- switch (state) {
- case sip_js.SessionState.Initial:
- case sip_js.SessionState.Establishing:
- break;
- case sip_js.SessionState.Established:
- if ([exports.Scene.Robot, exports.Scene.Monitor].includes(_this.scene)) {
- _this.stopLocalAudio();
- }
- break;
- case sip_js.SessionState.Terminating:
- break;
- case sip_js.SessionState.Terminated:
- _this.playAudio(AudioName.ByeAudio);
- setTimeout(function () {
- _this.stopAudio(AudioName.ByeAudio, false);
- }, 1000);
- _this.stopLocalAudio();
- // this._baseParams.scene = Scene.Manual
- setBaseOption(BaseOption.TrackParams, {
- call_id: ''
- });
- if (_this.scene == exports.Scene.Manual) {
- _this.scene = exports.Scene.Robot;
- _this._baseParams.scene = exports.Scene.Robot;
- }
- break;
- }
- });
- }
- };
- }
- });
- Object.defineProperty(HsCTI.prototype, "sessionStateChangeAndTrack", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (status) {
- this.eventEmitAndTrack(exports.CTIEvent.OnSessionStatusChange, {
- status: status
- });
- var trackName = "sip_session_state_".concat(upperCamelToLowerSnake(status));
- this.logger.log(trackName);
- }
- });
- /**
- * @private setCTIStatus CTI 状态流转
- * @param {CTIStatus} ctiStatus
- */
- Object.defineProperty(HsCTI.prototype, "setCTIStatus", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (ctiStatus) {
- if (ctiStatus === this.getCTIStatus) return;
- this._ctiStatus = ctiStatus;
- this._ctiStatusList.push(ctiStatus);
- var logInfo = "cti status | ".concat(ctiStatus, " | ").concat(this._ctiStatusList);
- if (ctiStatus === exports.CTIStatus.Terminated) {
- this.setSocketStatus({
- status: exports.SocketStatus.Terminated
- });
- this.setSipStatus({
- status: exports.SIPStatus.Terminated
- });
- this.stopLocalAudio();
- this.logger.warn(logInfo);
- } else {
- this.logger.debug(logInfo);
- }
- if (ctiStatus === exports.CTIStatus.Ready) {
- this.setSocketStatus({
- status: exports.SocketStatus.Ready
- });
- this.setSipStatus({
- status: exports.SIPStatus.Ready
- });
- this._terminatedStatusList = [];
- if (!this._ctiStatusList.includes(exports.CTIStatus.ReTry)) {
- this.checkIn();
- }
- }
- }
- });
- /**
- * @private setSocketStatus Socket 状态流转
- * @param SocketStatusChangeParams Socket 状态流转参数及错误详情等
- */
- Object.defineProperty(HsCTI.prototype, "setSocketStatus", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (_a) {
- var status = _a.status,
- code = _a.code,
- error = _a.error;
- if (status === this.getSocketStatus) return;
- this._socketStatus = status;
- this._socketStatusList.push(status);
- var logInfo = "socket status | ".concat(status, " | ").concat(this._socketStatusList);
- status === exports.SocketStatus.Terminated ? this.logger.warn(logInfo) : this.logger.debug(logInfo);
- this.socketOrSipStatusChange(status, this.getSIPStatus);
- if (error) {
- this._terminatedStatusList.push(code);
- this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, {
- type: exports.CTIErrorType.SdkTerminated,
- code: code,
- msg: code === exports.HskTerminatedCode.SocketRepeatLogin ? ExceptMessage.CTIRepeatLoginMsg : ExceptMessage.CommonNetworkErrorMsg,
- method: 'setSocketStatus'
- }, {
- error_msg: error,
- socket_status_list: this._socketStatusList,
- sip_status_list: this._sipStatusList,
- cti_status_list: this._ctiStatusList
- });
- this.clearSocketAndSip();
- }
- }
- });
- /**
- * @private setSipStatus SIP 状态流转
- * @param SIPStatusChangeParams SIP 状态流转参数及错误详情等
- */
- Object.defineProperty(HsCTI.prototype, "setSipStatus", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (_a) {
- var status = _a.status,
- code = _a.code,
- error = _a.error,
- method = _a.method;
- if (status === this.getSIPStatus) return;
- this._sipStatus = status;
- this._sipStatusList.push(status);
- var logInfo = "sip status | ".concat(status, " | ").concat(this._sipStatusList);
- status === exports.SIPStatus.Terminated ? this.logger.warn(logInfo) : this.logger.debug(logInfo);
- this.socketOrSipStatusChange(this.getSocketStatus, status);
- if (error) {
- /** 抛出 SIP 类型的错误详情 */
- this._terminatedStatusList.push(code);
- this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, {
- type: exports.CTIErrorType.SdkTerminated,
- code: code,
- msg: ExceptMessage.CommonNetworkErrorMsg,
- method: method || 'setSipStatus'
- }, {
- error_msg: error,
- socket_status_list: this._socketStatusList,
- sip_status_list: this._sipStatusList,
- cti_status_list: this._ctiStatusList
- });
- this.clearSocketAndSip();
- }
- }
- });
- /**
- * @private socketOrSipStatusChange Socket 或 SIP 状态变化可能引起 CTI 状态变化
- * @param {SocketStatus} socketStatus
- * @param {SIPStatus} sipStatus
- */
- Object.defineProperty(HsCTI.prototype, "socketOrSipStatusChange", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (socketStatus, sipStatus) {
- if (socketStatus === exports.SocketStatus.Ready && sipStatus === exports.SIPStatus.Ready) {
- this.setCTIStatus(exports.CTIStatus.Ready);
- }
- // if (socketStatus === SocketStatus.Ready) {
- // this.setCTIStatus(CTIStatus.Ready)
- // }
- if (socketStatus === exports.SocketStatus.ReTry || sipStatus === exports.SIPStatus.ReTry) {
- this.setCTIStatus(exports.CTIStatus.ReTry);
- }
- if (socketStatus === exports.SocketStatus.Terminated || sipStatus === exports.SIPStatus.Terminated) {
- this.setCTIStatus(exports.CTIStatus.Terminated);
- }
- }
- });
- /**
- * @private eventEmitAndTrack SDK 对外抛出事件并统一埋点
- * @param {CTIEvent} eventName 事件名称
- * @param {object} ext 事件参数
- * @param { error } error 错误详情或错误辅助信息
- */
- Object.defineProperty(HsCTI.prototype, "eventEmitAndTrack", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (eventName, ext, error) {
- this.logger.debug("sdk emit | ".concat(eventName, " | ").concat(JSON.stringify(ext)));
- // 如果出现异常,则将通话状态置为结束
- if (eventName === exports.CTIEvent.OnCtiError) {
- this._callStatus = exports.CallStatus.Stopped;
- }
- try {
- this.emit(eventName, ext);
- console.log(error);
- } catch (error) {
- this.logger.error("\u4E1A\u52A1\u76D1\u542C ".concat(eventName, " \u4E8B\u4EF6\uFF0C\u5904\u7406\u56DE\u8C03\u65F6\u62A5\u9519: ").concat(error));
- }
- }
- });
- /** @private checkIn 服务端签入,CTIStatus Ready 时自动调用,坐席状态变更 */
- Object.defineProperty(HsCTI.prototype, "checkIn", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- return __awaiter(this, void 0, void 0, function () {
- var res;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- return [4 /*yield*/, agentCheckIn(this._baseParams)];
- case 1:
- res = _a.sent();
- if (res.code === 0) {
- this.eventEmitAndTrack(exports.CTIEvent.OnInitalSuccess, {
- saas_id: this.saas_id,
- agent_id: this.agent_id,
- scene: this.scene,
- phoneNum: this._initOptions.phone_num,
- sipServer: this._initOptions.sip_server
- });
- }
- return [2 /*return*/, res];
- }
- });
- });
- }
- });
- /** @public checkOut 服务端签出, unInit 时自动调用,坐席状态变更 */
- Object.defineProperty(HsCTI.prototype, "checkOut", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- return [4 /*yield*/, agentCheckOut(this._baseParams)];
- case 1:
- return [2 /*return*/, _a.sent()];
- }
- });
- });
- }
- });
- /** @private _getCtiFlowId 获取手动外呼场景需要的 ctiFlowId */
- Object.defineProperty(HsCTI.prototype, "getCtiFlowId", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- return __awaiter(this, void 0, void 0, function () {
- var res, code, data;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- return [4 /*yield*/, getCtiFlowId(this._baseParams)];
- case 1:
- res = _a.sent();
- code = res.code, data = res.data;
- if (code === 0) {
- this._baseParams.ctiFlowId = data;
- this._ctiFlowIdList.push(data);
- setBaseOption(BaseOption.TrackParams, {
- cti_flow_id: data,
- cti_flow_id_list: JSON.stringify(this._ctiFlowIdList)
- });
- }
- return [2 /*return*/, res];
- }
- });
- });
- }
- });
- /** @public setIdle 服务端置闲,坐席状态变更 */
- Object.defineProperty(HsCTI.prototype, "setIdle", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- this.scene = exports.Scene.Robot;
- this._baseParams.scene = exports.Scene.Robot;
- return [4 /*yield*/, agentSetIdle(this._baseParams)];
- case 1:
- return [2 /*return*/, _a.sent()];
- }
- });
- });
- }
- });
- /** @public setBusy 服务端置忙,坐席状态变更 */
- Object.defineProperty(HsCTI.prototype, "setBusy", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- return [4 /*yield*/, agentSetBusy(this._baseParams)];
- case 1:
- return [2 /*return*/, _a.sent()];
- }
- });
- });
- }
- });
- Object.defineProperty(HsCTI.prototype, "makeCall", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (params) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- this.scene = exports.Scene.Manual;
- this._baseParams.scene = exports.Scene.Manual;
- // 如果当前通话状态处于外呼开始,则不允许再次调用此方法并上报埋点
- if (this._callStatus === exports.CallStatus.Started) {
- return [2 /*return*/];
- }
- this._callStatus = exports.CallStatus.Started;
- return [4 /*yield*/, this.getCtiFlowId()];
- case 1:
- _a.sent();
- this.playAudio(AudioName.WaitAudio);
- return [4 /*yield*/, this.serverCall(params)];
- case 2:
- return [2 /*return*/, _a.sent()];
- }
- });
- });
- }
- });
- Object.defineProperty(HsCTI.prototype, "serverCall", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (_a) {
- var called = _a.called,
- caller = _a.caller,
- ext = _a.ext;
- return __awaiter(this, void 0, void 0, function () {
- var params, res, code, data;
- return __generator(this, function (_b) {
- switch (_b.label) {
- case 0:
- params = __assign(__assign(__assign({}, this._baseParams), {
- called: called,
- caller: caller
- }), ext);
- return [4 /*yield*/, manualCall(params)];
- case 1:
- res = _b.sent();
- code = res.code, data = res.data;
- if (code === 0) {
- if (this._callId === '' && data) {
- this._callId = data;
- setBaseOption(BaseOption.TrackParams, {
- call_id: data
- });
- }
- } else {
- // 外呼接口调用失败将通话状态置为结束不阻碍下次外呼
- this._callStatus = exports.CallStatus.Stopped;
- this.stopLocalAudio();
- }
- return [2 /*return*/, res];
- }
- });
- });
- }
- });
- /** @public answer SDK SIP 接起 */
- Object.defineProperty(HsCTI.prototype, "answer", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- var _this = this;
- return new Promise(function (resolve, reject) {
- var _a;
- (_a = _this._sipUserAgent) === null || _a === void 0 ? void 0 : _a.answer({
- sessionDescriptionHandlerOptions: {
- constraints: {
- audio: true,
- video: false
- }
- }
- }).then(function () {
- resolve({
- code: 0,
- data: 'answer',
- msg: 'SIP 接起电话成功'
- });
- _this.logger.debug('sip_accept_success');
- }).catch(function (err) {
- var errorData = {
- type: exports.CTIErrorType.SdkError,
- code: exports.SdkErrorCode.Answer,
- msg: _this.scene === exports.Scene.Manual ? ExceptMessage.ManualCallAnswerErrorMsg : ExceptMessage.RobotOrWeChatAnswerErrorMsg,
- method: 'answer'
- };
- reject(errorData);
- _this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, errorData, "".concat(err));
- _this.logger.error("".concat(exports.CTIEvent.OnCtiError, " | ").concat(err));
- });
- });
- }
- });
- /** @public bye SDK SIP 挂断 */
- Object.defineProperty(HsCTI.prototype, "bye", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- var _this = this;
- return new Promise(function (resolve, reject) {
- var _a;
- (_a = _this._sipUserAgent) === null || _a === void 0 ? void 0 : _a.hangup().then(function () {
- resolve({
- code: 0,
- data: 'bye',
- msg: 'SIP 挂断电话成功'
- });
- _this.logger.debug('sip_bye_success');
- }).catch(function (err) {
- var errorData = {
- type: exports.CTIErrorType.SdkError,
- code: exports.SdkErrorCode.Bye,
- msg: ExceptMessage.SipByeErrorMsg,
- method: 'bye'
- };
- reject(errorData);
- if (err.message !== 'Session does not exist.') {
- _this.eventEmitAndTrack(exports.CTIEvent.OnCtiError, errorData, "".concat(err));
- }
- _this.logger.error("".concat(exports.CTIEvent.OnCtiError, " | ").concat(err));
- });
- });
- }
- });
- /** @public serverBye 挂断且流转坐席状态 */
- Object.defineProperty(HsCTI.prototype, "serverBye", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- return __awaiter(this, void 0, void 0, function () {
- var res, error_1;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- _a.trys.push([0, 2,, 3]);
- this.bye();
- return [4 /*yield*/, this.turnHang()];
- case 1:
- res = _a.sent();
- return [2 /*return*/, Promise.resolve(res)];
- case 2:
- error_1 = _a.sent();
- return [2 /*return*/, Promise.reject(error_1)];
- case 3:
- return [2 /*return*/];
- }
- });
- });
- }
- });
- /** @public turnHang 流转坐席状态-通话结束 */
- Object.defineProperty(HsCTI.prototype, "turnHang", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- return __awaiter(this, void 0, void 0, function () {
- var res;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- return [4 /*yield*/, manualHang(__assign(__assign({}, this._baseParams), {
- call_id: this._callId
- }))];
- case 1:
- res = _a.sent();
- this._callId = '';
- return [2 /*return*/, res];
- }
- });
- });
- }
- });
- /** @public getAgentStatus 获取坐席状态 */
- Object.defineProperty(HsCTI.prototype, "getAgentStatus", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- return [4 /*yield*/, getAgentStatus(this._baseParams)];
- case 1:
- return [2 /*return*/, _a.sent()];
- }
- });
- });
- }
- });
- /**
- * @public loadAgentGroupData 监听-根据监听组 ID 获取监听组成员
- * @param {string[]} monitorIds
- */
- Object.defineProperty(HsCTI.prototype, "loadAgentGroupData", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (monitorIds) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- return [4 /*yield*/, loadAgentGroupData(__assign(__assign({}, this._baseParams), {
- monitorIds: monitorIds
- }))];
- case 1:
- return [2 /*return*/, _a.sent()];
- }
- });
- });
- }
- });
- /**
- * @public listen 监听-服务端发起监听
- * @param {string} monitoredAgNo
- */
- Object.defineProperty(HsCTI.prototype, "listen", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (monitoredAgNo) {
- return __awaiter(this, void 0, void 0, function () {
- var flowIdRes;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- return [4 /*yield*/, this.getCtiFlowId()];
- case 1:
- flowIdRes = _a.sent();
- if (flowIdRes && flowIdRes.code !== 0) {
- return [2 /*return*/, flowIdRes];
- }
- return [4 /*yield*/, listen(__assign(__assign({}, this._baseParams), {
- agent_id: monitoredAgNo,
- leaderAgentId: this.agent_id
- }))];
- case 2:
- return [2 /*return*/, _a.sent()];
- }
- });
- });
- }
- });
- /**
- * @public setActiveService 机器人外呼-签入人工组
- * @param {string} serviceId
- */
- Object.defineProperty(HsCTI.prototype, "setActiveService", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function (serviceId) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- return [4 /*yield*/, setActiveServiceTask(__assign(__assign({}, this._baseParams), {
- serviceId: serviceId
- }))];
- case 1:
- return [2 /*return*/, _a.sent()];
- }
- });
- });
- }
- });
- /** @public unInit 卸载 SDK,checkOut 成功后断开 socket 和 sip 连接,并销毁 SdCTI 实例 */
- Object.defineProperty(HsCTI.prototype, "unInit", {
- enumerable: false,
- configurable: true,
- writable: true,
- value: function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- return [4 /*yield*/, this.checkOut()];
- case 1:
- _a.sent();
- this.setCTIStatus(exports.CTIStatus.Terminated);
- this.initInstanceOptions();
- this.clearSocketAndSip();
- this._callId = '';
- return [2 /*return*/];
- }
- });
- });
- }
- });
- __decorate([getUserMedia()], HsCTI.prototype, "init", null);
- __decorate([checkCTIStatus('签入'), handleApiRes()], HsCTI.prototype, "checkIn", null);
- __decorate([checkCTIStatus('签出'), handleApiRes()], HsCTI.prototype, "checkOut", null);
- __decorate([handleApiRes()], HsCTI.prototype, "getCtiFlowId", null);
- __decorate([checkCTIStatus('置闲'), handleApiRes()], HsCTI.prototype, "setIdle", null);
- __decorate([checkCTIStatus('置忙'), handleApiRes()], HsCTI.prototype, "setBusy", null);
- __decorate([checkCTIStatus('人工外呼')], HsCTI.prototype, "makeCall", null);
- __decorate([handleApiRes()], HsCTI.prototype, "serverCall", null);
- __decorate([checkCTIStatus('接起')], HsCTI.prototype, "answer", null);
- __decorate([checkCTIStatus('挂断')], HsCTI.prototype, "bye", null);
- __decorate([handleApiRes()], HsCTI.prototype, "turnHang", null);
- __decorate([handleApiRes()], HsCTI.prototype, "getAgentStatus", null);
- __decorate([checkCTIStatus('获取监听组成员'), handleApiRes()], HsCTI.prototype, "loadAgentGroupData", null);
- __decorate([checkCTIStatus('坐席监听'), handleApiRes()], HsCTI.prototype, "listen", null);
- __decorate([checkCTIStatus('签入人工组'), handleApiRes()], HsCTI.prototype, "setActiveService", null);
- __decorate([validateParams()], HsCTI, "getInstance", null);
- return HsCTI;
- }(EventEmitter);
- /**
- * @function getInstance 获取 HsCTI 的实例
- * @param HsCTIInitOptions 初始化 HsCTI 的配置
- */
- var getInstance = function (HsCTIInitOptions) {
- return HsCTI.getInstance(HsCTIInitOptions);
- };
- exports.Logger = Logger;
- exports.getInstance = getInstance;
- }));
|