hs-cti.es5.esm.js 183 KB

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